Thymeleaf + CSS+SpringBoot - css

I have a problem with CSS and Thymeleaf.
In my Spring boot app, I have this structure:
src/main/resource/static/css (for css files)
src/main/resource/static/templates (for html file)
Now, with my html page named ErrorPage and css file named Layout.css, using Thymeleaf I have, in the head of ErrorPage:
<link href="../css/Layout.css" th:href="#{css/Layout.css}" type="text/css" />
But this does not work.
What am I doing wrong?

Move your template folder right under resources:
src/main/resource/static/css (for CSS files);
src/main/resource/templates (for HTML templates).
Then correct the link tag as follows:
<link href="../static/css/Layout.css" th:href="#{/css/Layout.css}" rel="stylesheet" />

Move your template folder right under resources:
src/main/resources/static/css (for CSS files);
src/main/resources/templates (for HTML templates).
Then correct the link tag as follows (relative or absolute):
<link href="../css/firstcss.css" rel="stylesheet">
<link href="/css/secondcss.css" rel="stylesheet">
The old solution with static in front doesn't work for me.

The main culprit of this behaviour is a custom security configuration which is very likely you are doing in your WebSecurityConfigurerAdapter subclass.
If you use SpringBoot 2+ version you should add the following line in your WebSecurityConfigurerAdapter configuration
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

Related

CSS stylesheet doesn't work with Spring Security + Spring Boot + Thymeleaf

After much research, I haven't been able to find a solution. I have a project implemented with Spring Boot + Spring Security + Thymeleaf.
I have a REST API multi-module project and a web client built with Thymeleaf. My problem is that I can't seem to include my CSS stylesheet in my Thymeleaf page.
MvcConfig :
#Configuration
public class MvcConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.
addResourceHandler(
"/css/**",
"/img/**").
addResourceLocations(
"classpath:/resources/static/img",
"classpath:/resources/static/css");
}
My Html (Thymeleaf)
<!DOCTYPE HTML >
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head xmlns:th="http://www.thymeleaf.org">
<title>Bibliothèque d'OC</title>
<link rel="stylesheet" type="text/css" th:href="#{/static/css/style.css}">
<!-- CSS only -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</head>
I've tried changing the value of the path set on the th:href attribute of the link tag (th:href="#{/static/css/style.css}"). And I've also tried adding an href attribute to the link tag; neither one helped. I can't find the solution.
Can someone suggest a solution?
TL;DR — Change th:href="#{/static/css/style.css}" to th:href="#{/css/style.css}".
The long-winded version
Thymeleaf expects projects to have a particular, default directory structure: src/main/resources/static. The path that you set for Thymeleaf's special th:href attribute must be relative to that expected directory structure.1
The snippets in your original question and your replies in the comments, suggest that your project is laid out like this…
…
└───src
└───main
│
└───resources
├───static
│ └───css
└───templates
If that is the case, then the relative path to your stylesheets that you need to give to Thymeleaf should be: th:href="#{/css/style.css}".
If that is not the case and your project's directory structure is something different than what I illustrate above then please share, in the comments of this answer, what exactly your directory structure is.
I noticed that you declare the Thymeleaf th namespace twice; once in the html tag, then again in the head tag. There should be only one namespace declaration.2 My advice is that you remove the one in the head tag.
Consider this from a 2013 blog post on spring.io…3
…Spring Boot will automatically add static web resources located within any of the following directories:
/META-INF/resources/
/resources/
/static/
/public/
…
According to that, not only is this part of your application's configuration unnecessary, I have a hunch that it could be the root cause of your problem…
…
registry.
addResourceHandler(
"/css/**",
"/img/**").
addResourceLocations(
"classpath:/resources/static/img",
"classpath:/resources/static/css");
…
I've implemented at least a dozen different Spring Boot applications that served static content. I've never once had to implement any configuration code like you are doing there.
My advice is — in addition to the th:href attribute and th namespace declaration suggestions — remove that unnecessary registry.addResourceHandler( … ) configuration.
1 Add CSS and JS to Thymeleaf — Amy DeGregorio
2 Using Thymeleaf — Official documentation
3 Serving Static Web Content with Spring Boot — Spring Blog

