Serving External Resources From a Spring Application

Login | Register

Serving External Resources From a Spring Application

Spring

The majority of times when serving content via HTTP from a Spring application, the content is stored within the .Jar/.War file of the application or on remote servers. For example, Thymeleaf templates are typically stored within the src\main\resources\templates folder of a Java web application and frameworks like Bootstrap or jQuery are typically loaded from external content delivery networks.

Spring however, makes it very simple to expose a local directory via HTTP access, so for example, a local folder called /opt/assets could be available as http://hostname/assets. By separating the external folder from the .Jar/.War deployable, is becomes much easier to alter the content within the assets (in this case) folder.

To serve a local directory via HTTP using Spring, we add resource handlers via the WebMvcConfigurerAdapter class. The WebMvcConfigurerAdapter class contains a method addResoureHandlers which does all of the work for us.

void addResourceHandlers(ResourceHandlerRegistry registry)
Add handlers to serve static resources such as images, js, and, css files from specific locations under web application root, the classpath, and others.

The following code sample shows how to use the addResourceHandlers method to add a resource handler.

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Value("${assets.location}")
    private String assetsLocation;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/assets/*").addResourceLocations("file://" + assetsLocation);
        super.addResourceHandlers(registry);
    }

}

In this code, the WebConfig class extends from WebMvcConfigurerAdapter so that it enables us to modify the resource handlers. The class is annotated with @Configuration indicating that we are exposing bean methods to be processed by Spring.

The addResourceHandlers method adds a resource handler (in this case /assets/*) from the file location defined by the assets.location property within the application's application.properties file. The important thing to note here is that the resource location has to be prefixed with file:// to be able to successfully add the resource handler.

As you can see, this is a very powerful feature of Spring, but is very simple to implement within your own applications.

About

At Develop In Java, we've been a part of the Java community for over 10 years. If there's anything you'd like us to cover, just ask !

Current versions

  • Java - 1.8
  • Java EE - 7
  • Spring - 4.x