Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring mvc catch all route but only unknown routes

I've got a spring boot app with angular on the frontend.

I'm using ui-router with html5 mode and I would like spring to render 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 can i create a fallback mapping but that lets through the resources?

like image 517
Leon Radley Avatar asked Feb 10 '23 21:02

Leon Radley


1 Answers

The simplest way I found was implementing 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 propopes a HandlerInterceptor, but I wasn't able to understand how that would be implemented. I't would be great to see how this would be implemented, as single page applications using html5 history push state will want this behaviour. And I have not really found any best practices to this problem.

like image 86
Leon Radley Avatar answered Feb 14 '23 00:02

Leon Radley