![](/img/trans.png)
[英]how to display custom error message in jsp for spring security auth exception
[英]Display exception message handled by Spring using JSP
我在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中显示此消息。
为了解决这两个问题(显示消息并具有正确的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;
}
为什么? 如果希望属性通过重定向保留,则需要将其添加到Flash作用域。 上面的代码使用了来自文档的FlashMap
FlashMap在重定向之前(通常在会话中)保存,并在重定向后可用,并立即删除。
如果它是普通的控制器方法,则可以简单地添加RedirectAttributes作为参数,但是在@ExceptionHandler方法上,不能解析RedirectAttributes的参数,因此您需要添加HttpServletRequest并使用RedirectView。
您必须将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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.