I try to add CSS to my HTML page in Spring Boot using Thymeleaf, added the CSS file in static folder and linked it that way:
<link rel="stylesheet" th:href="@{/css/home.css}" href="../../css/home.css" />
but it doesn't work.
I wanted to stop accessing CSS and js in the URL so I added this method to my security configuration:
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/static/**"); // #3
}
Can anyone tell me what's my error or if any configuration needed?
.css
and .js
are static resources and Spring Boot maps it by default in your /resources/static
folder
For example:
There is a style.css
file that is located in /resources/static/css/style.css
If you want to access it throught thymeleaf add this to your html head section:
<link th:href="@{/css/style.css}" rel="stylesheet" />
Just an observation here, if your are using @EnableWebMvc
annotation then you should map the static resources by your own configuration.
EDIT
i wanted to stop accessing CSS and js in the URL so I added this method to my security configuration
All the resources should get access from browser otherwise the .css
and .js
will not be loaded.
If you need to get access to the resources only for authenticated users you can try the following configuration:
/resources/static
folder and create two sub-folders, One for resources for anonymous users public
and other for authenticated users private
./resources/static/public
folder./resources/static/private
folder./private
url private with this configuration: .antMatchers( "/private/**").authenticated()
and make /public
accessible for anonymous users: .antMatchers( "/public/**").permitAll()
Example for the security configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers( "/public/**").permitAll()
.antMatchers( "/private/**").authenticated()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
;
}
}
Finally try to access the public resources, for example if you have a style.css
file under public folder, then try to access it: http://localhost:808/public/style.css
, the browser should display the style.css content.
When you try to access the private folder (without authentication), for example there is a private.css under private folder then try it: http://localhost:808/private/private.css
. You should get redirected to login page, that means that you should login first and after that spring will let you to access to private.css
resource.
Regarding to thymeleaf it is the same approach, for public html pages use the public resources: <link th:href="@{/public/public.css}" rel="stylesheet" />
and for protected resources user private soruces <link th:href="@{/private/syle.css}" rel="stylesheet" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With