Static resources can be configured using two approaches in Spring Boot
- Add custom path in application.properties/application.yaml
- Implement WebMvcConfigurer
addResourceHandlers()
method
First configure your SpringSecurity class to accept requests to this resources
@Override
public void configure(WebSecurity web)
{
web.ignoring()
.antMatchers( "/static/**","/resources/**", "/js/**", "/css/**", "/images/**");
}
Then use any one of the following way to serve static content
- Open
application.properties/application.yaml
file and add the following line based on your directory structure
spring.resources.static-locations=classpath:/static/,classpath:/static/vendor/,classpath:/static/custom/
-
By default classpath points to
/resources/
directory under project root. So, static folder/file locations should be relative from that directory. -
Example:
Absoulte Path: /Users/johnd/IdeaProjects/SpringSessionTest/src/main/resources/static/vendor/css/bootstrap.min.css
Project Structure: SpringSessionTest/src/main/resources/static/vendor/css/bootstrap.min.css
In this case, your static-locations should be spring.resources.static-locations=classpath:/static/,classpath:/static/vendor/
and in your web page you can use
<link href="css/bootstrap.min.css" rel="stylesheet">
to link this stylesheet
- Create class ApplicationConfig that extends WebMvcConfigurer interface and configure your locations in CLASSPATH_RESOURCE_LOCATIONS string array
@Configuration
public class ApplicationConfig implements WebMvcConfigurer
{
private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
{
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/","classpath:/static/vendor/","classpath:/static/custom/"
};
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
}
Here is a resource that talks about handling spring boot static content in variety of ways . I found 4th one interesting
https://www.frugalisminds.com/spring-boot-serve-static-web-content/