.css
和.js
是静态资源,Spring Boot将其默认映射到您的/resources/static
文件夹中
例如:
有一个style.css
文件如果要访问它throught thymeleaf添加到您的HTML头部分,其位于/resources/static/css/style.css
:
<link th:href="@{/css/style.css}" rel="stylesheet" />
只是一个观察这里,如果您使用的是@EnableWebMvc
注释,那么您应该通过您自己的配置映射静态资源。
编辑
我想停止访问CSS和JS的URL,所以我说这个方法对我的安全配置
所有的资源应该从浏览器,否则.css
和.js
访问将不会被加载。
如果您需要获得对资源的访问只有通过验证的用户可以尝试以下配置:
- 转到
/resources/static
文件夹,并创建两个子文件夹,一个是资源的匿名用户public
和其他认证用户private
。
- 将所有公共资源放到
/resources/static/public
文件夹中。
- 将所有私人资源放入
/resources/static/private
文件夹。
- 转到你的春季安全配置类,让你
/private
网址私人使用此配置:.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()
;
}
}
最后尝试访问公共资源,例如,如果公用文件夹下有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" />
和保护资源的用户私人soruces <link th:href="@{/private/syle.css}" rel="stylesheet" />
非常感谢你,我删除@EnableWebMvc,一切工作正常 –
但如何我可以停止从URL访问..css和.js吗? –
请参阅我的编辑,我不确定是否您正在寻找。 –