Marius Marius - 14 days ago 12
Java Question

Spring Boot Thymeleaf static content doesn´t load

I just started a new Spring Boot (with Spring Security) and Thymeleaf project. Since I wanted to integrate static resources I tried different file structures but with none of them, Spring bound the files in.
Since I havent changed the static-resource path my console outputs

Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
on startup.

Different file structures I tried and didnĀ“t succeed with.

src
|--main
|--java
|--resources
|--static
|--css
|--bootstrap.min.css
|--custom_test.css
|--templates
|--....


also

src
|--main
|--java
|--resources
|--webjars
|--static
|--css
|--bootstrap.min.css
|--custom_test.css
|--templates
|--....


or

src
|--main
|--java
|--resources
|--public
|--css
|--bootstrap.min.css
|--custom_test.css
|--templates
|--....


In HTML/Thymeleaf I tried

<link rel="stylesheet" type="text/css" href="webjars/static/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="webjars/static/css/custom_test.css"/>


or

<link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}"/>
<link rel="stylesheet" type="text/css" th:href="@{/css/custom_test.css}"/>


None of this worked so far.
I really hope you can help me and others with the same poblem.
Thanks in advance!

Answer

Your problem may be the configuration of Spring Security. First, check with the developer tools of your browser and see what the response is for the resources that you do not get on the client. The response status code could be 302 or 401, depending on your current configuration.

If that is the case, you need to add an additional configuration to your project that looks like the following:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{        
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/favicon.ico").permitAll()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/static/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/blog/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }
// ...
}