Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

404 error redirect in Spring with Java config

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?

like image 867
Carlos López Avatar asked May 09 '14 22:05

Carlos López


People also ask

How do I redirect an error page in spring boot?

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.

Why does spring boot say 404 error?

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.

How do I redirect a URL in spring?

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.


1 Answers

In Spring Framework, there are number of ways of handing exceptions (and particularly 404 error). Here is a documentation link.

  • First, you can still use 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.

like image 148
Eugene Avatar answered Sep 20 '22 12:09

Eugene