Spring Boot + Thymeleaf css is not applied to template
I had same problems and I was also trying to use thymeleaf template resolver for pdf generation. I did lots research on thymeleaf and spring framework, I tried WebContext, I tried HttpServletRequest, I tried some of Spring Thymeleaf integration solutions it was not working either. So I think it was not syntax error, and I finally end up with using absolute path instead of relative.
Url for reference
Here the reason with my assumption, lets say our resources are served on localhost:8080/myapp/css/style.css
. And the relative path to request resource is really ups to what context it relatives to.
For eaxmple a normal thymeleaf model Veiw, which return as html pages on browser for client, so the context in that case would be the request hostname, port and application context(eg: localhost:8080/myapp). And relative path will be based on that. So if relative path is /css/style.css, context + relative path will result to be localhost:8080/myapp/css/style.css
Unlike web context, in our case, offline template is on server backend, so the context I assume would be the server running context, which would be the local server path + appcontext(eg: D:/myServer/apps/myapp), relative path /css/style.css on this would be D:/myServer/apps/myapp/css/style.css
, this is not make sense. In order to use static resources, I have to pass it's absolute path.
I started use :
<link rel="stylesheet" type="text/css" th:href="@{http://localhost:8080/myapp/css/style.css}"/>
It's working fine but what if there are multiple host names or server is running on a proxy, then this is going to be a hard coded solution. It's better to know what is the real base url the user is requesting. So we can't really get rid off HttpSevletRequest.
Here is my code:
1.Config resource handler:
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**")
.addResourceLocations("classpath:/css/")
.setCachePeriod(31556926);
}
Get base url from HttpServletRequest, you can inject it in method or autowired in your service class, or get from RequestContextHolder. I write this in my Service class:
private static String getCurrentBaseUrl() {
ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest req = sra.getRequest();
return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
}This is the place I use template engine in my class:
Context context = new Context();
context.setVariable("variales", variables);
context.setVariable("baseUrl", getCurrentBaseUrl());
String content = springTemplateEngine.process("myTemplate",context);In my template, I use absolute css url like this:
<link type="stylesheet" th:src="@{|${baseUrl}/css/style.css|}" />
SpringBoot with Thymeleaf - css not found
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. =)
Spring Boot, Thymeleaf and CSS
Instead of
<link rel="stylesheet" href="css/main.css"/>
Use this :
<link rel="stylesheet" th:href="@{/css/main.css}" />
and make sure this is your file placeholders
src/main/resource/static/css
- for CSS files
src/main/resource/templates
- for HTML templates files
Spring Boot cant serve css file with Thymeleaf View
The issue was actually in my CSS file :) . Apparently i had selectors for classes that werent present in the html. After removing them the solution proposed in the comments worked fine!
Spring Boot + Thymeleaf CSS file cannot access and have 500 error no template found
After checking my source code, I find it's because I have another controller has request mapping to home page and block CSS/JS URL. After I comment the function test2(), home page can load static resources now.
@RequestMapping(value = "/")
public String test1(){
return "index";
}
@RequestMapping
public String test2(){
return "index";
}
When I run my Spring Boot Project with Thymeleaf, the browser won't load the css files but path for href and th:href is correct
Spring Boot serves anything that is in src/main/resources/static
at the root of your application.
So the URL to use to get the CSS with Thymeleaf should be /css/styles.css
.
Edit your HTML file like this:
<link rel="stylesheet" type="text/css" href="../static/css/styles.css" th:href="@{/css/styles.css}">
In your security configuration, also use /css
and not /static/css
:
.antMatchers(
"/registration**",
"/js/**",
"/css/**",
"/img/**").permitAll()
You can also use:
http.authorizeRequests()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations())
.permitAll()
.antMatchers("/registration**",
"/img/**")
.permitAll()
PathRequest.toStaticResources().atCommonLocations()
includes /css/*
, /js/*
, /images/*
, /webjars/*
and favicon.ico
.
Custom .css file doesn't work with Thymeleaf & Spring MVC
Try changing a little bit your folder structure, create a folder under resources called static, and a folder called css under static and place the css files there, something like:
resources
└─── static
└─── css
└─── main.css
Then you should be able to access it by using:
<link rel="stylesheet" type="text/css" th:href="@{/css/main.css}"/>
Spring Thymeleaf not loading CSS (xml configuration)
I had the same problem in the beginning :)
Put your css, js, images, ... inside a "static" folder within the resources directory. Otherwise thymeleaf can't find it.
It should look like this: resources -> static -> css -> style.css
You can now access the css via href="css/style.css"
The same goes for js, images, etc.
EDIT: Added pictures of a sample project
Project structure
Html page
Check out the demo project under Github ! :)
Related Topics
How to Remove Border of Drop Down List:Css
How to Word-Wrap Long Words in a Div
Why Is a Flex Item Limited to Parent Size
What's So Bad About In-Line Css
Understanding Z-Index Stacking Order
Css to Select/Style First Word
How Does the CSS Block Formatting Context Work
Use of Xsl-Fo, Css3 Instead of Css2 to Create Paginated Documents Like Pdf
Areas Covered by Flexbox Which Are Difficult or Impossible to Achieve With Grid
How to Change Colour of Blue Highlight on Select Box Dropdown
How to Fill Html5 Input[Type=Range] on the Left Side of the Thumb With CSS Only
Ipad Safari Scrolling Causes HTML Elements to Disappear and Reappear With a Delay
Difference Between Visibility:Hidden and Display:None
Border Gradient With Border Radius
Text in a Flex Container Doesn't Wrap in Ie11