Posted In: Spring, Spring Boot, Spring MVC

How to handle static content in Spring MVC and Spring Boot

How to exclude static content from being served by Dispatcher Servlet?

Spring MVC

1. All requests are set to pass through Dispatcher servlet

  <servlet>
    <display-name>springapp</display-name>
    <servlet-name>springapp</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
	<url-pattern>/</url-pattern>
  </servlet-mapping>

2. Create sample app.js file in /WebContent/resources folder. For Maven create JS file in /src/main/webapp/resources

3. Now try accessing following URL

http://localhost:90/example/resources/app.js
Application will throw 404 error

WARNING: No mapping found for HTTP request with URI [/example/resources/app.js] in DispatcherServlet

4a. To resolve this now add following entry to your spring XML

<mvc:resources mapping="/resources/**" location="/resources/" />

Now try to access JS file. It should be accessible.

4b. Another way is to use Java Configuration

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

Spring Boot

Spring Boot automatically excludes following folders and serves them as web content

/META-INF/resources/
/resources/
/static/
/public/

This is achieved through following code in org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
		"classpath:/META-INF/resources/", "classpath:/resources/",
		"classpath:/static/", "classpath:/public/" };

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
	if (!registry.hasMappingForPattern("/webjars/**")) {
		registry.addResourceHandler("/webjars/**").addResourceLocations(
				"classpath:/META-INF/resources/webjars/");
	}
	if (!registry.hasMappingForPattern("/**")) {
		registry.addResourceHandler("/**").addResourceLocations(
				RESOURCE_LOCATIONS);
	}
}

by , on July 11th, 2017

  • Categories