1.前言
以前開發一直使用 springMVC模式開發 ,前端頁面常使用 JSP ,現在html5淘汰了 ,要么使用html ,要么使用vue ,
現在使用spring boot ,有必要總結一下 spring boot 對html 的操作 。
2.環境
spring boot 2.1.6.RELEASE
3.操作
(1)下載依賴
<!--spring security 依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--訪問靜態資源--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
完整pom

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>security-5500</artifactId> <version>0.0.1-SNAPSHOT</version> <name>security-5500</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!--spring security 依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--訪問靜態資源--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
(2)目錄結構
(3)resources 里的static包是存放靜態資源的 ,static下面新建一個img包 ,里面放一個圖片文件
啟動后,直接輸入網址 http://localhost:5500/img/xx.png 即可訪問 ,不會被security攔截
【只要pom加了security依賴包 ,將默認啟動security,默認賬戶名 為 user
密碼是打印台打印的 隨機數
】
(4)使用了thymeleaf 模板 ,那么html文件必須放在 路徑為 resources/templates 的文件夾里面
否則spring boot 掃描不到文件 ,當然,也是可以修改的需要在application配置文件里修改
完整的pom.xml

spring.application.name=security-5500 # 應用服務web訪問端口 server.port=5500 #配置security登錄賬戶密和密碼 ,不配置則默認賬戶是user,密碼是隨機生成的字符串,打印在啟動欄中 #spring.security.user.name=11 #spring.security.user.password=22 # ## ## ## ## Enable template caching. #spring.thymeleaf.cache=true ## Check that the templates location exists. #spring.thymeleaf.check-template-location=true ## Content-Type value. ##spring.thymeleaf.content-type=text/html ## Enable MVC Thymeleaf view resolution. #spring.thymeleaf.enabled=true ## Template encoding. #spring.thymeleaf.encoding=utf-8 ## Comma-separated list of view names that should be excluded from resolution. #spring.thymeleaf.excluded-view-names= ## Template mode to be applied to templates. See also StandardTemplateModeHandlers. #spring.thymeleaf.mode=HTML5 ## Prefix that gets prepended to view names when building a URL. ##設置html文件位置 #spring.thymeleaf.prefix=classpath:/templates/ ## Suffix that gets appended to view names when building a URL. #spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
(5)新建html文件
新建一個名為 index.html的文件 ,使用了 thymeleaf 模板的語法 th:href="@{/home}" 進行跳轉 ,這個 /home路徑是虛擬路徑 ,需要設置的,待會展示
<!DOCTYPE html> <html lang="zh" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> 你好 ,世界 ,2333 <p>點擊 <a th:href="@{/home}">我</a> 去home.html頁面</p> </body> </html>
新建一個名為 home.html的文件
<!DOCTYPE html> <html lang="zh" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta charset="UTF-8"> <title>security首頁</title> </head> <body> <h1>Welcome!你好,世界</h1> <p>Click <a th:href="@{/hai}">here</a> to see a greeting.</p> </body> </html>
新建一個名為 hai.html的文件
<!DOCTYPE html> <html lang="zh" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta charset="UTF-8"> <title>hai文件</title> </head> <body> 你好呀世界,成功登錄進來了 </body> </html>
新建一個名為 kk.html的文件,用於測試html文件獲取靜態文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>kk</title> </head> <body> <img src="img/xx.png" alt=""> </body> </html>
還需要新建一個login.html文件 ,待會用來作為security的自定義登錄頁面
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Spring Security自定義</title> </head> <body> <div th:if="${param.error}"> Invalid username and password. </div> <div th:if="${param.logout}"> You have been logged out. </div> <form th:action="@{/login}" method="post"> <div><label> User Name : <input type="text" name="username"/> </label></div> <div><label> Password: <input type="password" name="password"/> </label></div> <div><input type="submit" value="Sign In"/></div> </form> <br> lalallalalal啊是德國海 </body> </html>
(6)設置虛擬路徑用於訪問html文件 【springMVC的視圖設置一樣,但是,不需要配置,直接引入 thymeleaf 即可使用】
在controller層
package com.example.security5500.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MVCController {
@RequestMapping("/home")
public String home() {
return "home";
}
@RequestMapping("/login")
public String login(){
return "login";
}
@RequestMapping("/hai")
public String hai() {
return "hai";
}
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("kk")
public String kk() {
return "kk";
}
//心得,index.html默認是首頁,當沒有指定路徑 / 是哪個文件時 index.html將默認是根路徑/
}
(7)測試
啟動類沒有改變 ,默認即可
啟動程序,訪問 http://localhost:5500/ 將會彈出security頁面
輸入默認賬戶和密碼 即可跳轉index.html頁面
點擊 “我” ,可跳轉到home.html頁面
【注意 ,必須配置好了 html文件的虛擬路徑
thymeleaf 模板語法
才可以使用,否則提示404
】
好了,到了這里已經完整的解釋了 spring boot 怎么使用html作為前端頁面開發
(8)修改security的攔截規則
新建 文件 WebSecurityConfig
源碼

