Springboot custom 404 error message

  springboot

Order

This article briefly introduces how to personalize 404 error messages in springboot.

Return json

@Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return new EmbeddedServletContainerCustomizer(){
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
            }
        };
    }

Then define 404 request

    @GetMapping("/404")
    @ResponseBody
    public Object customNotFound(){
        return "not found";
    }

Return to page

@Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return new EmbeddedServletContainerCustomizer(){
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
            }
        };
    }

Then place the 404.html in the resources/static directory.

This is the end of the story.

doc