404 error redirect in Spring with Java config

java, spring, spring-mvc

Solution

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.

Problem

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?

Original source

Related problems