Refused to apply style because its MIME type ('application/json') is not a supported

I want to use the fullcalendar library, using gulp and yarn this is the generated link tag:
But I'm getting this error in the console :
Refused to apply style from
'http://localhost/bower_components/fullcalendar/dist/fullcalendar.css'
because its MIME type ('application/json') is not a supported
stylesheet MIME type, and strict MIME checking is enabled.
Why I'm getting this and how can I solve it?
In my case, I found out that I had a typo in css file name. Thus I was trying to import an non existing file.
You're app is serving fullcalendar.css with the wrong MIME type ('application/json') some how. So, my advise is to dig the problem trusting in the error message.
In my case, I was trying Thymeleaf and WebJars with spring-boot for the first time and following blindly some tutorial I added this:
#Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/");
}
}
Also, my styles were defined in html as below:
<link rel="stylesheet" type="text/css" th:href="#{/webjars/bootstrap/css/bootstrap.min.css}" />
<link rel="stylesheet" type="text/css" th:href="#{/css/main.css}" />
This way, "bootstrap.min.css" and others were given the very same error: "Refused to apply style because its MIME type ('application/json') is not a supported".
I still haven't broken down the reasons for this behavior, but as soon as I realized that spring-boot has an automatic configuration for WebJars, I removed that registration and everything started to work well.
Note: There are some similar tracks with "MIME type ('text/html')" and the reason is usually security filters not allowing the css files and redirecting to html login page. So, keep this in mind and check whether you have some kind of filter/redirect for this request.
Directly put the URL in the browser and see if you can reach it.
For your case, give this url in the browser http://localhost/bower_components/fullcalendar/dist/fullcalendar.css
If you can't reach it, then you have wrong url in your code.
For my case, I had the css file in a directory named css, but in the code I wrote /plugins/css and was getting the same error.
Also, don't forget to give the type="text/css"
So, my code example below:
<head>
<link rel="stylesheet" type="text/css" th:href="#{/css/app.css}">
</head>
If you are using Spring Boot you will not even have to override addResourceHandlers(), just make sure to use th:href and point it to the correct directory.
In my case in the css file
where was a reference to a map file
/*# sourceMappingURL=bootstrap-datepicker.css.map */
that was not present.
I removed the reference to the source map and worked.
You can trying using the relative path to your static content.
<head>
<link rel="stylesheet" type="text/css" href="../css/app.css">
</head>

ASP.NET MVC 6 Not Rendering CSS Style Sheet

I am trying to get add a css file to my layout file, which is in the Shared folder. When I run the web application, my CSS is not rendered (CSS that is not in the solution (ie: Bootstrap CDN) renders.
I have tried linking the CSS using these methods, and they don't work:
<link rel="stylesheet" href="#Url.Content("~/Assets/Scripts/StyleSheet.css")" type="text/css"/>
<link rel="stylesheet" href="~/Assets/Scripts/StyleSheet.css" type="text/css"/>
The File Structure For my app is:
Is there something I should be adding to the Startup.cs file so it can read css files?
Thanks.
EDIT: ERROR 404 WITH THE STYLE SHEET
I ran the application on Mozilla Firefox, and used the built in Developers Console to see whats happening. After observing the network tab, it tells me ERROR 404 Occurred while trying to retrieve the style sheet. This is really odd.
Do other changes in your layout show up correctly? For instance if you add a random text string, does that show up? As far as startup.cs, you should have app.UseStaticFiles(); in the Configure section.
Once more note, my CSS in the _layout looks like this:
<environment names="Development">
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
I don't think it's required to be broken out, but I haven't tried it not broken out...
With Reference to a similar problem posted on StackOverflow: ASP.NET 5 MVC6 Custom CSS & Javascript placing convention
I placed the CSS File in the wwwroot directory, in a css folder.
Then, in my Layout file, I changed the href attribute:
<link rel="stylesheet" href="#Url.Content("../css/style.css")"/>
Finally, I made sure I had app.UseStaticFiles() in my Configure method:
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
app.UseMvc(config => config.MapRoute(
name: "Default",
template: "{Controller}/{action}/{id?}",
defaults: new {controller = "Home", action = "Index"}
));
}

