Performing a redirect from a spring MVC @ExceptionHandler method

后端 未结 4 817
心在旅途
心在旅途 2021-02-07 10:49

I want to have the following method:

@ExceptionHandler(MyRuntimeException.class)
public String myRuntimeException(MyRuntimeException e, RedirectAttributes redire         


        
相关标签:
4条回答
  • 2021-02-07 10:58

    Note that this is actually supported out-of-the-box by Spring 4.3.5+ (see SPR-14651 for more details).

    I've managed to get it working using the RequestContextUtils class. My code looks like this

    @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;
    }
    

    Then in the jsp page I simply access the attribute

    <c:if test="${myAttribute}">
        <script type="text/javascript">
          // other stuff here
        </script>
    </c:if>
    

    Hope it helps!

    0 讨论(0)
  • 2021-02-07 10:59

    Since Spring 4.3.5 (SPR-14651) you can use stright away your first aproach:

    @ExceptionHandler(MyRuntimeException.class)
    public String myRuntimeException(MyRuntimeException e, RedirectAttributes redirectAttrs){
        redirectAttrs.addFlashAttribute("error", e);
        return "redirect:someView";
    }
    
    0 讨论(0)
  • 2021-02-07 11:09

    I am looking at the JavaDoc and I don't see where RedirectAttributes is a valid type that is accepted.

    0 讨论(0)
  • 2021-02-07 11:12

    You could always forward then redirect (or redirect twice).. First to another request mapping where you have normal access to RedirectAttributes, then again to your final destination.

        @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";
        }
    
    0 讨论(0)
提交回复
热议问题