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?
The solution proposed in comments above really works:
In your web configuration class,
Declare a bean as follows,
Add the mentioned html files(
401.html
.etc) to/src/main/resources/static/
folder.Hope this helps
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:For this to work, set throwExceptionIfNoHandlerFound property to true for
DispatcherServlet
in web.xml:You can also pass some objects to error view, see javadoc for this.
Simple answer for 100% free xml:
Set properties for
DispatcherServlet
Create
@ControllerAdvice
:The most clean solution since spring 4.2 RC3 is using the new
createDispatcherServlet
hook within the class extendingAbstractDispatcherServletInitializer
(or indirectly through extendingAbstractAnnotationConfigDispatcherServletInitializer
) like this:Then you can use a global
@ControllerAdvice
(a class that is annotated with@ControllerAdvice
) as described in the reference docs. Within the advice you can handle theNoHandlerFoundException
with an@ExceptionHandler
as described here.This could look something like this:
Use code-based Servlet container initialization as described in the doc and override registerDispatcherServlet method to set throwExceptionIfNoHandlerFound property to true:
Then create an exception handler:
Don't forget about using @EnableWebMvc annotation on your Spring configuration file: