Compare commits
5 Commits
539dc41868
...
e8afe9a5f4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8afe9a5f4 | ||
|
|
efcfe7e012 | ||
|
|
8f93488989 | ||
|
|
2d4598cc69 | ||
|
|
6a4c6a369a |
29
pom.xml
29
pom.xml
@@ -37,6 +37,35 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 参数校验 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 仅用于学习的可选鉴权演示(不影响主流程) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>0.12.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>0.12.3</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>0.12.3</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- 测试 -->
|
||||
<dependency>
|
||||
|
||||
@@ -7,25 +7,31 @@
|
||||
=========|_|==============|___/=/_/_/_/
|
||||
:: Spring Boot :: (v3.2.0)
|
||||
|
||||
2026-03-06T17:09:02.230Z INFO 1154290 --- [springboot-demo] [ main] com.example.demo.DemoApplication : Starting DemoApplication v0.0.1-SNAPSHOT using Java 21.0.10 with PID 1154290 (/home/llm/projects/springboot-demo/target/demo-0.0.1-SNAPSHOT.jar started by llm in /home/llm/projects/springboot-demo)
|
||||
2026-03-06T17:09:02.380Z INFO 1154290 --- [springboot-demo] [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default"
|
||||
2026-03-06T17:10:05.868Z INFO 1154290 --- [springboot-demo] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port 8082 (http)
|
||||
2026-03-06T17:10:06.093Z INFO 1154290 --- [springboot-demo] [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
|
||||
2026-03-06T17:10:06.093Z INFO 1154290 --- [springboot-demo] [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.16]
|
||||
2026-03-06T17:10:07.996Z INFO 1154290 --- [springb2026-03-06T17:10:12.808Z INFO 1153691 --- [springboot-demo] [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint(s) beneath base path '/actuator'
|
||||
2026-03-06T17:10:14.838Z INFO 1153691 --- [springboot-demo] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat start2026-03-06T17:10:23.314Z INFO 1154290 --- [springboot-demo] [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
|
||||
2026-03-06T17:10:40.414Z INFO 1154290 --- [springboot-demo] [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint(s) beneath base path '/actuator'
|
||||
2026-03-06T17:10:41.395Z INFO 1154290 --- [springboot-demo] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port 8082 (http) with context path ''
|
||||
2026-03-06T17:10:41.541Z INFO 1154290 --- [springboot-demo] [ main] com.example.demo.DemoApplication : Started DemoApplication in 116.974 seconds (process running for 133.101)
|
||||
2026-03-07T08:12:47.326Z INFO 1374194 --- [springboot-demo] [ main] com.example.demo.DemoApplication : Starting DemoApplication v0.0.1-SNAPSHOT using Java 21.0.10 with PID 1374194 (/home/llm/projects/springboot-demo/target/demo-0.0.1-SNAPSHOT.jar started by llm in /home/llm/projects/springboot-demo)
|
||||
2026-03-07T08:12:47.356Z INFO 1374194 --- [springboot-demo] [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default"
|
||||
2026-03-07T08:13:00.941Z INFO 1374194 --- [springboot-demo] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port 8082 (http)
|
||||
2026-03-07T08:13:01.016Z INFO 1374194 --- [springboot-demo] [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
|
||||
2026-03-07T08:13:01.020Z INFO 1374194 --- [springboot-demo] [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.16]
|
||||
2026-03-07T08:13:01.808Z INFO 1374194 --- [springboot-demo] [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
|
||||
2026-03-07T08:13:01.814Z INFO 1374194 --- [springboot-demo] [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 13966 ms
|
||||
2026-03-07T08:13:07.411Z INFO 1374194 --- [springboot-demo] [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
|
||||
2026-03-07T08:13:15.547Z INFO 1374194 --- [springboot-demo] [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint(s) beneath base path '/actuator'
|
||||
2026-03-07T08:13:16.328Z INFO 1374194 --- [springboot-demo] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port 8082 (http) with context path ''
|
||||
2026-03-07T08:13:16.450Z INFO 1374194 --- [springboot-demo] [ main] com.example.demo.DemoApplication : Started DemoApplication in 33.141 seconds (process running for 36.573)
|
||||
[EventListener] Spring Boot 应用启动完成!
|
||||
2026-03-06T17:11:05.601Z INFO 1154290 --- [springboot-demo] [nio-8082-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
|
||||
2026-03-06T17:11:05.601Z INFO 1154290 --- [springboot-demo] [nio-8082-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
|
||||
2026-03-06T17:11:05.619Z INFO 1154290 --- [springboot-demo] [nio-8082-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 13 ms
|
||||
2026-03-07T08:13:47.186Z INFO 1374194 --- [springboot-demo] [nio-8082-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
|
||||
2026-03-07T08:13:47.186Z INFO 1374194 --- [springboot-demo] [nio-8082-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
|
||||
2026-03-07T08:13:47.195Z INFO 1374194 --- [springboot-demo] [nio-8082-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
|
||||
[AOP-Before] Controller 方法开始: root
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: root
|
||||
返回值: {aop=https://spring.xiaoxiaoluohao.indevs.in/aop, learn=https://spring.xiaoxiaoluohao.indevs.in/learn, api=https://spring.xiaoxiaoluohao.indevs.in/api/users, message=欢迎来到 Spring Boot 学习脚手架!}
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 18ms
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 8ms
|
||||
[AOP-Before] Controller 方法开始: root
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: root
|
||||
返回值: {aop=https://spring.xiaoxiaoluohao.indevs.in/aop, learn=https://spring.xiaoxiaoluohao.indevs.in/learn, api=https://spring.xiaoxiaoluohao.indevs.in/api/users, message=欢迎来到 Spring Boot 学习脚手架!}
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 3ms
|
||||
[AOP-Before] Controller 方法开始: root
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: root
|
||||
@@ -35,4 +41,56 @@
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: root
|
||||
返回值: {aop=https://spring.xiaoxiaoluohao.indevs.in/aop, learn=https://spring.xiaoxiaoluohao.indevs.in/learn, api=https://spring.xiaoxiaoluohao.indevs.in/api/users, message=欢迎来到 Spring Boot 学习脚手架!}
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 3ms
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 10ms
|
||||
[AOP-Before] Controller 方法开始: getAllUsers
|
||||
参数: []
|
||||
[AOP-After] Service 方法结束: findAll
|
||||
[AOP-Performance] UserService.findAll() 执行耗时: 2ms
|
||||
[AOP-AfterReturning] 方法返回: getAllUsers
|
||||
返回值: [com.example.demo.model.User@3616c07a, com.example.demo.model.User@a6b1d0f, com.example.demo.model.User@7935776c]
|
||||
[AOP-Performance] UserController.getAllUsers() 执行耗时: 5ms
|
||||
[AOP-Before] Controller 方法开始: info
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: info
|
||||
返回值: {app=springboot-demo, endpoints=[Ljava.lang.String;@6c7b5bf1, message=欢迎学习 Spring Boot!}
|
||||
[AOP-Performance] LearnController.info() 执行耗时: 2ms
|
||||
[AOP-Before] Controller 方法开始: index
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: index
|
||||
返回值: {endpoints=[Ljava.lang.String;@1b97f799, topics=[Ljava.lang.String;@1fa86033, message=Spring Boot 学习中心}
|
||||
[AOP-Performance] AopEventController.index() 执行耗时: 11ms
|
||||
[AOP-Before] Controller 方法开始: root
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: root
|
||||
返回值: {aop=https://spring.xiaoxiaoluohao.indevs.in/aop, learn=https://spring.xiaoxiaoluohao.indevs.in/learn, api=https://spring.xiaoxiaoluohao.indevs.in/api/users, message=欢迎来到 Spring Boot 学习脚手架!}
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 6ms
|
||||
[AOP-Before] Controller 方法开始: index
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: index
|
||||
返回值: {endpoints=[Ljava.lang.String;@63de5cba, topics=[Ljava.lang.String;@67e1d419, message=Spring Boot 学习中心}
|
||||
[AOP-Performance] AopEventController.index() 执行耗时: 1ms
|
||||
[AOP-Before] Controller 方法开始: root
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: root
|
||||
返回值: {aop=https://spring.xiaoxiaoluohao.indevs.in/aop, learn=https://spring.xiaoxiaoluohao.indevs.in/learn, api=https://spring.xiaoxiaoluohao.indevs.in/api/users, message=欢迎来到 Spring Boot 学习脚手架!}
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 0ms
|
||||
[AOP-Before] Controller 方法开始: root
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: root
|
||||
返回值: {aop=https://spring.xiaoxiaoluohao.indevs.in/aop, learn=https://spring.xiaoxiaoluohao.indevs.in/learn, api=https://spring.xiaoxiaoluohao.indevs.in/api/users, message=欢迎来到 Spring Boot 学习脚手架!}
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 0ms
|
||||
[AOP-Before] Controller 方法开始: root
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: root
|
||||
返回值: {aop=https://spring.xiaoxiaoluohao.indevs.in/aop, learn=https://spring.xiaoxiaoluohao.indevs.in/learn, api=https://spring.xiaoxiaoluohao.indevs.in/api/users, message=欢迎来到 Spring Boot 学习脚手架!}
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 0ms
|
||||
[AOP-Before] Controller 方法开始: root
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: root
|
||||
返回值: {aop=https://spring.xiaoxiaoluohao.indevs.in/aop, learn=https://spring.xiaoxiaoluohao.indevs.in/learn, api=https://spring.xiaoxiaoluohao.indevs.in/api/users, message=欢迎来到 Spring Boot 学习脚手架!}
|
||||
[AOP-Performance] LearnController.root() 执行耗时: 2ms
|
||||
[AOP-Before] Controller 方法开始: index
|
||||
参数: []
|
||||
[AOP-AfterReturning] 方法返回: index
|
||||
返回值: {endpoints=[Ljava.lang.String;@22e35681, topics=[Ljava.lang.String;@2214743, message=Spring Boot 学习中心}
|
||||
[AOP-Performance] AopEventController.index() 执行耗时: 0ms
|
||||
|
||||
22
src/main/java/com/example/demo/common/ApiResponse.java
Normal file
22
src/main/java/com/example/demo/common/ApiResponse.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.example.demo.common;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record ApiResponse<T>(
|
||||
int code,
|
||||
String message,
|
||||
T data,
|
||||
Instant timestamp
|
||||
) {
|
||||
public static <T> ApiResponse<T> ok(T data) {
|
||||
return new ApiResponse<>(0, "success", data, Instant.now());
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> ok(String message, T data) {
|
||||
return new ApiResponse<>(0, message, data, Instant.now());
|
||||
}
|
||||
|
||||
public static ApiResponse<Void> fail(int code, String message) {
|
||||
return new ApiResponse<>(code, message, null, Instant.now());
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import com.example.demo.aop.RateLimited;
|
||||
import com.example.demo.event.UserEventPublisher;
|
||||
import com.example.demo.model.User;
|
||||
import com.example.demo.service.UserService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -20,17 +19,20 @@ import java.util.Map;
|
||||
@RequestMapping("/aop")
|
||||
public class AopEventController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
private final UserService userService;
|
||||
private final UserEventPublisher eventPublisher;
|
||||
private final PerformanceAspect performanceAspect;
|
||||
private final RateLimitAspect rateLimitAspect;
|
||||
|
||||
@Autowired
|
||||
private UserEventPublisher eventPublisher;
|
||||
|
||||
@Autowired
|
||||
private PerformanceAspect performanceAspect;
|
||||
|
||||
@Autowired
|
||||
private RateLimitAspect rateLimitAspect;
|
||||
public AopEventController(UserService userService,
|
||||
UserEventPublisher eventPublisher,
|
||||
PerformanceAspect performanceAspect,
|
||||
RateLimitAspect rateLimitAspect) {
|
||||
this.userService = userService;
|
||||
this.eventPublisher = eventPublisher;
|
||||
this.performanceAspect = performanceAspect;
|
||||
this.rateLimitAspect = rateLimitAspect;
|
||||
}
|
||||
|
||||
/**
|
||||
* 学习首页
|
||||
|
||||
@@ -45,7 +45,9 @@ public class LearnController {
|
||||
"POST /learn/body - JSON 请求体示例",
|
||||
"GET /learn/path/{id} - 路径变量示例",
|
||||
"GET /learn/header - 请求头示例",
|
||||
"GET /learn/cookie - Cookie 示例"
|
||||
"GET /learn/cookie - Cookie 示例",
|
||||
"POST /api/auth/login - 学习用 JWT 登录",
|
||||
"GET /api/secure/me - 受保护接口(需 Bearer Token)"
|
||||
});
|
||||
return info;
|
||||
}
|
||||
|
||||
@@ -1,64 +1,54 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import com.example.demo.common.ApiResponse;
|
||||
import com.example.demo.dto.UserRequest;
|
||||
import com.example.demo.model.User;
|
||||
import com.example.demo.service.UserService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户控制器 - RESTful API 示例
|
||||
*
|
||||
* 学习点:
|
||||
* - @RestController: 组合了 @Controller 和 @ResponseBody
|
||||
* - @RequestMapping: 路由映射
|
||||
* - @PathVariable: 路径变量
|
||||
* - @RequestParam: 查询参数
|
||||
* - @RequestBody: 请求体
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/users")
|
||||
public class UserController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
private final UserService userService;
|
||||
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
// GET /api/users - 获取所有用户
|
||||
@GetMapping
|
||||
public List<User> getAllUsers() {
|
||||
return userService.findAll();
|
||||
public ApiResponse<List<User>> getAllUsers() {
|
||||
return ApiResponse.ok(userService.findAll());
|
||||
}
|
||||
|
||||
// GET /api/users/{id} - 获取单个用户
|
||||
@GetMapping("/{id}")
|
||||
public User getUserById(@PathVariable Long id) {
|
||||
return userService.findById(id);
|
||||
public ApiResponse<User> getUserById(@PathVariable Long id) {
|
||||
return ApiResponse.ok(userService.findById(id));
|
||||
}
|
||||
|
||||
// POST /api/users - 创建用户
|
||||
@PostMapping
|
||||
public User createUser(@RequestBody User user) {
|
||||
return userService.save(user);
|
||||
public ApiResponse<User> createUser(@Valid @RequestBody UserRequest req) {
|
||||
User user = new User(null, req.name(), req.email(), req.age());
|
||||
return ApiResponse.ok("创建成功", userService.create(user));
|
||||
}
|
||||
|
||||
// PUT /api/users/{id} - 更新用户
|
||||
@PutMapping("/{id}")
|
||||
public User updateUser(@PathVariable Long id, @RequestBody User user) {
|
||||
user.setId(id);
|
||||
return userService.save(user);
|
||||
public ApiResponse<User> updateUser(@PathVariable Long id, @Valid @RequestBody UserRequest req) {
|
||||
User user = new User(id, req.name(), req.email(), req.age());
|
||||
return ApiResponse.ok("更新成功", userService.update(id, user));
|
||||
}
|
||||
|
||||
// DELETE /api/users/{id} - 删除用户
|
||||
@DeleteMapping("/{id}")
|
||||
public String deleteUser(@PathVariable Long id) {
|
||||
public ApiResponse<Void> deleteUser(@PathVariable Long id) {
|
||||
userService.delete(id);
|
||||
return "用户 " + id + " 已删除";
|
||||
return ApiResponse.ok("删除成功", null);
|
||||
}
|
||||
|
||||
// GET /api/users/search?name=xxx - 搜索用户
|
||||
@GetMapping("/search")
|
||||
public List<User> searchUsers(@RequestParam String name) {
|
||||
return userService.findByName(name);
|
||||
public ApiResponse<List<User>> searchUsers(@RequestParam String name) {
|
||||
return ApiResponse.ok(userService.findByName(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.example.demo.controller.auth;
|
||||
|
||||
import com.example.demo.common.ApiResponse;
|
||||
import com.example.demo.dto.auth.LoginRequest;
|
||||
import com.example.demo.security.LearningJwtUtil;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
public class LearningAuthController {
|
||||
|
||||
private final LearningJwtUtil jwtUtil;
|
||||
|
||||
public LearningAuthController(LearningJwtUtil jwtUtil) {
|
||||
this.jwtUtil = jwtUtil;
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ApiResponse<Map<String, Object>> login(@Valid @RequestBody LoginRequest req) {
|
||||
// 学习演示:仅做最小账号检查
|
||||
if (!(("admin".equals(req.username()) && "admin123".equals(req.password()))
|
||||
|| ("user".equals(req.username()) && "user123".equals(req.password())))) {
|
||||
return new ApiResponse<>(401, "用户名或密码错误", null, java.time.Instant.now());
|
||||
}
|
||||
String token = jwtUtil.generateToken(req.username());
|
||||
return ApiResponse.ok(Map.of(
|
||||
"token", token,
|
||||
"type", "Bearer",
|
||||
"username", req.username(),
|
||||
"tip", "在请求头中加入 Authorization: Bearer <token> 访问 /api/secure/**"
|
||||
));
|
||||
}
|
||||
|
||||
@GetMapping("/mode")
|
||||
public ApiResponse<Map<String, Object>> mode() {
|
||||
return ApiResponse.ok(Map.of(
|
||||
"mode", "learning-jwt",
|
||||
"protectedPath", "/api/secure/**",
|
||||
"defaultAccounts", "admin/admin123, user/user123"
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.example.demo.controller.auth;
|
||||
|
||||
import com.example.demo.common.ApiResponse;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/secure")
|
||||
public class SecureDemoController {
|
||||
|
||||
@GetMapping("/me")
|
||||
public ApiResponse<Map<String, Object>> me(Authentication authentication) {
|
||||
return ApiResponse.ok(Map.of(
|
||||
"principal", authentication.getName(),
|
||||
"authorities", authentication.getAuthorities(),
|
||||
"message", "你已通过学习用 JWT 鉴权"
|
||||
));
|
||||
}
|
||||
}
|
||||
19
src/main/java/com/example/demo/dto/UserRequest.java
Normal file
19
src/main/java/com/example/demo/dto/UserRequest.java
Normal file
@@ -0,0 +1,19 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record UserRequest(
|
||||
@NotBlank(message = "姓名不能为空")
|
||||
String name,
|
||||
|
||||
@NotBlank(message = "邮箱不能为空")
|
||||
@Email(message = "邮箱格式不正确")
|
||||
String email,
|
||||
|
||||
@Min(value = 1, message = "年龄最小为 1")
|
||||
@Max(value = 120, message = "年龄最大为 120")
|
||||
Integer age
|
||||
) {}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.example.demo.dto.auth;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record LoginRequest(
|
||||
@NotBlank(message = "用户名不能为空") String username,
|
||||
@NotBlank(message = "密码不能为空") String password
|
||||
) {}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.example.demo.exception;
|
||||
|
||||
import com.example.demo.common.ApiResponse;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(ResourceNotFoundException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleNotFound(ResourceNotFoundException e) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(ApiResponse.fail(404, e.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ApiResponse<Map<String, String>>> handleValidation(MethodArgumentNotValidException e) {
|
||||
Map<String, String> errors = new HashMap<>();
|
||||
for (FieldError error : e.getBindingResult().getFieldErrors()) {
|
||||
errors.put(error.getField(), error.getDefaultMessage());
|
||||
}
|
||||
return ResponseEntity.badRequest()
|
||||
.body(new ApiResponse<>(400, "参数校验失败", errors, java.time.Instant.now()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleAny(Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(ApiResponse.fail(500, "服务器内部错误: " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.example.demo.exception;
|
||||
|
||||
public class ResourceNotFoundException extends RuntimeException {
|
||||
public ResourceNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.example.demo.security;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class LearningJwtFilter extends OncePerRequestFilter {
|
||||
|
||||
private final LearningJwtUtil jwtUtil;
|
||||
|
||||
public LearningJwtFilter(LearningJwtUtil jwtUtil) {
|
||||
this.jwtUtil = jwtUtil;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return !request.getRequestURI().startsWith("/api/secure/");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String auth = request.getHeader("Authorization");
|
||||
if (!StringUtils.hasText(auth) || !auth.startsWith("Bearer ")) {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("{\"code\":401,\"message\":\"缺少或非法 Authorization\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
String token = auth.substring(7);
|
||||
if (!jwtUtil.validate(token)) {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("{\"code\":401,\"message\":\"Token 无效或过期\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
String username = jwtUtil.username(token);
|
||||
var authToken = new UsernamePasswordAuthenticationToken(
|
||||
username,
|
||||
null,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER"))
|
||||
);
|
||||
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
54
src/main/java/com/example/demo/security/LearningJwtUtil.java
Normal file
54
src/main/java/com/example/demo/security/LearningJwtUtil.java
Normal file
@@ -0,0 +1,54 @@
|
||||
package com.example.demo.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class LearningJwtUtil {
|
||||
|
||||
@Value("${learning.auth.jwt.secret}")
|
||||
private String secret;
|
||||
|
||||
@Value("${learning.auth.jwt.expiration:86400000}")
|
||||
private long expiration;
|
||||
|
||||
private SecretKey key() {
|
||||
return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public String generateToken(String username) {
|
||||
Date now = new Date();
|
||||
return Jwts.builder()
|
||||
.claims(Map.of("username", username))
|
||||
.subject(username)
|
||||
.issuedAt(now)
|
||||
.expiration(new Date(now.getTime() + expiration))
|
||||
.signWith(key(), Jwts.SIG.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public boolean validate(String token) {
|
||||
try {
|
||||
parse(token);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public String username(String token) {
|
||||
return parse(token).getSubject();
|
||||
}
|
||||
|
||||
private Claims parse(String token) {
|
||||
return Jwts.parser().verifyWith(key()).build().parseSignedClaims(token).getPayload();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.example.demo.security;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(name = "learning.auth.enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class LearningSecurityConfig {
|
||||
|
||||
private final LearningJwtFilter learningJwtFilter;
|
||||
|
||||
public LearningSecurityConfig(LearningJwtFilter learningJwtFilter) {
|
||||
this.learningJwtFilter = learningJwtFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain learningSecurityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(
|
||||
"/", "/home", "/learn/**", "/aop/**", "/api/users/**", "/api/health",
|
||||
"/api/auth/**", "/actuator/**", "/index.html", "/users.html", "/aop.html", "/events.html"
|
||||
).permitAll()
|
||||
.requestMatchers("/api/secure/**").authenticated()
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(learningJwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import com.example.demo.exception.ResourceNotFoundException;
|
||||
import com.example.demo.model.User;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -8,23 +9,13 @@ import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 用户服务 - 业务逻辑层
|
||||
*
|
||||
* 学习点:
|
||||
* - @Service: 标记为服务层组件,自动注册为 Bean
|
||||
* - 依赖注入:Controller 通过 @Autowired 注入此服务
|
||||
* - 分层架构:Controller -> Service -> Repository
|
||||
*/
|
||||
@Service
|
||||
public class UserService {
|
||||
|
||||
// 内存存储(演示用,实际项目用数据库)
|
||||
private final List<User> users = new ArrayList<>();
|
||||
private final AtomicLong idGenerator = new AtomicLong(1);
|
||||
|
||||
public UserService() {
|
||||
// 初始化一些测试数据
|
||||
users.add(new User(idGenerator.getAndIncrement(), "张三", "zhangsan@example.com", 25));
|
||||
users.add(new User(idGenerator.getAndIncrement(), "李四", "lisi@example.com", 30));
|
||||
users.add(new User(idGenerator.getAndIncrement(), "王五", "wangwu@example.com", 28));
|
||||
@@ -38,7 +29,7 @@ public class UserService {
|
||||
return users.stream()
|
||||
.filter(u -> u.getId().equals(id))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
.orElseThrow(() -> new ResourceNotFoundException("用户不存在: id=" + id));
|
||||
}
|
||||
|
||||
public List<User> findByName(String name) {
|
||||
@@ -47,23 +38,28 @@ public class UserService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public User save(User user) {
|
||||
if (user.getId() == null) {
|
||||
user.setId(idGenerator.getAndIncrement());
|
||||
users.add(user);
|
||||
} else {
|
||||
// 更新
|
||||
for (int i = 0; i < users.size(); i++) {
|
||||
if (users.get(i).getId().equals(user.getId())) {
|
||||
users.set(i, user);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
public User create(User user) {
|
||||
user.setId(idGenerator.getAndIncrement());
|
||||
users.add(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
public void delete(Long id) {
|
||||
users.removeIf(u -> u.getId().equals(id));
|
||||
public User update(Long id, User user) {
|
||||
findById(id);
|
||||
user.setId(id);
|
||||
for (int i = 0; i < users.size(); i++) {
|
||||
if (users.get(i).getId().equals(id)) {
|
||||
users.set(i, user);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
throw new ResourceNotFoundException("用户不存在: id=" + id);
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(Long id) {
|
||||
boolean removed = users.removeIf(u -> u.getId().equals(id));
|
||||
if (!removed) {
|
||||
throw new ResourceNotFoundException("用户不存在: id=" + id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +1,10 @@
|
||||
server.port=8082
|
||||
spring.application.name=springboot-demo
|
||||
|
||||
# 学习友好:默认只保护 /api/secure/**
|
||||
learning.auth.enabled=true
|
||||
learning.auth.jwt.secret=demo-learning-secret-key-demo-learning-secret-key
|
||||
learning.auth.jwt.expiration=86400000
|
||||
|
||||
# 避免默认生成密码干扰学习输出
|
||||
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
|
||||
|
||||
@@ -28,6 +28,8 @@
|
||||
.nav { margin-bottom: 20px; }
|
||||
.nav a { margin-right: 15px; color: #6DB33F; text-decoration: none; }
|
||||
.nav a:hover { text-decoration: underline; }
|
||||
.lab { background:#fff7e6; border-left:4px solid #fa8c16; padding:15px; border-radius:8px; margin:15px 0; }
|
||||
.lab h4 { color:#ad6800; margin-bottom:8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -38,11 +40,24 @@
|
||||
</div>
|
||||
|
||||
<h1>🔪 AOP 切面编程</h1>
|
||||
|
||||
<div class="lab">
|
||||
<h4>🧪 实验任务卡(AOP)</h4>
|
||||
<label style="display:block;margin-bottom:8px;"><input id="aopTaskDone" type="checkbox" onchange="toggleAopTaskDone(this)"> 本任务我已经完成</label>
|
||||
<ul style="padding-left:20px;line-height:1.8;">
|
||||
<li>目标:观察同一请求如何触发 Before/After/Around 通知</li>
|
||||
<li>步骤1:调用用户接口 <code>/api/users</code></li>
|
||||
<li>步骤2:回到本页点击“刷新统计数据”</li>
|
||||
<li>预期:统计里能看到 Controller/Service 方法耗时累积</li>
|
||||
<li>常见坑:只看页面不看控制台,容易错过切面日志</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3>📊 实时性能统计</h3>
|
||||
<p>AOP 自动统计所有 Controller 和 Service 方法的执行时间</p>
|
||||
<button class="btn btn-primary" onclick="loadStats()">刷新统计数据</button>
|
||||
<button class="btn btn-info" onclick="demoValidationError()">演示校验失败</button>
|
||||
<div class="result-box" id="statsResult">点击按钮查看...</div>
|
||||
</div>
|
||||
|
||||
@@ -167,11 +182,41 @@ execution(* com.example.demo.service.*.save*(..))
|
||||
<p style="margin-top: 30px;"><a href="/">← 返回学习中心</a></p>
|
||||
|
||||
<script>
|
||||
const AOP_TASK_KEY = 'task.aop.done';
|
||||
|
||||
function toggleAopTaskDone(el) {
|
||||
localStorage.setItem(AOP_TASK_KEY, el.checked ? '1' : '0');
|
||||
}
|
||||
|
||||
function initAopTaskState() {
|
||||
const done = localStorage.getItem(AOP_TASK_KEY) === '1';
|
||||
const checkbox = document.getElementById('aopTaskDone');
|
||||
if (checkbox) checkbox.checked = done;
|
||||
}
|
||||
|
||||
async function demoValidationError() {
|
||||
const box = document.getElementById('statsResult');
|
||||
box.textContent = '发送错误示例请求中...';
|
||||
try {
|
||||
const res = await fetch('/api/users', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: '', email: 'bad', age: 999 })
|
||||
});
|
||||
const data = await res.json();
|
||||
box.textContent = JSON.stringify(data, null, 2);
|
||||
} catch (e) {
|
||||
box.textContent = '错误: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
const res = await fetch('/aop/stats');
|
||||
const data = await res.json();
|
||||
document.getElementById('statsResult').textContent = JSON.stringify(data, null, 2);
|
||||
}
|
||||
|
||||
initAopTaskState();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -30,6 +30,8 @@
|
||||
.nav { margin-bottom: 20px; }
|
||||
.nav a { margin-right: 15px; color: #6DB33F; text-decoration: none; }
|
||||
.nav a:hover { text-decoration: underline; }
|
||||
.lab { background:#fff7e6; border-left:4px solid #fa8c16; padding:15px; border-radius:8px; margin:15px 0; }
|
||||
.lab h4 { color:#ad6800; margin-bottom:8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -40,6 +42,18 @@
|
||||
</div>
|
||||
|
||||
<h1>📡 Spring 事件机制</h1>
|
||||
|
||||
<div class="lab">
|
||||
<h4>🧪 实验任务卡(事件)</h4>
|
||||
<label style="display:block;margin-bottom:8px;"><input id="eventTaskDone" type="checkbox" onchange="toggleEventTaskDone(this)"> 本任务我已经完成</label>
|
||||
<ul style="padding-left:20px;line-height:1.8;">
|
||||
<li>目标:体验发布者与监听者解耦</li>
|
||||
<li>步骤1:输入 userId/userName,点击“发布登录事件”</li>
|
||||
<li>步骤2:重复发布不同用户,比较返回结果</li>
|
||||
<li>预期:接口立即返回;监听处理在日志中可观察</li>
|
||||
<li>常见坑:把事件当同步 RPC,忽略异步监听特性</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3>🎉 事件发布演示</h3>
|
||||
@@ -48,6 +62,7 @@
|
||||
<input type="text" id="userName" placeholder="用户名" value="张三" style="padding: 10px; border: 1px solid #ddd; border-radius: 4px; width: 150px;">
|
||||
<input type="number" id="userId" placeholder="用户ID" value="1" style="padding: 10px; border: 1px solid #ddd; border-radius: 4px; width: 100px;">
|
||||
<button class="btn btn-primary" onclick="publishEvent()">发布登录事件</button>
|
||||
<button class="btn btn-warning" onclick="demoEventError()">演示参数错误</button>
|
||||
</div>
|
||||
<div class="result-box" id="eventResult">等待事件发布...</div>
|
||||
</div>
|
||||
@@ -187,6 +202,29 @@ public class AopEventController {
|
||||
<p style="margin-top: 30px;"><a href="/">← 返回学习中心</a></p>
|
||||
|
||||
<script>
|
||||
const EVENT_TASK_KEY = 'task.event.done';
|
||||
|
||||
function toggleEventTaskDone(el) {
|
||||
localStorage.setItem(EVENT_TASK_KEY, el.checked ? '1' : '0');
|
||||
}
|
||||
|
||||
function initEventTaskState() {
|
||||
const done = localStorage.getItem(EVENT_TASK_KEY) === '1';
|
||||
const checkbox = document.getElementById('eventTaskDone');
|
||||
if (checkbox) checkbox.checked = done;
|
||||
}
|
||||
|
||||
async function demoEventError() {
|
||||
const resultBox = document.getElementById('eventResult');
|
||||
try {
|
||||
const res = await fetch('/aop/event/publish?userName=', { method: 'POST' });
|
||||
const data = await res.json();
|
||||
resultBox.textContent = JSON.stringify(data, null, 2);
|
||||
} catch (e) {
|
||||
resultBox.textContent = '错误: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function publishEvent() {
|
||||
const userId = document.getElementById('userId').value;
|
||||
const userName = document.getElementById('userName').value;
|
||||
@@ -208,6 +246,8 @@ public class AopEventController {
|
||||
document.getElementById('eventResult').textContent = '错误: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
initEventTaskState();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -68,6 +68,10 @@
|
||||
<h4>📡 事件机制</h4>
|
||||
<p>发布/订阅模式、解耦业务逻辑</p>
|
||||
</a>
|
||||
<a href="/learn" class="feature-item">
|
||||
<h4>🔐 鉴权演示(学习用)</h4>
|
||||
<p>最小 JWT 流程:登录、携带 Token、访问受保护接口</p>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -143,7 +143,8 @@ public class UserController {
|
||||
// 加载用户列表
|
||||
async function loadUsers() {
|
||||
const res = await fetch('/api/users');
|
||||
const users = await res.json();
|
||||
const payload = await res.json();
|
||||
const users = payload.data || [];
|
||||
const tbody = document.querySelector('#userTable tbody');
|
||||
tbody.innerHTML = users.map(u => `
|
||||
<tr>
|
||||
@@ -196,7 +197,7 @@ public class UserController {
|
||||
await fetch(`/api/users/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...user, id: parseInt(id) })
|
||||
body: JSON.stringify(user)
|
||||
});
|
||||
} else {
|
||||
await fetch('/api/users', {
|
||||
|
||||
54
src/test/java/com/example/demo/controller/AuthFlowTest.java
Normal file
54
src/test/java/com/example/demo/controller/AuthFlowTest.java
Normal file
@@ -0,0 +1,54 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class AuthFlowTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Test
|
||||
void secureEndpointShouldRejectWithoutToken() throws Exception {
|
||||
mockMvc.perform(get("/api/secure/me"))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.code").value(401));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAccessSecureEndpointWithValidToken() throws Exception {
|
||||
String loginReq = objectMapper.writeValueAsString(Map.of("username", "admin", "password", "admin123"));
|
||||
|
||||
String loginResp = mockMvc.perform(post("/api/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(loginReq))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
|
||||
String token = objectMapper.readTree(loginResp).path("data").path("token").asText();
|
||||
|
||||
mockMvc.perform(get("/api/secure/me")
|
||||
.header("Authorization", "Bearer " + token))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.data.principal").value("admin"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class UserControllerTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
void shouldListUsersWithApiResponseWrapper() throws Exception {
|
||||
mockMvc.perform(get("/api/users"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.data").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCreateUser() throws Exception {
|
||||
String json = """
|
||||
{
|
||||
\"name\": \"测试用户\",
|
||||
\"email\": \"test@example.com\",
|
||||
\"age\": 22
|
||||
}
|
||||
""";
|
||||
|
||||
mockMvc.perform(post("/api/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.data.name").value("测试用户"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectInvalidUser() throws Exception {
|
||||
String json = """
|
||||
{
|
||||
\"name\": \"\",
|
||||
\"email\": \"bad-mail\",
|
||||
\"age\": 222
|
||||
}
|
||||
""";
|
||||
|
||||
mockMvc.perform(post("/api/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.code").value(400));
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,10 @@
|
||||
server.port=8082
|
||||
spring.application.name=springboot-demo
|
||||
|
||||
# 学习友好:默认只保护 /api/secure/**
|
||||
learning.auth.enabled=true
|
||||
learning.auth.jwt.secret=demo-learning-secret-key-demo-learning-secret-key
|
||||
learning.auth.jwt.expiration=86400000
|
||||
|
||||
# 避免默认生成密码干扰学习输出
|
||||
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
|
||||
|
||||
BIN
target/classes/com/example/demo/common/ApiResponse.class
Normal file
BIN
target/classes/com/example/demo/common/ApiResponse.class
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
target/classes/com/example/demo/dto/UserRequest.class
Normal file
BIN
target/classes/com/example/demo/dto/UserRequest.class
Normal file
Binary file not shown.
BIN
target/classes/com/example/demo/dto/auth/LoginRequest.class
Normal file
BIN
target/classes/com/example/demo/dto/auth/LoginRequest.class
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
target/classes/com/example/demo/security/LearningJwtFilter.class
Normal file
BIN
target/classes/com/example/demo/security/LearningJwtFilter.class
Normal file
Binary file not shown.
BIN
target/classes/com/example/demo/security/LearningJwtUtil.class
Normal file
BIN
target/classes/com/example/demo/security/LearningJwtUtil.class
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -28,6 +28,8 @@
|
||||
.nav { margin-bottom: 20px; }
|
||||
.nav a { margin-right: 15px; color: #6DB33F; text-decoration: none; }
|
||||
.nav a:hover { text-decoration: underline; }
|
||||
.lab { background:#fff7e6; border-left:4px solid #fa8c16; padding:15px; border-radius:8px; margin:15px 0; }
|
||||
.lab h4 { color:#ad6800; margin-bottom:8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -38,11 +40,24 @@
|
||||
</div>
|
||||
|
||||
<h1>🔪 AOP 切面编程</h1>
|
||||
|
||||
<div class="lab">
|
||||
<h4>🧪 实验任务卡(AOP)</h4>
|
||||
<label style="display:block;margin-bottom:8px;"><input id="aopTaskDone" type="checkbox" onchange="toggleAopTaskDone(this)"> 本任务我已经完成</label>
|
||||
<ul style="padding-left:20px;line-height:1.8;">
|
||||
<li>目标:观察同一请求如何触发 Before/After/Around 通知</li>
|
||||
<li>步骤1:调用用户接口 <code>/api/users</code></li>
|
||||
<li>步骤2:回到本页点击“刷新统计数据”</li>
|
||||
<li>预期:统计里能看到 Controller/Service 方法耗时累积</li>
|
||||
<li>常见坑:只看页面不看控制台,容易错过切面日志</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3>📊 实时性能统计</h3>
|
||||
<p>AOP 自动统计所有 Controller 和 Service 方法的执行时间</p>
|
||||
<button class="btn btn-primary" onclick="loadStats()">刷新统计数据</button>
|
||||
<button class="btn btn-info" onclick="demoValidationError()">演示校验失败</button>
|
||||
<div class="result-box" id="statsResult">点击按钮查看...</div>
|
||||
</div>
|
||||
|
||||
@@ -167,11 +182,41 @@ execution(* com.example.demo.service.*.save*(..))
|
||||
<p style="margin-top: 30px;"><a href="/">← 返回学习中心</a></p>
|
||||
|
||||
<script>
|
||||
const AOP_TASK_KEY = 'task.aop.done';
|
||||
|
||||
function toggleAopTaskDone(el) {
|
||||
localStorage.setItem(AOP_TASK_KEY, el.checked ? '1' : '0');
|
||||
}
|
||||
|
||||
function initAopTaskState() {
|
||||
const done = localStorage.getItem(AOP_TASK_KEY) === '1';
|
||||
const checkbox = document.getElementById('aopTaskDone');
|
||||
if (checkbox) checkbox.checked = done;
|
||||
}
|
||||
|
||||
async function demoValidationError() {
|
||||
const box = document.getElementById('statsResult');
|
||||
box.textContent = '发送错误示例请求中...';
|
||||
try {
|
||||
const res = await fetch('/api/users', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: '', email: 'bad', age: 999 })
|
||||
});
|
||||
const data = await res.json();
|
||||
box.textContent = JSON.stringify(data, null, 2);
|
||||
} catch (e) {
|
||||
box.textContent = '错误: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
const res = await fetch('/aop/stats');
|
||||
const data = await res.json();
|
||||
document.getElementById('statsResult').textContent = JSON.stringify(data, null, 2);
|
||||
}
|
||||
|
||||
initAopTaskState();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -30,6 +30,8 @@
|
||||
.nav { margin-bottom: 20px; }
|
||||
.nav a { margin-right: 15px; color: #6DB33F; text-decoration: none; }
|
||||
.nav a:hover { text-decoration: underline; }
|
||||
.lab { background:#fff7e6; border-left:4px solid #fa8c16; padding:15px; border-radius:8px; margin:15px 0; }
|
||||
.lab h4 { color:#ad6800; margin-bottom:8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -40,6 +42,18 @@
|
||||
</div>
|
||||
|
||||
<h1>📡 Spring 事件机制</h1>
|
||||
|
||||
<div class="lab">
|
||||
<h4>🧪 实验任务卡(事件)</h4>
|
||||
<label style="display:block;margin-bottom:8px;"><input id="eventTaskDone" type="checkbox" onchange="toggleEventTaskDone(this)"> 本任务我已经完成</label>
|
||||
<ul style="padding-left:20px;line-height:1.8;">
|
||||
<li>目标:体验发布者与监听者解耦</li>
|
||||
<li>步骤1:输入 userId/userName,点击“发布登录事件”</li>
|
||||
<li>步骤2:重复发布不同用户,比较返回结果</li>
|
||||
<li>预期:接口立即返回;监听处理在日志中可观察</li>
|
||||
<li>常见坑:把事件当同步 RPC,忽略异步监听特性</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3>🎉 事件发布演示</h3>
|
||||
@@ -48,6 +62,7 @@
|
||||
<input type="text" id="userName" placeholder="用户名" value="张三" style="padding: 10px; border: 1px solid #ddd; border-radius: 4px; width: 150px;">
|
||||
<input type="number" id="userId" placeholder="用户ID" value="1" style="padding: 10px; border: 1px solid #ddd; border-radius: 4px; width: 100px;">
|
||||
<button class="btn btn-primary" onclick="publishEvent()">发布登录事件</button>
|
||||
<button class="btn btn-warning" onclick="demoEventError()">演示参数错误</button>
|
||||
</div>
|
||||
<div class="result-box" id="eventResult">等待事件发布...</div>
|
||||
</div>
|
||||
@@ -187,6 +202,29 @@ public class AopEventController {
|
||||
<p style="margin-top: 30px;"><a href="/">← 返回学习中心</a></p>
|
||||
|
||||
<script>
|
||||
const EVENT_TASK_KEY = 'task.event.done';
|
||||
|
||||
function toggleEventTaskDone(el) {
|
||||
localStorage.setItem(EVENT_TASK_KEY, el.checked ? '1' : '0');
|
||||
}
|
||||
|
||||
function initEventTaskState() {
|
||||
const done = localStorage.getItem(EVENT_TASK_KEY) === '1';
|
||||
const checkbox = document.getElementById('eventTaskDone');
|
||||
if (checkbox) checkbox.checked = done;
|
||||
}
|
||||
|
||||
async function demoEventError() {
|
||||
const resultBox = document.getElementById('eventResult');
|
||||
try {
|
||||
const res = await fetch('/aop/event/publish?userName=', { method: 'POST' });
|
||||
const data = await res.json();
|
||||
resultBox.textContent = JSON.stringify(data, null, 2);
|
||||
} catch (e) {
|
||||
resultBox.textContent = '错误: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function publishEvent() {
|
||||
const userId = document.getElementById('userId').value;
|
||||
const userName = document.getElementById('userName').value;
|
||||
@@ -208,6 +246,8 @@ public class AopEventController {
|
||||
document.getElementById('eventResult').textContent = '错误: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
initEventTaskState();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -68,6 +68,10 @@
|
||||
<h4>📡 事件机制</h4>
|
||||
<p>发布/订阅模式、解耦业务逻辑</p>
|
||||
</a>
|
||||
<a href="/learn" class="feature-item">
|
||||
<h4>🔐 鉴权演示(学习用)</h4>
|
||||
<p>最小 JWT 流程:登录、携带 Token、访问受保护接口</p>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -143,7 +143,8 @@ public class UserController {
|
||||
// 加载用户列表
|
||||
async function loadUsers() {
|
||||
const res = await fetch('/api/users');
|
||||
const users = await res.json();
|
||||
const payload = await res.json();
|
||||
const users = payload.data || [];
|
||||
const tbody = document.querySelector('#userTable tbody');
|
||||
tbody.innerHTML = users.map(u => `
|
||||
<tr>
|
||||
@@ -196,7 +197,7 @@ public class UserController {
|
||||
await fetch(`/api/users/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...user, id: parseInt(id) })
|
||||
body: JSON.stringify(user)
|
||||
});
|
||||
} else {
|
||||
await fetch('/api/users', {
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,3 +0,0 @@
|
||||
artifactId=demo
|
||||
groupId=com.example
|
||||
version=0.0.1-SNAPSHOT
|
||||
@@ -1,15 +1,25 @@
|
||||
com/example/demo/controller/auth/SecureDemoController.class
|
||||
com/example/demo/exception/ResourceNotFoundException.class
|
||||
com/example/demo/event/UserEventPublisher.class
|
||||
com/example/demo/exception/GlobalExceptionHandler.class
|
||||
com/example/demo/dto/auth/LoginRequest.class
|
||||
com/example/demo/DemoApplication.class
|
||||
com/example/demo/controller/PageController.class
|
||||
com/example/demo/dto/UserRequest.class
|
||||
com/example/demo/security/LearningJwtUtil.class
|
||||
com/example/demo/security/LearningSecurityConfig.class
|
||||
com/example/demo/model/UserEvent$Type.class
|
||||
com/example/demo/model/User.class
|
||||
com/example/demo/service/UserService.class
|
||||
com/example/demo/aop/PerformanceAspect.class
|
||||
com/example/demo/aop/RateLimited.class
|
||||
com/example/demo/model/UserEvent.class
|
||||
com/example/demo/aop/LoggingAspect.class
|
||||
com/example/demo/event/UserEventPublisher.class
|
||||
com/example/demo/controller/auth/LearningAuthController.class
|
||||
com/example/demo/common/ApiResponse.class
|
||||
com/example/demo/controller/AopEventController.class
|
||||
com/example/demo/controller/LearnController.class
|
||||
com/example/demo/DemoApplication.class
|
||||
com/example/demo/event/UserEventListener.class
|
||||
com/example/demo/controller/PageController.class
|
||||
com/example/demo/controller/UserController.class
|
||||
com/example/demo/model/UserEvent$Type.class
|
||||
com/example/demo/model/User.class
|
||||
com/example/demo/aop/RateLimitAspect.class
|
||||
com/example/demo/service/UserService.class
|
||||
com/example/demo/aop/PerformanceAspect.class
|
||||
com/example/demo/security/LearningJwtFilter.class
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/security/LearningSecurityConfig.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/controller/auth/SecureDemoController.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/controller/UserController.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/model/User.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/aop/LoggingAspect.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/security/LearningJwtUtil.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/controller/PageController.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/aop/RateLimited.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/aop/PerformanceAspect.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/service/UserService.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/exception/ResourceNotFoundException.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/controller/AopEventController.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/exception/GlobalExceptionHandler.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/event/UserEventPublisher.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/dto/auth/LoginRequest.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/dto/UserRequest.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/common/ApiResponse.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/security/LearningJwtFilter.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/DemoApplication.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/event/UserEventListener.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/controller/LearnController.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/controller/auth/LearningAuthController.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/model/UserEvent.java
|
||||
/home/llm/projects/springboot-demo/src/main/java/com/example/demo/aop/RateLimitAspect.java
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
com/example/demo/controller/UserControllerTest.class
|
||||
com/example/demo/controller/AuthFlowTest.class
|
||||
@@ -0,0 +1,2 @@
|
||||
/home/llm/projects/springboot-demo/src/test/java/com/example/demo/controller/AuthFlowTest.java
|
||||
/home/llm/projects/springboot-demo/src/test/java/com/example/demo/controller/UserControllerTest.java
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,4 @@
|
||||
-------------------------------------------------------------------------------
|
||||
Test set: com.example.demo.controller.AuthFlowTest
|
||||
-------------------------------------------------------------------------------
|
||||
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.666 s -- in com.example.demo.controller.AuthFlowTest
|
||||
@@ -0,0 +1,4 @@
|
||||
-------------------------------------------------------------------------------
|
||||
Test set: com.example.demo.controller.UserControllerTest
|
||||
-------------------------------------------------------------------------------
|
||||
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 24.99 s -- in com.example.demo.controller.UserControllerTest
|
||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user