How to handle exceptions thrown while rendering a view in Spring MVC?

后端 未结 3 1837
失恋的感觉
失恋的感觉 2020-12-05 02:47

I have a Spring MVC application which uses FreeMarker as View technology (But maybe the view technology doesn\'t really matter for my question). I need to intercept all exce

3条回答
  •  心在旅途
    2020-12-05 03:12

    You could extends the DispatcherServlet.

    In your web.xml replace the generic DispatcherServlet for your own class.

    
        springmvc
        com.controller.generic.DispatcherServletHandler
        1
    
    

    Later create your own class DispatcherServletHandler and extends from DispatcherServlet:

    public class DispatcherServletHandler extends DispatcherServlet {
    
        private static final String ERROR = "error";
        private static final String VIEW_ERROR_PAGE = "/WEB-INF/views/error/view-error.jsp";
    
        @Override
        protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
            try{
                super.doService(request, response);
            } catch(Exception ex) {
                request.setAttribute(ERROR, ex);
                request.getRequestDispatcher(VIEW_ERROR_PAGE).forward(request, response);
            }
         }
    }
    

    And in that page we only have to show a message to the user.

提交回复
热议问题