How to create a 404 controller using spring boot?

I want to return a custom 404 error using SpringBoot, but I would like to add some server logic to it, and not just a static page.

1. I disabled the default whitelabel page in application.properties

error.whitelabel.enabled=false

2. I added Thymeleaf error.html to resources/templates

It works, by the way. The page is served, but the controller is not called.

3. I created the Error class as a โ€œControllerโ€

 package com.noxgroup.nitro.pages; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/error") public class Error { @ExceptionHandler public String index() { System.out.println("Returning Error"); return "index"; } } 

Unfortunately, I do not see Returning Error anywhere in the console.

I am using Embedded Tomcat with Spring Boot. I saw various options that do not work, including using @ControllerAdvice, removing RequestMapping, etc. Doesnโ€™t work for me.

+6
source share
2 answers

The servlet container will collect 404 before it can reach Spring, so you will need to identify the error page at the servlet container level that will go to your user controller.

 @Component public class CustomizationBean implements EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error")); } } 
+17
source

The easiest way I've found is to implement ErrorController.

 @Controller public class RedirectUnknownUrls implements ErrorController { @GetMapping("/error") public void redirectNonExistentUrlsToHome(HttpServletResponse response) throws IOException { response.sendRedirect("/"); } @Override public String getErrorPath() { return "/error"; } } 
+3
source

Source: https://habr.com/ru/post/983419/


All Articles