404 error redirect in Spring with java config

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

    In your web configuration class,

    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter 
    

    Declare a bean as follows,

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
    
      return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container)       
        {
          ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
          ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
          ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
    
          container.addErrorPages(error401Page,error404Page,error500Page);
        }
      };
    }
    

    Add the mentioned html files(401.html .etc) to /src/main/resources/static/ folder.

    Hope this helps

提交回复
热议问题