Spring isn't loading CSS and gives a 404 when the page is loaded
I'm running a Spring (not Boot) web app and it's finding my JSP views properly, but my CSS isn't being found for some reason. To be clear, the page is loading with the necessary elements, but any CSS styling from classes in my .css
files is not being applied. The structure for the CSS file I'm trying to use is src/main/resources/css/style.css
.
Below is the relevant code for my AppConfig
class:
public class AppConfig implements WebMvcConfigurer {
...
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**")
.addResourceLocations("/css/");
}
...
}
And the JSP header:
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css"/>
I've already checked some other questions asking after this issue and have had no luck. Several of them advised checking the config file for Spring Security to ensure that permission is granted for all requests using the resource file but based on what I can see, it shouldn't be prohibiting the CSS from being loaded:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setPasswordEncoder(encoder());
authenticationProvider.setUserDetailsService(userService);
return authenticationProvider;
}
}
Solution 1:
For a non-Spring Boot project your css
folder should be not in src/main/resources
but in src/main/webapp
.