404 error redirect in Spring with java config

前端 未结 9 1189
-上瘾入骨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 05:05

    In springboot it is even simplier. Because of Spring autoconfiguration stuff, spring creates a bean org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties. This class is annotated with @ConfigurationProperties(prefix = "spring.mvc") and therefore it will seek for properties with spring.mvc prefix.

    Part from javadoc:

    Annotation for externalized configuration. Add this to a class definition or a
    * @Bean method in a @Configuration class if you want to bind and validate
    * some external Properties (e.g. from a .properties file).
    

    You just have to add to your i.e. application.properties file following properties:

     spring.mvc.throwExceptionIfNoHandlerFound=true
     spring.resources.add-mappings=false //this is for spring so it won't return default handler for resources that not exist
    

    and add exception resolver as follows:

    @ControllerAdvice
    public class ExceptionResponseStatusHandler {
        @ExceptionHandler(NoHandlerFoundException.class)
        public ModelAndView handle404() {
            var out = new ModelAndView();
            out.setViewName("404");//you must have view named i.e. 404.html
            return out;
        }
    }
    

提交回复
热议问题