【问题标题】:redirecting to the controller's action from exception handler once it caught by the exception?一旦被异常捕获,从异常处理程序重定向到控制器的操作?
【发布时间】:2018-09-20 16:59:11
【问题描述】:

我使用以下代码从异常处理程序重定向到控制器的操作,它正在工作,但 flowid 被附加到客户端浏览器的 URL。如果没有那个flowid,有没有其他方法可以做到这一点?您也可以在下面看到 URL 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;
      }

【问题讨论】:

    标签: java spring response.redirect


    【解决方案1】:

    您可以使用 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;
          }
    

    【讨论】:

    • 如何在重定向前设置属性使重定向url方法可用??
    【解决方案2】:

    这是spring redirect 的默认行为。您可以按照以下步骤进行更改:

    • ---基于 XML 的配置---*

      对于基于XML 的配置,只需在您的custom servlet xml configuration 中添加<mvc:annotation-driven ignoreDefaultModelOnRedirect="true" />

    • ---基于Java的配置---

      您可以自动装配现有的RequestMappingHandlerAdapter 并将默认的IgnoreDefaultModelOnRedirect 属性设置为true,如下所示-

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

    现在您可以使用与示例中用于redirect 相同的ModelAndView

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多