项目文件;
名称
pom.xml
;内容
(01)总的
<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.0modelVersion> <parent> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>2.5.9version> <relativePath/> parent> <groupId>com.examplegroupId> <artifactId>SpringDemoartifactId> <version>0.0.1-SNAPSHOTversion> <name>SpringDemoname> <description>Demo project for Spring Bootdescription> <properties> <java.version>8java.version> properties> <dependencies> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> plugin> plugins> build> project>
(02)依赖1
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency>
(03)依赖2
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> dependency>
名称
DemoController.java
;内容
(01)总的
package com.example.springdemo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DemoController { @GetMapping("demo_a") public String demo_a() { System.out.println("【DemoController.demo_a】......"); return "This is demo_a method......"; } @GetMapping("demo_b") public String demo_b() { System.out.println("【DemoController.demo_b】......"); return "This is demo_b method......"; } }
(02)方法1
@GetMapping("demo_a") public String demo_a() { System.out.println("【DemoController.demo_a】......"); return "This is demo_a method......"; }
(03)方法2
@GetMapping("demo_b") public String demo_b() { System.out.println("【DemoController.demo_b】......"); return "This is demo_b method......"; }
名称
pom.xml
;内容
(01)总的
<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.0modelVersion> <parent> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>2.5.9version> <relativePath/> parent> <groupId>com.examplegroupId> <artifactId>SpringDemoartifactId> <version>0.0.1-SNAPSHOTversion> <name>SpringDemoname> <description>Demo project for Spring Bootdescription> <properties> <java.version>8java.version> properties> <dependencies> <dependency> <groupId>com.github.xiaoymingroupId> <artifactId>knife4j-spring-boot-starterartifactId> <version>2.0.9version> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> plugin> plugins> build> project>
(02)依赖1
<dependency> <groupId>com.github.xiaoymingroupId> <artifactId>knife4j-spring-boot-starterartifactId> <version>2.0.9version> dependency>
名称
application.properties
;内容
(01)总的
# 开启Knife4j增强模式 knife4j.enable=true
名称
Knife4jConfiguration.java
;内容
(01)总的
package com.example.springdemo.config; import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; /** * Knife4j配置类 * * @author SUNxRUN */ @Configuration @EnableSwagger2WebMvc public class Knife4jConfiguration { /** * 【重要】指定Controller包路径 */ private String basePackage = "com.example.springdemo.controller"; /** * 分组名称 */ private String groupName = "略"; /** * 【主页】题目 */ private String title = "在线API文档"; /** * 【主页】简介 */ private String description = "前后交互"; /** * 【主页】作者 */ private String contactName = "SUNxRUN"; /** * 【主页】版本 */ private String version = "1.0.0"; /** * 【主机】host */ private String host = "http://localhost:9081"; /** * 【主页】服务URL */ private String termsOfServiceUrl = "http://www.apache.org/licenses/LICENSE-2.0"; /** * 联系网址 */ private String contactUrl = "略"; /** * 联系邮箱 */ private String contactEmail = "略"; @Autowired private OpenApiExtensionResolver openApiExtensionResolver; public Knife4jConfiguration() { System.out.println("【配置类】Knife4jConfiguration-----已运行"); } @Bean public Docket docket() { String groupName = "1.0.0"; Docket docket = new Docket(DocumentationType.SWAGGER_2) .host(host) .apiInfo(apiInfo()) .groupName(groupName) .select() .apis(RequestHandlerSelectors.basePackage(basePackage)) .paths(PathSelectors.any()) .build() .extensions(openApiExtensionResolver.buildExtensions(groupName)); return docket; } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(title) .description(description) .termsOfServiceUrl(termsOfServiceUrl) .contact(new Contact(contactName, contactUrl, contactEmail)) .version(version) .build(); } }
名称
pom.xml
;内容
(01)总的
<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.0modelVersion> <parent> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>2.5.9version> <relativePath/> parent> <groupId>com.examplegroupId> <artifactId>SpringDemoartifactId> <version>0.0.1-SNAPSHOTversion> <name>SpringDemoname> <description>Demo project for Spring Bootdescription> <properties> <java.version>8java.version> properties> <dependencies> <dependency> <groupId>io.jsonwebtokengroupId> <artifactId>jjwtartifactId> <version>0.9.1version> dependency> <dependency> <groupId>com.github.xiaoymingroupId> <artifactId>knife4j-spring-boot-starterartifactId> <version>2.0.9version> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> plugin> plugins> build> project>
(02)依赖1
<dependency> <groupId>io.jsonwebtokengroupId> <artifactId>jjwtartifactId> <version>0.9.1version> dependency>
名称
JwtTests.java
;内容
(01)总的
package com.example.springdemo; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.junit.jupiter.api.Test; import java.util.Date; import java.util.HashMap; import java.util.Map; public class JwtTests { @Test public void testGenerateJwt() { // 准备`claims` Map<String, Object> claims = new HashMap<>(); claims.put("id", 1); claims.put("name", "SUNxRUN"); // 准备`过期时间(设置:10年)` Date expirationDate = new Date(System.currentTimeMillis() + 525600 * 10 * 60 * 1000); // 准备`密钥` String secretKey = "1234567890"; // JWT的组成部分:Header(头)、Payload(载荷)、Signature(签名) String jwt = Jwts.builder() // Header:用于配置算法与此结果数据的类型 // 通常配置两个属性:tye(类型)、alg(算法) .setHeaderParam("typ", "jwt") .setHeaderParam("alg", "HS256") // Payload:用于配置需要封装到JWT中的数据 .setClaims(claims) .setExpiration(expirationDate) // Signature:用于指定算法与密钥(盐) .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); System.out.println(jwt); } @Test public void testParseJwt() { // `密钥` String secretKey = "1234567890"; // `JWT` String jwt = "eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiU1VOeFJVTiIsImlkIjoxLCJleHAiOjE3MDc0NzcyNDR9.stHmCODCatUhNQ6M9_tYQfR4ay0rRd0wQIMZgYXKyhY"; Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody(); Object id = claims.get("id"); System.out.println("id=" + id); Object name = claims.get("name"); System.out.println("name=" + name); } }
方法1
@Test public void testGenerateJwt() { // 准备`claims` Map<String, Object> claims = new HashMap<>(); claims.put("id", 1); claims.put("name", "SUNxRUN"); // 准备`过期时间(设置:10年)` Date expirationDate = new Date(System.currentTimeMillis() + 525600 * 10 * 60 * 1000); // 准备`密钥` String secretKey = "1234567890"; // JWT的组成部分:Header(头)、Payload(载荷)、Signature(签名) String jwt = Jwts.builder() // Header:用于配置算法与此结果数据的类型 // 通常配置两个属性:tye(类型)、alg(算法) .setHeaderParam("typ", "jwt") .setHeaderParam("alg", "HS256") // Payload:用于配置需要封装到JWT中的数据 .setClaims(claims) .setExpiration(expirationDate) // Signature:用于指定算法与密钥(盐) .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); System.out.println(jwt); }
方法2
@Test public void testParseJwt() { // `密钥` String secretKey = "1234567890"; // `JWT` String jwt = "eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiU1VOeFJVTiIsImlkIjoxLCJleHAiOjE3MDc0NzcyNDR9.stHmCODCatUhNQ6M9_tYQfR4ay0rRd0wQIMZgYXKyhY"; Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody(); Object id = claims.get("id"); System.out.println("id=" + id); Object name = claims.get("name"); System.out.println("name=" + name); }
名称
pom.xml
;内容
(01)总的
4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.9 com.example SpringDemo 0.0.1-SNAPSHOT SpringDemo Demo project for Spring Boot 8 org.springframework.boot spring-boot-starter-security io.jsonwebtoken jjwt 0.9.1 com.github.xiaoymin knife4j-spring-boot-starter 2.0.9 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin (02)依赖1
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-securityartifactId> dependency>
名称
BCryptTests.java
;内容
(01)总的
package com.example.springdemo; import org.junit.jupiter.api.Test; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class BCryptTests { @Test public void testBCrypt() { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String rawPassword = "123456"; String encodedPassword = passwordEncoder.encode(rawPassword); System.out.println(encodedPassword); } }
(02)方法1
@Test public void testBCrypt() { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String rawPassword = "123456"; String encodedPassword = passwordEncoder.encode(rawPassword); System.out.println(encodedPassword); }
名称
UserDetailsServiceImpl.java
;内容
(01)总的
package com.example.springdemo.security; 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.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { System.out.println("`Spring Security`会自动根据用户名查询用户详情!【用户名】:" + s); if ("LinShiYongHu".equals(s)) { UserDetails userDetails = User.builder() .username("LinShiYongHu") .password("$2a$10$sgbF5BycuObR79id8Y08U.Mg.YAMJCU2TPBqzSUqu5zg401iGMUcu") // 密码:123456 .disabled(false) // 账号是否禁用 .accountLocked(false) // 账号是否锁定 .accountExpired(false) // 账号是否过期 .authorities("权限信息,暂不处理!") // 账号的权限信息 .build(); return userDetails; } return null; } }
(02)方法1
@Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { System.out.println("`Spring Security`会自动根据用户名查询用户详情!【用户名】:" + s); if ("LinShiYongHu".equals(s)) { UserDetails userDetails = User.builder() .username("LinShiYongHu") .password("$2a$10$sgbF5BycuObR79id8Y08U.Mg.YAMJCU2TPBqzSUqu5zg401iGMUcu") // 密码:123456 .disabled(false) // 账号是否禁用 .accountLocked(false) // 账号是否锁定 .accountExpired(false) // 账号是否过期 .authorities("权限信息,暂不处理!") // 账号的权限信息 .build(); return userDetails; } return null; }
名称
SecurityConfiguration.java
;内容
(01)总的
package com.example.springdemo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class SecurityConfiguration { @Bean public PasswordEncoder passwordEncoder() { System.out.println("创建密码编辑器组件:BCryptPasswordEncoder......"); return new BCryptPasswordEncoder(); } }
(02)方法1
@Bean public PasswordEncoder passwordEncoder() { System.out.println("创建密码编辑器组件:BCryptPasswordEncoder......"); return new BCryptPasswordEncoder(); }