Spring MVC: How to return custom 404 errorpages?

后端 未结 8 2150
遇见更好的自我
遇见更好的自我 2020-11-27 04:40

I\'m looking for a clean way to return customized 404 errorpages in Spring 4 when a requested resource was not found. Queries to different domain types should result in diff

8条回答
  •  醉话见心
    2020-11-27 05:01

    I also needed to NOT use org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.

    According to org.springframework.web.servlet.DispatcherServlet.setThrowExceptionIfNoHandlerFound(boolean): "Note that if DefaultServletHttpRequestHandler is used, then requests will always be forwarded to the default servlet and a NoHandlerFoundException would never be thrown in that case."

    https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html#setThrowExceptionIfNoHandlerFound-boolean-

    Before

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "com.foo.web")
    public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
    
      @Override
      public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
      }
    
      // ...
    }
    

    After

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "com.foo.web")
    public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
    
      @Override
      public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
      }
    
      // ...
    }
    

提交回复
热议问题