404 error redirect in Spring with java config

前端 未结 9 1196
-上瘾入骨i
-上瘾入骨i 2020-11-27 04:46

As you know, in XML, the way to configure this is:


    404
    /my-custom-page-not-fo         


        
9条回答
  •  旧时难觅i
    2020-11-27 04:57

    The most clean solution since spring 4.2 RC3 is using the new createDispatcherServlet hook within the class extending AbstractDispatcherServletInitializer (or indirectly through extending AbstractAnnotationConfigDispatcherServletInitializer) like this:

    public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
        @Override
        protected Class[] getRootConfigClasses() {
            return null;
        }
    
        /* ... */
    
        @Override
        protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
            final DispatcherServlet dispatcherServlet = super.createDispatcherServlet(servletAppContext);
            dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
            return dispatcherServlet;
        }
    }
    

    Then you can use a global @ControllerAdvice (a class that is annotated with @ControllerAdvice) as described in the reference docs. Within the advice you can handle the NoHandlerFoundException with an @ExceptionHandler as described here.

    This could look something like this:

    @ControllerAdvice
    public class NoHandlerFoundControllerAdvice {
    
        @ExceptionHandler(NoHandlerFoundException.class)
        public ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException ex) {
            // prepare responseEntity
            return responseEntity;
        }
    
    }
    

提交回复
热议问题