package com.example.security5500.securityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//定義了哪些URL路徑應該被保護,哪些不應該。具體來說,“/”和“/ home”路徑被配置為不需要任何身份驗證。所有其他路徑必須經過身份驗證。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//設置不攔截頁面,可直接通過,路徑訪問 "/", "/index", "/home" 則不攔截
.authorizeRequests()
.antMatchers("/", "/index", "/home").permitAll()
.anyRequest().authenticated()
.and()
//設置自定義登錄頁面
.formLogin()
.loginPage("/login")
.permitAll()
.and()
//設置自定義登出頁面
.logout()
// .logoutUrl("/mylogout")
.permitAll();
}
}
再次啟動工程
訪問 http://localhost:5500/ 可直接進入頁面了 ,不需要security 驗證
訪問 http://localhost:5500/hai 會被security攔截 ,將進入配置的自定義登錄頁面
登錄后才可以跳轉 hai.html
(9)登出
登出 security 網址訪問 http://localhost:5500/login?logout ,點擊藍色大按鈕即可
4.如何修改security的賬戶與密碼?
(1)方法一 :
application配置文件添加屬性
#配置security登錄賬戶密和密碼 ,不配置則默認賬戶是user,密碼是隨機生成的字符串,打印在啟動欄中
spring.security.user.name=11
spring.security.user.password=22
完整源碼

spring.application.name=security-5500
# 應用服務web訪問端口
server.port=5500
#配置security登錄賬戶密和密碼 ,不配置則默認賬戶是user,密碼是隨機生成的字符串,打印在啟動欄中
spring.security.user.name=11
spring.security.user.password=22
#
##
##
##
## Enable template caching.
#spring.thymeleaf.cache=true
## Check that the templates location exists.
#spring.thymeleaf.check-template-location=true
## Content-Type value.
##spring.thymeleaf.content-type=text/html
## Enable MVC Thymeleaf view resolution.
#spring.thymeleaf.enabled=true
## Template encoding.
#spring.thymeleaf.encoding=utf-8
## Comma-separated list of view names that should be excluded from resolution.
#spring.thymeleaf.excluded-view-names=
## Template mode to be applied to templates. See also StandardTemplateModeHandlers.
#spring.thymeleaf.mode=HTML5
## Prefix that gets prepended to view names when building a URL.
##設置html文件位置
#spring.thymeleaf.prefix=classpath:/templates/
## Suffix that gets appended to view names when building a URL.
#spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
(2)方法二:
進入剛才配置security規則的文件 WebSecurityConfig ,直接將用戶設置在內存中
//將單個用戶設置在內存中 ,在這里設置了用戶信息,那么application的登錄信息則不需要寫
@Bean
@Override
protected UserDetailsService userDetailsService() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
UserDetails user = User
.withUsername("user")
.password(encoder.encode("11"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
完整源碼

package com.example.security5500.securityConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { //定義了哪些URL路徑應該被保護,哪些不應該。具體來說,“/”和“/ home”路徑被配置為不需要任何身份驗證。所有其他路徑必須經過身份驗證。 @Override protected void configure(HttpSecurity http) throws Exception { http //設置不攔截頁面,可直接通過,路徑訪問 "/", "/index", "/home" 則不攔截 .authorizeRequests() .antMatchers("/", "/index", "/home").permitAll() .anyRequest().authenticated() .and() //設置自定義登錄頁面 .formLogin() .loginPage("/login") .permitAll() .and() //設置自定義登出頁面 .logout() // .logoutUrl("/mylogout") .permitAll(); } //將單個用戶設置在內存中 ,在這里設置了用戶信息,那么application的登錄信息則不需要寫 @Bean @Override protected UserDetailsService userDetailsService() { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); UserDetails user = User .withUsername("user") .password(encoder.encode("11")) .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }
(3)方法三:
仍然是修改 配置security規則的文件 WebSecurityConfig
//可以使用以下配置在內存中進行注冊公開內存的身份驗證{@link UserDetailsService}: // 在內存中添加 user 和 admin 用戶 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication().withUser("user").password("11").roles("USER").and() .withUser("admin").password("11").roles("USER", "ADMIN"); } // 將 UserDetailsService 顯示為 Bean @Bean @Override public UserDetailsService userDetailsServiceBean() throws Exception { return super.userDetailsServiceBean(); } @Bean public static NoOpPasswordEncoder passwordEncoder() { return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance(); }
完整源碼

package com.example.security5500.securityConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { //定義了哪些URL路徑應該被保護,哪些不應該。具體來說,“/”和“/ home”路徑被配置為不需要任何身份驗證。所有其他路徑必須經過身份驗證。 @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() //設置不攔截頁面,可直接通過,路徑訪問 "/", "/index", "/home" 則不攔截 .antMatchers("/", "/index", "/home").permitAll() .anyRequest().authenticated() .and() //設置自定義登錄頁面 .formLogin() .loginPage("/login") .permitAll() .and() //設置自定義登出頁面 .logout() // .logoutUrl("/mylogout") .permitAll(); } //可以使用以下配置在內存中進行注冊公開內存的身份驗證{@link UserDetailsService}: // 在內存中添加 user 和 admin 用戶 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication().withUser("user").password("11").roles("USER").and() .withUser("admin").password("11").roles("USER", "ADMIN"); } // 將 UserDetailsService 顯示為 Bean @Bean @Override public UserDetailsService userDetailsServiceBean() throws Exception { return super.userDetailsServiceBean(); } @Bean public static NoOpPasswordEncoder passwordEncoder() { return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance(); } }
注意:
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
這一個方法是用來設置加密方式的額 ,NoOpPasswordEncoder是不加密的意思,雖然不加密,但是少了會報錯,
處理該加密方式外還有 BCryptPasswordEncoder 、SCryptPasswordEncoder 等 ,詳細可查看我的其他隨筆
【注意: 三個方法任選一個都可以修改登錄賬號密碼,但是,方法2和3不能同時使用 ,如果WebSecurityConfig 和application 文件 都寫上 ,會導致application配置文件設置的賬號密碼失效,僅WebSecurityConfig內的方法設置的有效】