Spring mvc catch the whole route but only unknown routes

I have a spring boot application with angular on the interface.

I am using ui-router with html5 mode and I would like spring to display the same index.html on all unknown routes.

// Works great, but it also overrides all the resources @RequestMapping public String index() { return "index"; } // Seems do be the same as above, but still overrides the resources @RequestMapping("/**") public String index() { return "index"; } // Works well but not for subdirectories. since it doesn't map to those @RequestMapping("/*") public String index() { return "index"; } 

So my question is how to create a fallback mapping, but which allows through resources?

+1
source share
4 answers

The easiest way I've found is to implement a custom 404 page.

 @Configuration public class MvcConfig { @Bean public EmbeddedServletContainerCustomizer notFoundCustomizer(){ return new NotFoundIndexTemplate(); } private static class NotFoundIndexTemplate implements EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/")); } } } 

Neil McGuigan offers a HandlerInterceptor, but I could not figure out how this would be implemented. It would be great for me to see how this is implemented, since single-page applications using html5 history push state will want this behavior. And I actually did not find any recommendations on this issue.

+3
source

try using @ExceptionHandler in your controller, change Exception.class with the exception class with which you want to handle.

 @ExceptionHandler(value = {Exception.class}) public String notFoundErrorHandler() { return "index"; } 
+2
source

Define an entry point for all URLs in the web.xml file, for example:

 <error-page> <error-code>404</error-code> <location>/Error_404</location> </error-page> 

This will cause all errors to fail on the 404 ie page and drop the URL /Error_404 , catch it in the controller and click on the right place.

+1
source

You can handle all inappropriate requests in the 404 handler. Look at this , there are several options

Another thing you could do is to override DefaultAnnotationHandlerMapping and add some kind of catch-all controller by setting the defaultHandler property.

public void setDefaultHandler(Object defaultHandler)
Set the default handler for this handler mapping. This handler will be returned if no specific mapping is found. The default value is null , indicating that there is no default handler.

+1
source

All Articles