.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:
- Go to the
/resources/static
folder and create two sub-folders, One for resources for anonymous users public
and other for authenticated users private
.
- Put all public resources to the
/resources/static/public
folder.
- Put all private resources to the
/resources/static/private
folder.
- Go to your Spring Security Configuration Class and make your
/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" />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…