从Spring MVC @ExceptionHandler方法执行重定向
我想要以下方法:
@ExceptionHandler(MyRuntimeException.class)public String myRuntimeException(MyRuntimeException e, RedirectAttributes redirectAttrs){//does not work
redirectAttrs.addFlashAttribute("error", e);
return "redirect:someView";
}
我得到:
java.lang.IllegalStateException: No suitable resolver for argument [1] type=org.springframework.web.servlet.mvc.support.RedirectAttributes]
有没有一种方法可以从重定向@ExceptionHandler
?也许有某种方法可以规避这一限制?
我修改了异常处理程序,如下所示:
@ExceptionHandler(InvalidTokenException.class)public ModelAndView invalidTokenException(InvalidTokenException e, HttpServletRequest request) {
RedirectView redirectView = new RedirectView("signin");
return new ModelAndView(redirectView , "message", "invalid token/member not found");//TODO:i18n
}
这是可能引发异常的方法:
@RequestMapping(value = "/activateMember/{token}", method = RequestMethod.GET, produces = "text/html")public String activateMember(@PathVariable("token") String token) {
signupService.activateMember(token);
return "redirect:memberArea/index";
}
我修改后的异常处理程序的问题是它系统地将我重定向到以下URL:
http://localhost:8080/bignibou/activateMember/signin?message=invalid+token%2Fmember+not+found
代替:
http://localhost:8080/bignibou/signin?message=invalid+token%2Fmember+not+found
:
这是我修改后的处理程序方法:
@ExceptionHandler(InvalidTokenException.class)public String invalidTokenException(InvalidTokenException e, HttpSession session) {
session.setAttribute("message", "invalid token/member not found");// TODO:i18n
return "redirect:../signin";
}
我现在遇到的问题是消息卡在了会话中…
回答:
请注意,Spring
4.3.5+实际上是开箱即用的(有关更多详细信息,请参阅SPR-14651)。
我已经设法使用RequestContextUtils类使其工作。我的代码看起来像这样
@ExceptionHandler(MyException.class)public RedirectView handleMyException(MyException ex,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String redirect = getRedirectUrl(currentHomepageId);
RedirectView rw = new RedirectView(redirect);
rw.setStatusCode(HttpStatus.MOVED_PERMANENTLY); // you might not need this
FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
if (outputFlashMap != null){
outputFlashMap.put("myAttribute", true);
}
return rw;
}
然后在jsp页面中,我只需访问属性
<c:if test="${myAttribute}"> <script type="text/javascript">
// other stuff here
</script>
</c:if>
希望能帮助到你!
以上是 从Spring MVC @ExceptionHandler方法执行重定向 的全部内容, 来源链接: utcz.com/qa/424355.html