使用JSP显示Spring处理的异常消息

时间:2014-12-22 10:56:23

标签: java spring jsp spring-mvc

我是Spring的新手,也是JSP的新手。我正在项目中工作,我需要创建一个页面,在特定例外的情况下,应用程序将被重定向。 我有服务的方法,抛出一个例外。使用@RequestMapping注释在我们的页面控制器之一中调用此方法。因此,为了重定向到特定的错误页面,我使用@ExceptionHanlder创建了两个方法,它们在此控制器中处理此异常。看起来如何:

@ExceptionHandler(IllegalStateException.class)
public ModelAndView handleIllegalStateException (IllegalStateException ex) {
    ModelAndView modelAndView =  new ModelAndView("redirect:/error");
    modelAndView.addObject("exceptionMsg", ex.getMessage());
    return modelAndView;
}

但还不够。我还需要创建ErrorPageController:

@Controller
@RequestMapping("/error")
public class ErrorPageController {
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView displayErrorPage() {
        return new ModelAndView("error");
    }
}

现在可以显示错误页面。但我的问题是,我无法在JSP中显示错误消息... 我有:

<h3>Error page: "${exceptionMsg}"</h3>

但是我没有看到消息; /而不是它,我在URL中看到消息:

localhost/error?exceptionMsg=Cannot+change+participation+status+if+the+event+is+cancelled+or+it+has+ended.

这是错误的,因为在URL中我只想要一个“localhost / error”而已。我希望在JSP中显示此消息。

2 个答案:

答案 0 :(得分:3)

要修复两个问题(显示消息,并有正确的URL),您应该在原始代码中将异常处理程序方法更改为例如。

@ExceptionHandler(IllegalStateException.class)
public RedirectView handleIllegalStateException(IllegalStateException ex, HttpServletRequest request) {
    RedirectView rw = new RedirectView("/error");
    FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
    if (outputFlashMap != null) {
        outputFlashMap.put("exceptionMsg", ex.getMessage());
    }
    return rw;
}

为什么呢?如果希望通过重定向保留属性,则需要将它们添加到闪存范围。上面的代码使用了文档中的FlashMap

  

FlashMap在重定向之前保存(通常在会话中)和   在重定向后可用并立即删除。

如果它是一个普通的控制器方法,你可以简单地添加RedirectAttributes作为参数,但是在@ExceptionHandler方法中,RedirectAttributes的参数没有被解析,所以你需要添加HttpServletRequest并使用RedirectView。

答案 1 :(得分:2)

您必须将ModelAndView更改为:

@ExceptionHandler(IllegalStateException.class)
public ModelAndView handleIllegalStateException (IllegalStateException ex) {
    ModelAndView modelAndView =  new ModelAndView("error");
    modelAndView.addObject("exceptionMsg", ex.getMessage());
    return modelAndView;
}

将此部分放在error.jsp:

<h3>Error page: "${exceptionMsg}"</h3>