404 error redirect in Spring with java config

前端 未结 9 1191
-上瘾入骨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条回答
  •  被撕碎了的回忆
    2020-11-27 04:55

    A solution for Spring 5 and Thymeleaf 3.

    In MyWebInitializer, enable exception throwing with setThrowExceptionIfNoHandlerFound(). We need to do casting to DispatcherServlet.

    @Configuration
    public class MyWebInitializer extends
            AbstractAnnotationConfigDispatcherServletInitializer {
    
            ...
    
            @Override
            protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
                var dispatcher = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
                dispatcher.setThrowExceptionIfNoHandlerFound(true);
                return dispatcher;
            }
        }
    

    Create a controller advice with @ControllerAdvice and add error message to the ModealAndView.

    @ControllerAdvice
    public class ControllerAdvisor {
    
        @ExceptionHandler(NoHandlerFoundException.class)
        public ModelAndView handle(Exception ex) {
    
            var mv = new ModelAndView();
            mv.addObject("message", ex.getMessage());
            mv.setViewName("error/404");
    
            return mv;
        }
    }
    

    Create 404 error template, which displays the error message. Based on my configuration, the file is src/main/resources/templates/error/404.html.

    
    
    
        
        
        Resource not found
    
    
    
    

    404 - resource not found

    For completeness, I add the Thymeleaf resolver configuration. We configure the Thymeleaf templates to be in templates directory on the classpath.

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = {"com.zetcode"})
    public class WebConfig implements WebMvcConfigurer {
    
        @Autowired
        private ApplicationContext applicationContext;
    
        ...
    
        @Bean
        public SpringResourceTemplateResolver templateResolver() {
    
            var templateResolver = new SpringResourceTemplateResolver();
    
            templateResolver.setApplicationContext(applicationContext);
            templateResolver.setPrefix("classpath:/templates/");
            templateResolver.setSuffix(".html");
    
            return templateResolver;
        }
        ...
    }
    

提交回复
热议问题