Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure spring boot to redirect 404 to a single page app [duplicate]

I want to configure my Spring Boot app to redirect any 404 not found request to my single page app.

For example if I am calling localhost:8080/asdasd/asdasdasd/asdasd which is does not exist, it should redirect to localhost:8080/notFound.

The problem is that I have a single page react app and it runs in the root path localhost:8080/. So spring should redirect to localhost:8080/notFound and then forward to / (to keep route).

like image 309
Vovan Avatar asked Jun 22 '17 07:06

Vovan


2 Answers

This is the full Spring Boot 2.0 example:

@Configuration
public class WebApplicationConfig implements WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/notFound").setViewName("forward:/index.html");
}


@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
    return container -> {
        container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
                "/notFound"));
    };
  }

}
like image 179
Jay Steven Hamilton Avatar answered Sep 22 '22 09:09

Jay Steven Hamilton


This should do the trick: Add an error page for 404 that routes to /notFound, and forward that to your SPA (assuming the entry is on /index.html):

@Configuration
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/notFound").setViewName("forward:/index.html");
    }


    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return container -> {
            container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
                    "/notFound"));
        };
    }

}
like image 43
Ralf Stuckert Avatar answered Sep 22 '22 09:09

Ralf Stuckert