Css is not working properly in asp.net mvc3 Razor Views

I have a application on asp.net mvc3 and working in a razor view.
On my layout page I attach a css file and put some css in that file, but when I access /Account/LogOn view the css is not working.
It only works if I attach the css on Logon view. Anyone know why my css attached on the layout page is not working on /Account/LogOn?
I also tried by including following code:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "xyz.com – Login";
}
It is still not working. Thanks in advance
Refer your css using url helper
like this
<link rel="stylesheet" type="text/css" href="#Url.Content("~/Content/default.css")" media="screen" />
In your _layout.cshtml, ensure that you use a path referencing the root (~) of your application. Use #Url.Content() to escape the path:
<link href="#Url.Content("~/Content/css/styles.css")" rel="stylesheet" type="text/css" />
Create the stylesheet under the folder Contents by the name say abc.css
Now include the stylesheet in the LayoutPage so that it is included automatically in all the pages derived from the content page.
<link href="#Url.Content("~/Content/abc.css")" rel="stylesheet" type="text/css" />

CSS and images on Master Page

I have this quite popular problem, but have failed to find a solution that works.
Basicly, I am using a Master Page (/Masterpages/Default.master), that includes
<link href="../css/style.css" rel="stylesheet" type="text/css />
And it also includes some images with the same relative linking.
But when I apply the Master Page to content pages (in diffrent folderlevels) the css formating and images is lost.
Is there anyway to dynamicaly solve the folderlevel links to css and images to all content pages using the masterpage?
Thanks in advance
UPDATE:
There is an additional problem. It's tricky to get the output to render correctly in both the browser and in design view in Visual Studio.
I got it to work by using the asp:image solution for the images in the masterpage and by double linking the css in the masterpage, one to make it render in VS and one to make it render correctly browsing the site.
<link href="../css/style.css" rel="stylesheet" type="text/css" />
<link href="<%=ResolveUrl("~/css/style.css")%>" rel="stylesheet" type="text/css" />
best to use:
<link href="<%=ResolveUrl("~/css/style.css") %>" rel="stylesheet" type="text/css />
since this will cope with iis application roots unlike:
<link href="/css/style.css" rel="stylesheet" type="text/css />
You can make your link runat="server" and use tilde mapping to make the CSS path relative to the site root.
<link runat="server" id="siteStyle"
href="~/css/style.css"
rel="stylesheet"
type="text/css" />
The images referenced in the CSS should be relative to the location of the CSS file and should resolve normally once the CSS file itself is included properly. For images in tags on the page, you would need to use the ASP:Image control and, again, use the tilde mapping for a path relative to the root.
Fairly sure this will work
<link href="/css/style.css" rel="stylesheet" type="text/css />
/ takes you to the root of your site
You can use the tilde to get the link to work from anywhere. This will work in Images as well.
<link runat="server" href="~/css/style.css" rel="stylesheet" type="text/css />
Images in CSS are relative to the file they are referenced from.
(An exception from this is the "filter" rule in Internet Explorer which is used for PNG fixes. The images in this case are relative to the HTML document.)
Yes, the problem is that the materpage is using a relative url to load the CSS:
"../css/style.css"
you need to change this to the site root (depending on the location of your css files) something like:
"/css/style.css"
than all the various folder levels can use the same url.
Actually, master pages will rebase css files for you automatically, without you having to add runat="server". Be sure that your css file is located one directory down in the folder you specified.
You can use an absolute path to the css file, but visual studio doesn't seem to render the styles in design view when you do this. Also, sometime you won't know if you're going to be running in a virtual directory, so it's not always ideal to use the absolute path.
Also, use relative links to your image assests from the css file itself - which will work irrespective of how you link to your stylesheet.
You might also be interested in looking into themes and skins.
ASP.NET Themes and Skins Overview

Resources