redirecting to the controller's action from exception handler once it caught by the exception?

Viewed 203

i have used following code to redirect to controller's action from the exception handler, it is working but flowid is getting appended to the browser's URL in the client side. is there any alternative way to do this without having that flowid? you can see the URL as well below http://localhost:8080/sample/home?flowId=fd19e86a-d9f8-485c-858c-41bcc5a10cd9

@ExceptionHandler(DataAccessException.class)
public ModelAndView handleError(HttpServletRequest req, DataAccessExceptionex) {
        logger.error("Request: " + req.getRequestURL() + " raised " + ex);

        ModelAndView mav = new ModelAndView("redirect:/home");
        mav.addObject("exception", ex);
        mav.addObject("url", req.getRequestURL());
       return mav;
      }
2 Answers

You can use the HttpServletResponse.sendRedirect():

    @ExceptionHandler(DataAccessException.class)
    public ModelAndView handleError(HttpServletRequest req, final HttpServletResponse response, DataAccessException ex) {
        logger.error("Request: " + req.getRequestURL() + " raised " + ex);

        response.sendRedirect("/sample");

        return null;
      }

This is the default behaviour of spring redirect. You can change the same following the below steps:

  • ---XML Based Configurations---*:

    For XML based configurations, just add <mvc:annotation-driven ignoreDefaultModelOnRedirect="true" /> in your custom servlet xml configuration.

  • ---Java Based Configuration---:

    You can autowired the existing RequestMappingHandlerAdapter and set the default IgnoreDefaultModelOnRedirect property as true pointed out in as follows-

     @EnableWebMvc
     @Configuration
     public class CustomWebConfig {
         @Autowired
         private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
    
         @PostConstruct
         public void init() {
            requestMappingHandlerAdapter.setIgnoreDefaultModelOnRedirect(true);
         }
     }
    

Now you can use the same ModelAndView as you used in your example for the redirect.

Related