Spring 4 Loading Static Resources

Spring 4 loading static resources

You say that your stylesheets and JavaScript files are under "/assets". I'm going to assume you have directories "/assets/css" and "/assets/js". Then, given the following resource handler definition:

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

You would load these resources in your HTML like so:

<link href="/assets/css/style.css" rel="stylesheet" />
<script src="/assets/js/general.js"></script>

Spring MVC static resources not loading

Try removing default servlet mappings from web.xml. Default servlet is an servlet which is created in every web app. In tomcat it serves static resources.

Thymeleaf unable to load static resources

It looks like your CSS is served as HTML.

Since you put the Stylesheets in src/main/resources/static Spring should set up most things based on sensible defaults, including setting the correct content-type header.

I assume you are using Spring Security, since you showed a login form.

It could be that your resources are protected by Spring Security. Thus instead of your stylesheet you get a 30x redirect to the login page. This would explain why your browser complains about the text/html content type, which is wrong for css but the correct type for a login page.

Do you configure HttpSecurity somewhere in your project (most likely annotated with @EnableWebSecurity)?

If so, you need to allow anonymous access to your resources:

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**", "/images/**").permitAll()
// rest of your code

If you switch to the network tab in your browser console, you should be able to inspect the redirect to the login page.



Related Topics



Leave a reply



Submit