.css 和 .js 是静态资源,Spring Boot 默认将其映射到您的 /resources/static 文件夹中
例如:
有一个style.css 文件位于/resources/static/css/style.css
如果您想通过 thymeleaf 访问它,请将其添加到您的 html 头部部分:
<link th:href="@{/css/style.css}" rel="stylesheet" />
这里只是一个观察,如果你使用@EnableWebMvc注解,那么你应该通过你自己的配置来映射静态资源。
编辑
我想停止访问 URL 中的 CSS 和 js,所以我将此方法添加到我的安全配置中
所有资源都应该从浏览器访问,否则.css和.js将不会被加载。
如果您只需要通过身份验证的用户访问资源,您可以尝试以下配置:
- 转到
/resources/static 文件夹并创建两个子文件夹,一个用于匿名用户public 的资源,另一个用于经过身份验证的用户private。
- 将所有公共资源放到
/resources/static/public文件夹中。
- 将所有私有资源放到
/resources/static/private文件夹中。
- 转到您的 Spring Security 配置类并使用此配置将您的
/private url 设为私有:.antMatchers( "/private/**").authenticated() 并使 /public 可供匿名用户访问:.antMatchers( "/public/**").permitAll()
安全配置示例:
@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()
;
}
}
最后尝试访问公共资源,比如你的public文件夹下有style.css文件,然后尝试访问:http://localhost:808/public/style.css,浏览器应该会显示style.css内容。
当您尝试访问私有文件夹时(无需身份验证),例如私有文件夹下有一个 private.css 则尝试:http://localhost:808/private/private.css。你应该被重定向到登录页面,这意味着你应该先登录,然后春天会让你访问private.css资源。
对于 thymeleaf,它是相同的方法,对于公共 html 页面使用公共资源:<link th:href="@{/public/public.css}" rel="stylesheet" />,对于受保护资源,用户私有资源 <link th:href="@{/private/syle.css}" rel="stylesheet" />