14

First to say is that I've been searching for a solution for a while now and I'm quite desperate now.

I cannot get the css file to be accessible from html page when run by Spring Boot.

html.file

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head lang="en">
        <title th:text='#{Title}'>AntiIntruder</title>
        <meta charset="UTF-8" />
        <link rel="stylesheet" type="text/css" media="all" href="../assets/css/style.css" th:href="@{/css/style.css}" />
    </head>
    <body>
...

Application.java

@SpringBootApplication // adds @Configuration, @EnableAutoConfiguration, @ComponentScan
@EnableWebMvc
public class Application extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

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

folder structure:

folder structure

I've tried putting the css folder into a static folder and/or removing the addResourcesHandlers, referencing to the css by relative path and some other things. Nothing seems to resolve this. Please, let me know also if you tried to solve this but did not find a solution, so that I know, that I'm not ignored.

Bato
  • 437
  • 1
  • 4
  • 11
  • I'm rebuilding the code after each change and refreshing the page in Firefox with Ctrl+F5. I've also tried using Chrome. I run the webapp with `gradle bootRun` – Bato Apr 10 '15 at 13:48
  • If I open the `html` file directly in the browser, the page is formatted correctly with the css file. – Bato Apr 10 '15 at 13:51
  • Remove the @EnableWebMvc annotation as already mentioned. See also https://stackoverflow.com/a/37205978/14691363 – Telamon Apr 07 '21 at 13:12

9 Answers9

35

1. Using Custom Resource Path

In your Web Config

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

Put your style.css file inside this folder

src/main/resources/assets/css/

After that in your views

<link rel="stylesheet" type="text/css" th:href="@{/assets/css/style.css}" />

.

2. Using predefined paths in spring boot

Remove addResourceHandlers from your web config

Put the style.css inside any of the following folders

  • src/main/resources/META-INF/resources/assets/css
  • src/main/resources/resources/assets/css/
  • src/main/resources/static/assets/css/
  • src/main/resources/public/assets/css/

And in the view

<link rel="stylesheet" type="text/css" th:href="@{/assets/css/style.css}" />

.

NOTE: You can remove the assets folder here. If you want to do it, remove it from the predefined resource folder and also from the view th:href. But i kept it as it is because, you explicitly mentioned the assets/ path in your question. So I belive it's your requirement to have assets/ in your resource URL.

Faraj Farook
  • 14,385
  • 16
  • 71
  • 97
  • 1
    Thank you for a very nice explanation! I give you an upvote for that. Unfortunatelly, this does not work either. I've also tried moving the css file to different location, also in the resulting war file. I've tried deploying the app to standard tomcat... I have no idea...this should be working now. Is there some other info that I could provide you with? Would posting some more code help? If yes, which one? – Bato Apr 10 '15 at 23:27
  • See https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot for more detail and note in the example above that `assets` is served from the application root (i.e. `public`, `static`, etc is not part of the path). Leaving `assets` in the hierarchy makes it easier to configure security: `http.authorizeRequests().antMatchers("/assets/**").permitAll()` – Glenn Jun 02 '18 at 21:17
  • This approach is like research. The best)) – Ryabinin Sergey Dec 22 '22 at 19:21
10

The problem was the @EnableWebMvc annotation in the Application.java file. As soon as I removed that one, the css started to be available at localhost:8080/css/style.css but was not applied. So far I haven't found the reason why the @EnableWebMvc was causing the problem.

Then I removed a controller mapped to /** that I had implemented in order to display custom error page.

@RequestMapping("/**")
public String notFound() {
    return "errors/404";
}

After removing also this one, I've got my css working. =)

Bato
  • 437
  • 1
  • 4
  • 11
6

If you put your css in the static folder, you dont need the addResourceHandlers method.

.../static/css/app.css

Or if you really want to put them in the assets folder:

.addResourceLocations("classpath:/assets/") <-- without the * at the end
.../assets/css/app/css

in both cases the css should be available through

th:href="@{/css/app.css}"
MystyxMac
  • 1,532
  • 2
  • 14
  • 28
  • I removed the `addResourceHandlers` and put the `css` folder into the `static` folder and it still does not work. Then I put it back to `assets` and put the `addResourceHandlers` back but without the `*` and this does not help either. – Bato Apr 10 '15 at 13:47
  • I could not get it to work unless i remove EnableWebMvc from my WebConfig class. – djangofan Oct 18 '17 at 02:56
  • I removed the `/static/` part of the path to the `.css` file and it started working fine! Does this mean the relative root path for the static resources shouldn't include `/static/`? – Mike Jul 30 '19 at 20:17
1

Put your css folder inside resources/static folder

L01c
  • 1,033
  • 10
  • 19
1

In my case the problem was in file read permissions. I copied the file 'style.css' from another project, and browser could not read it. After re-creating 'style.css', everything worked fine.

0

My advice is to put (again) css folder under static folder, remove addResourcesHandlers and reach css with absolute path (e.g. /css/style.css).

Sezin Karli
  • 2,517
  • 19
  • 24
  • I've done that again, but the result is the same. The css is in `resources/static/css/style.css` and the tag is `` In browser's console I can see that it's looking for the css file in `http://localhost:8080/css/style.css` – Bato Apr 10 '15 at 13:34
  • @Bato : I am seeing the same issue. any pointers how you had resolved these ages ago ? – jetty Jun 06 '21 at 15:57
0

For me I had to remove the static reference to the stylesheet for it to work in thymeleaf. So

<link rel="stylesheet" type="text/css" media="all" href="../assets/css/style.css" th:href="@{/css/style.css}">

Became

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

I spent hours trying all sorts of configurations and file path renaming. Don't know why but this is the only thing that got my css and js to load in Spring Boot 5.

0

first implements on one of your configuration class with WebMvcConfigurer like this

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
//and overide this configuration method like this    
@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/webjars/**", "/resources/**");
    }
}

so now you can overide your HttpSecurity configuration like this

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{
 
   @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                        .antMatchers("/", "/index").anonymous()
                        .antMatchers("/**/*.*").permitAll()
                .anyRequest().authenticated();
    }
}

this ("/**/*.*") regex text will allow files with anny extension

and if your are using an webjars libraries like bootstrap add this config to your WebSecurityConfiguration

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
0

If this topic still relevant in 2022. I have had a similar problem and i solved it like this:

This link in /templates/file.html

<link rel="stylesheet" type="text/css" media="all" ref="../static/css/styles.css">

and i have added application.properties

spring.mvc.static-path-pattern=/static/**

my css path is

 src/main/resources/static/css/

helpful link

Vladimir
  • 1
  • 2