Static Resources Configuration

In this section, you will learn about Static Resources Configuration through MVC Java config and XML Namespace.

Static Resources Configuration

Static Resources Configuration

In this section, you will learn about Static Resources Configuration through MVC Java config and XML Namespace.

Using this alternative, static resource request of a specific pattern (URL pattern) is handled by ResourceHttpRequestHandler which searches the requested resource at the listed resource locations and serve it. This option also gives easy way to serve static resources from locations other than the web application root, including locations on the classpath.

Given below MVC Java config to configure static resources :

@Configuration
@EnableWebMvc
public class MyWebAppConfig extends WebMvcConfigurerAdapter {
	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/resources/**").addResourceLocations("/public-contents/");
	}

}

In the above configuration, the resource requests having URL pattern /resources/** is served from directory /public-contents/ in the web application root.

You can do the same in MVC XML Namespace as :


<mvc:resources mapping="/resources/**" location="/public-contents/"/>

You can set the expiration period which assures maximum utilization of the web-browser cache and also cut down HTTP requests from browser. You can configure it using MVC Java config as below :

@Configuration
@EnableWebMvc
public class MyWebAppConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/resources/**").addResourceLocations("/public-contents/").setCachePeriod(31556926);
	}

}

In the above case, we are setting the expiration period for 1 year. You can do the same in XML as :


<mvc:resources mapping="/resources/**" location="/public-contents/" cache-period="31556926"/>