serve static content using springboot

springboot can serve static content files, for example, html, js, css and image, for http request. By default, springboot searches the below directories for the static resources in the class path.

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/

So you can put your front end assets, for example, index.html, into src/main/resources/public directory. After complication and packaging, assuming jar package type, the static resources will lie in classpath:/public directory inside the jar package. This static resource could be served by springboot to respond to client http request /index.html.

The location of the static resource can be customized using a property named spring.resources.static-locations. Let’s say we want to serve the static resource in a directory outside of the jar package, the below configuration can be used

spring.resources.static-locations=file:/your/static/resource/directory

By default, the static resources are mapped on /** for the client request. You can customize this using spring.mvc.static-path-pattern property. For example

spring.mvc.static-path-pattern=/blog/**

Then all client request starting /blob/ will be served using the static resource directories defined by spring.resources.staticlocations.

If this does not meet your requirement, you configure it by extending class WebMvcConfigurer.

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {

    // Register resource handler for CSS and JS
    registry.addResourceHandler("/public/**").addResourceLocations("classpath:/statics/");
 
    // Register resource handler for images
    registry.addResourceHandler("/images/**").addResourceLocations("file:/opt/images/");
  }
}

Using this class, http request for /public/** pattern will be served by resources in directory /statics in the classpath, while the http request for /images/** pattern will be served by resource in directory /opt/images directory outside of the jar package.