.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嗎? –
請參閱我的編輯,我不確定是否您正在尋找。 –