我想要以下方法:
@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
编辑2 :
这是我修改过的处理程序方法:
@ExceptionHandler(InvalidTokenException.class)
public String invalidTokenException(InvalidTokenException e, HttpSession session) {
session.setAttribute("message", "invalid token/member not found");// TODO:i18n
return "redirect:../signin";
}
我现在遇到的问题是消息卡在会话中......
答案 0 :(得分:24)
请注意,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>
希望它有所帮助!
答案 1 :(得分:6)
您可以随时转发然后重定向(或重定向两次).. 首先是另一个请求映射,您可以正常访问RedirectAttributes,然后再次访问最终目的地。
@ExceptionHandler(Exception.class)
public String handleException(final Exception e) {
return "forward:/n/error";
}
@RequestMapping(value = "/n/error", method = RequestMethod.GET)
public String error(final RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute("foo", "baz");
return "redirect:/final-destination";
}
答案 2 :(得分:2)
我正在查看JavaDoc,但我看不到RedirectAttributes是一个被接受的有效类型。
答案 3 :(得分:2)
从Spring 4.3.5开始(SPR-14651)你可以直接使用你的第一个方法:
@ExceptionHandler(MyRuntimeException.class)
public String myRuntimeException(MyRuntimeException e, RedirectAttributes redirectAttrs){
redirectAttrs.addFlashAttribute("error", e);
return "redirect:someView";
}