SPA with Spring Boot - service index.html for non-API requests

I'm currently working on a webpage that should use a single page React interface. For internal use, I use the spring framework.

All api calls must use the url prefixed with /api and must be handled by REST controllers.

All other URLs should just serve the index.html file. How can I achieve this with spring?

+5
source share
1 answer

The easiest way to achieve what you want is to implement a custom 404 handler.

Add these parameters to your application.properties:

 spring.resources.add-mappings=false spring.mvc.throw-exception-if-no-handler-found=true 

The first property removes all static processing by default, the second property disables Spring's default whitelabel page (by default, Spring catches a NoHandlerFoundException and NoHandlerFoundException a standard whitelabel page)

Add a 404 handler to your application context:

 import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class PageNotFoundController { @ExceptionHandler(NoHandlerFoundException.class) public String handleError404() { return "redirect:/index.html"; } } 

In the end, you will need to add your custom view to view your static content (index.html in this case)

 import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceView; import org.springframework.web.servlet.view.UrlBasedViewResolver; @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/index.html").addResourceLocations("classpath:/static/index.html"); super.addResourceHandlers(registry); } @Bean public ViewResolver viewResolver() { UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setViewClass(InternalResourceView.class); return viewResolver; } } 

Your index.html should be placed in the /resources/static/ directory.

+4
source

All Articles