Spring Boot
Spring Security
Static Resources
Web Development
Java

Serving static web resources in Spring Boot Spring Security application

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Serving static web resources efficiently is a key requirement in many web applications, particularly when you are working with frameworks like Spring Boot. Static content typically includes assets like HTML files, CSS stylesheets, JavaScript, and images. In a Spring Boot application, serving these assets can be seamlessly integrated with the robust security features provided by Spring Security. This article explores the approaches and considerations in serving static web resources within a Spring Boot and Spring Security environment.

Static Resource Handling in Spring Boot

Spring Boot simplifies static resource handling via its "spring-boot-starter-web" dependency. By default, Spring Boot will automatically serve static resources from several predefined locations within your classpath.

Default Locations for Static Resources

The default locations that Spring Boot scans for static resources include:

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

Placing files in these directories within your src/main/resources will make them automatically available under the root path of your web application.

For example, a file located at src/main/resources/static/index.html can be accessed at http://localhost:8080/index.html.

Configuration Example

You can change these defaults using the spring.resources.static-locations property within your application.properties:

properties
spring.resources.static-locations=classpath:/my-resources/,file:/external-resources/

Customizing Resource Handling

Spring MVC provides several ways to customize static resource handling:

Using ResourceHandlerRegistry

You can customize static resource handling by overriding the addResourceHandlers method in a @Configuration class that implements WebMvcConfigurer.

java
1import org.springframework.context.annotation.Configuration;
2import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
3import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
4
5@Configuration
6public class WebConfig implements WebMvcConfigurer {
7
8    @Override
9    public void addResourceHandlers(ResourceHandlerRegistry registry) {
10        registry.addResourceHandler("/resources/**")
11                .addResourceLocations("classpath:/custom-resources/")
12                .setCachePeriod(3600);
13    }
14}

In this example, any requests that begin with /resources/ will be served from the classpath:/custom-resources/ directory, with cache headers instructing the client to cache the resources for 3600 seconds (one hour).

Integrating with Spring Security

When integrating static resources with Spring Security, it's crucial to configure the security settings properly to allow unauthenticated access to the static assets while still protecting your API and application views.

Configuring Security for Static Resources

To serve static resources securely, you must configure Spring Security to permit all requests to paths where static resources reside. This is done in your WebSecurityConfigurerAdapter implementation.

java
1import org.springframework.security.config.annotation.web.builders.HttpSecurity;
2import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
3
4public class SecurityConfig extends WebSecurityConfigurerAdapter {
5
6    @Override
7    protected void configure(HttpSecurity http) throws Exception {
8        http
9            .authorizeRequests()
10                .antMatchers("/resources/**", "/static/**", "/public/**", "/webjars/**").permitAll()
11                .anyRequest().authenticated()
12            .and()
13            .formLogin().permitAll()
14            .and()
15            .logout().permitAll();
16    }
17}

In this setup:

  • "/resources/**", "/static/**", "/public/**", and "/webjars/**" are configured to be accessible by anyone.
  • All other URL patterns require authentication.

Performance Considerations

When serving static resources, application performance can be improved through caching and compression:

  • Caching: Implement caching for static resources to enhance load times. This can be done using setCachePeriod() as shown earlier, instructing browsers to cache resources for a specific duration.
  • Compression: Enable GZIP compression to reduce the size of responses. This can be enabled in Spring Boot via:
properties
  server.compression.enabled=true
  server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript

Summary Table

Below is a summary table highlighting key points:

AspectDetail
Default Locations/static, /public, /resources, /META-INF/resources
Custom ConfigurationUse addResourceHandlers() to customize and extend default settings
Security ConfigurationUse HttpSecurity to permit all requests to resources while securing other application components
Cache ConfigurationsUse setCachePeriod() in ResourceHandlerRegistry Enable HTTP caching through cache-control headers
CompressionEnable GZIP compression in application.properties

Conclusion

Serving static web resources in a Spring Boot application, in conjunction with Spring Security, requires careful planning to ensure efficient delivery and appropriate security. By default, Spring Boot provides a robust framework to handle static resources, while Spring Security allows for setting up fine-grained security controls. Understanding how to leverage these features effectively can greatly enhance the performance and security of your web application.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.