As you know, in XML, the way to configure this is:
<error-page> <error-code>404</error-code> <location>/my-custom-page-not-found.html</location> </error-page>
But I haven't found a way to do it in Java config. The first way I tried was:
@RequestMapping(value = "/**") public String Error(){ return "error"; }
And it appeared to work, but it has conflicts retrieving the resources.
Is there a way to do it?
In Spring Boot 1.4. x you can add a custom error page: If you want to display a custom HTML error page for a given status code, you add a file to an /error folder. Error pages can either be static HTML (i.e. added under any of the static resource folders) or built using templates.
We went through the two most common reasons for receiving a 404 response from our Spring application. The first was using an incorrect URI while making the request. The second was mapping the DispatcherServlet to the wrong url-pattern in web. xml.
We can use a name such as a redirect: http://localhost:8080/spring-redirect-and-forward/redirectedUrl if we need to redirect to an absolute URL.
In Spring Framework, there are number of ways of handing exceptions (and particularly 404 error). Here is a documentation link.
error-page
tag in web.xml, and customize error page. Here is an example.Second, you can use one @ExceptionHandler
for all controllers, like this:
@ControllerAdvice public class ControllerAdvisor { @ExceptionHandler(NoHandlerFoundException.class) public String handle(Exception ex) { return "404";//this is view name } }
For this to work, set throwExceptionIfNoHandlerFound property to true for DispatcherServlet
in web.xml:
<init-param> <param-name>throwExceptionIfNoHandlerFound</param-name> <param-value>true</param-value> </init-param>
You can also pass some objects to error view, see javadoc for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With