Using Spring MVC 3.1+ WebApplicationInitializer to programmatically configure session-config and error-page

后端 未结 5 2132
迷失自我
迷失自我 2020-12-14 18:19

WebApplicationInitializer provides a way to programmatically represent a good portion of a standard web.xml file - the servlets, filters, listeners.

However I have

5条回答
  •  不思量自难忘°
    2020-12-14 18:35

    Extending on BwithLove comment, you can define 404 error page using exception and controller method which is @ExceptionHandler:

    1. Enable throwing NoHandlerFoundException in DispatcherServlet.
    2. Use @ControllerAdvice and @ExceptionHandler in controller.

    WebAppInitializer class:

    public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        DispatcherServlet dispatcherServlet = new DispatcherServlet(getContext());
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", dispatcherServlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }
    
    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("com.my.config");
        context.scan("com.my.controllers");
        return context;
    }
    }
    

    Controller class:

    @Controller
    @ControllerAdvice
    public class MainController {
    
        @RequestMapping(value = "/")
        public String whenStart() {
            return "index";
        }
    
    
        @ExceptionHandler(NoHandlerFoundException.class)
        @ResponseStatus(value = HttpStatus.NOT_FOUND)
        public String requestHandlingNoHandlerFound(HttpServletRequest req, NoHandlerFoundException ex) {
            return "error404";
        }
    }
    

    "error404" is a JSP file.

提交回复
热议问题