Compare commits

...

7 Commits

Author SHA1 Message Date
Codex
09574c3400 feat: add guided learning cockpit 2026-03-19 13:53:49 +08:00
Codex
00306082fb feat: upgrade user management demo 2026-03-18 16:43:04 +08:00
likingcode
e8afe9a5f4 Update: build artifacts and classes 2026-03-18 15:18:30 +08:00
likingcode
efcfe7e012 feat(learning-auth): add optional JWT learning flow with secure demo endpoint 2026-03-09 02:11:49 +08:00
likingcode
8f93488989 feat(v3): add task progress state and error demos for demo pages 2026-03-09 02:04:16 +08:00
likingcode
2d4598cc69 feat(v2): add task cards for AOP and event learning pages 2026-03-09 01:55:19 +08:00
likingcode
6a4c6a369a feat(v1): unify API response, validation, exception handling and tests 2026-03-08 14:40:30 +00:00
60 changed files with 2501 additions and 1129 deletions

29
pom.xml
View File

@@ -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>

View File

@@ -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

View File

@@ -9,61 +9,35 @@ import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 性能监控切面 - 演示 @Around 环绕通知
*
* 学习点:
* - @Around 最强大的通知类型
* - ProceedingJoinPoint 控制方法执行
* - 方法执行时间统计
*/
@Aspect
@Component
public class PerformanceAspect {
// 方法执行时间统计
private final Map<String, Long> totalTimes = new ConcurrentHashMap<>();
private final Map<String, Long> callCounts = new ConcurrentHashMap<>();
/**
* 环绕通知 - 统计方法执行时间
*/
@Around("execution(* com.example.demo.controller.*.*(..)) || " +
"execution(* com.example.demo.service.*.*(..))")
"execution(* com.example.demo.service.*.*(..))")
public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().toShortString();
long startTime = System.currentTimeMillis();
try {
// 执行目标方法
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
// 记录统计
long duration = System.currentTimeMillis() - startTime;
totalTimes.merge(methodName, duration, Long::sum);
callCounts.merge(methodName, 1L, Long::sum);
System.out.println("[AOP-Performance] " + methodName +
" 执行耗时: " + duration + "ms");
System.out.println("[AOP-Performance] " + methodName + " completed in " + duration + "ms");
return result;
} catch (Throwable e) {
long endTime = System.currentTimeMillis();
System.out.println("[AOP-Performance] " + methodName +
" 异常耗时: " + (endTime - startTime) + "ms");
throw e;
} catch (Throwable error) {
long duration = System.currentTimeMillis() - startTime;
System.out.println("[AOP-Performance] " + methodName + " failed after " + duration + "ms");
throw error;
}
}
/**
* 获取性能统计
*/
public Map<String, Map<String, Long>> getStatistics() {
Map<String, Map<String, Long>> stats = new HashMap<>();
for (String method : totalTimes.keySet()) {
Map<String, Long> methodStats = new HashMap<>();
methodStats.put("totalTime", totalTimes.get(method));
@@ -71,7 +45,6 @@ public class PerformanceAspect {
methodStats.put("avgTime", totalTimes.get(method) / callCounts.get(method));
stats.put(method, methodStats);
}
return stats;
}
}
}

View 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());
}
}

View File

@@ -3,175 +3,178 @@ package com.example.demo.controller;
import com.example.demo.aop.PerformanceAspect;
import com.example.demo.aop.RateLimitAspect;
import com.example.demo.aop.RateLimited;
import com.example.demo.event.UserEventListener;
import com.example.demo.event.UserEventPublisher;
import com.example.demo.model.User;
import com.example.demo.model.UserEvent;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* AOP 和事件机制学习控制器
*/
@RestController
@RequestMapping("/aop")
public class AopEventController {
@Autowired
private UserService userService;
private final UserService userService;
private final UserEventPublisher eventPublisher;
private final UserEventListener userEventListener;
private final PerformanceAspect performanceAspect;
private final RateLimitAspect rateLimitAspect;
@Autowired
private UserEventPublisher eventPublisher;
public AopEventController(UserService userService,
UserEventPublisher eventPublisher,
UserEventListener userEventListener,
PerformanceAspect performanceAspect,
RateLimitAspect rateLimitAspect) {
this.userService = userService;
this.eventPublisher = eventPublisher;
this.userEventListener = userEventListener;
this.performanceAspect = performanceAspect;
this.rateLimitAspect = rateLimitAspect;
}
@Autowired
private PerformanceAspect performanceAspect;
@Autowired
private RateLimitAspect rateLimitAspect;
/**
* 学习首页
*/
@GetMapping
public Map<String, Object> index() {
Map<String, Object> info = new HashMap<>();
info.put("message", "Spring Boot 学习中心");
info.put("message", "Explore cross-cutting behavior through AOP, events, and rate limiting.");
info.put("topics", new String[]{
"AOP 切面编程",
"事件机制",
"Bean 生命周期"
"AOP advice and performance tracing",
"Application events and listener decoupling",
"Annotation-driven rate limiting"
});
info.put("endpoints", new String[]{
"GET /aop - AOP 概念说明",
"GET /aop/stats - 性能统计",
"GET /aop/event - 事件机制说明",
"POST /aop/event/publish - 发布用户事件",
"GET /aop/event/history - 查看事件历史",
"GET /aop/ratelimit - 限流测试"
"GET /aop/aop",
"GET /aop/aop/stats",
"GET /aop/event",
"POST /aop/event/publish",
"GET /aop/event/history",
"GET /aop/ratelimit"
});
info.put("userCount", userService.findAll().size());
return info;
}
// ==================== AOP 示例 ====================
/**
* AOP 概念说明
*/
@GetMapping("/aop")
public Map<String, Object> aopInfo() {
Map<String, Object> info = new HashMap<>();
info.put("title", "AOP 切面编程");
info.put("title", "AOP learning notes");
info.put("concepts", new String[]{
"Aspect(切面): 横切关注点的模块化",
"JoinPoint(连接点): 程序执行的某个点",
"Pointcut(切入点): 匹配连接点的表达式",
"Advice(通知): 在连接点执行的动作",
"Weaving(织入): 将切面应用到目标对象"
"Aspect: a reusable cross-cutting module",
"Join point: a place where the program can be intercepted",
"Pointcut: the matcher that selects join points",
"Advice: code that runs before, after, or around the join point",
"Weaving: combining the aspect with the target object"
});
info.put("adviceTypes", new String[]{
"@Before - 方法执行前",
"@After - 方法执行后(无论成功或异常)",
"@AfterReturning - 方法成功返回后",
"@AfterThrowing - 方法抛出异常后",
"@Around - 环绕通知(最强大)"
"@Before for pre-checks",
"@After for cleanup",
"@AfterReturning for successful results",
"@AfterThrowing for failures",
"@Around for timing, wrapping, and total control"
});
info.put("useCases", new String[]{
"日志记录",
"性能监控",
"事务管理",
"权限检查",
"限流控制"
"Logging",
"Performance measurement",
"Authorization checks",
"Rate limiting",
"Reusable validation"
});
return info;
}
/**
* 查看性能统计
*/
@GetMapping("/aop/stats")
public Map<String, Object> getPerformanceStats() {
Map<String, Object> result = new HashMap<>();
result.put("title", "方法性能统计");
result.put("description", "由 PerformanceAspect 自动收集");
result.put("title", "Collected performance metrics");
result.put("description", "These numbers come from the around advice on controllers and services.");
result.put("statistics", performanceAspect.getStatistics());
return result;
}
// ==================== 事件机制示例 ====================
/**
* 事件机制说明
*/
@GetMapping("/event")
public Map<String, Object> eventInfo() {
Map<String, Object> info = new HashMap<>();
info.put("title", "Spring 事件机制");
info.put("title", "Spring application events");
info.put("concepts", new String[]{
"ApplicationEventPublisher - 事件发布者",
"@EventListener - 事件监听器",
"@Async - 异步处理事件",
"condition - 条件过滤"
"ApplicationEventPublisher emits a domain or lifecycle event.",
"@EventListener reacts without tight coupling to the caller.",
"@Async lets slow follow-up work happen outside the request path.",
"Conditions help one listener focus on one event type."
});
info.put("benefits", new String[]{
"解耦:发布者和监听者互不依赖",
"扩展:新增监听器无需修改发布者",
"异步:耗时操作不阻塞主流程",
"测试:更容易进行单元测试"
});
info.put("eventTypes", new String[]{
"CREATED - 用户创建",
"UPDATED - 用户更新",
"DELETED - 用户删除",
"LOGIN - 用户登录"
"Controllers stay smaller.",
"Listeners can grow independently.",
"The request flow stays responsive.",
"Side effects become easier to test."
});
info.put("eventTypes", UserEvent.Type.values());
return info;
}
/**
* 发布用户事件
*/
@PostMapping("/event/publish")
public Map<String, Object> publishEvent(
@RequestParam Long userId,
@RequestParam String userName,
@RequestParam(defaultValue = "LOGIN") String eventType
@RequestParam Long userId,
@RequestParam String userName,
@RequestParam(defaultValue = "LOGIN") String eventType
) {
eventPublisher.publishUserLogin(userId, userName);
UserEvent.Type type = resolveType(eventType);
String detail = switch (type) {
case CREATED -> "User was created through the demo flow";
case UPDATED -> "User profile was updated through the demo flow";
case DELETED -> "User was removed through the demo flow";
case LOGIN -> "User signed in through the demo flow";
};
eventPublisher.publishUserEvent(userId, userName, type, detail);
Map<String, Object> result = new HashMap<>();
result.put("message", "事件已发布");
result.put("eventType", eventType);
result.put("message", "Event published successfully.");
result.put("eventType", type.name());
result.put("userId", userId);
result.put("userName", userName);
result.put("historySize", userEventListener.getEventHistory().size());
return result;
}
/**
* 查看事件历史
*/
@GetMapping("/event/history")
public Map<String, Object> getEventHistory() {
List<Map<String, Object>> items = userEventListener.getEventHistory().stream()
.map(event -> Map.<String, Object>of(
"type", event.getType().name(),
"userId", event.getUserId(),
"userName", event.getUserName(),
"detail", event.getDetail(),
"timestamp", event.getTimestamp().toString()
))
.toList();
Map<String, Object> result = new HashMap<>();
result.put("title", "事件历史记录");
result.put("note", "由 UserEventListener 自动记录");
result.put("title", "Recent user event history");
result.put("total", items.size());
result.put("items", items);
return result;
}
// ==================== 限流示例 ====================
/**
* 限流测试接口
*/
@GetMapping("/ratelimit")
@RateLimited(value = 10, message = "测试限流每分钟最多10次")
@RateLimited(value = 10, message = "Demo limit reached: only 10 requests per minute are allowed.")
public Map<String, Object> testRateLimit() {
Map<String, Object> result = new HashMap<>();
result.put("message", "请求成功");
result.put("note", "使用 @RateLimited 注解");
result.put("message", "Rate-limited endpoint executed successfully.");
result.put("note", "The @RateLimited annotation wraps this method through an aspect.");
result.put("rateLimitStatus", rateLimitAspect.getRateLimitStatus());
return result;
}
}
private UserEvent.Type resolveType(String rawType) {
try {
return UserEvent.Type.valueOf(rawType.trim().toUpperCase());
} catch (Exception ignored) {
return UserEvent.Type.LOGIN;
}
}
}

View File

@@ -1,116 +1,120 @@
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* 学习示例控制器
*
* 学习点:
* - 各种参数接收方式
* - 配置注入
* - 响应格式
*/
@RestController
public class LearnController {
// 从配置文件注入值
@Value("${spring.application.name:demo}")
private String appName;
/**
* 根路径 - 重定向到学习中心
*/
@GetMapping("/")
@GetMapping("/learn/root")
public Map<String, Object> root() {
Map<String, Object> info = new HashMap<>();
info.put("message", "欢迎来到 Spring Boot 学习脚手架!");
info.put("learn", "https://spring.xiaoxiaoluohao.indevs.in/learn");
info.put("aop", "https://spring.xiaoxiaoluohao.indevs.in/aop");
info.put("api", "https://spring.xiaoxiaoluohao.indevs.in/api/users");
info.put("message", "Welcome to the Spring Boot learning workspace.");
info.put("homePage", "/");
info.put("userLab", "/users.html");
info.put("aopLab", "/aop.html");
info.put("eventLab", "/events.html");
info.put("learnApi", "/learn");
return info;
}
// GET /learn - API 信息
@GetMapping("/learn")
public Map<String, Object> info() {
Map<String, Object> info = new HashMap<>();
info.put("app", appName);
info.put("message", "欢迎学习 Spring Boot");
info.put("message", "Use this endpoint family to compare common Spring MVC input patterns.");
info.put("learningGoals", new String[]{
"Understand how query parameters, path variables, headers, cookies, and JSON bodies are mapped.",
"Compare normal responses with handled exceptions.",
"Connect the browser, controller method signature, and serialized JSON output."
});
info.put("endpoints", new String[]{
"GET /learn/params?name=xxx&age=18 - 参数示例",
"POST /learn/body - JSON 请求体示例",
"GET /learn/path/{id} - 路径变量示例",
"GET /learn/header - 请求头示例",
"GET /learn/cookie - Cookie 示例"
"GET /learn/params?name=alex&age=18",
"POST /learn/body",
"GET /learn/path/{id}",
"GET /learn/header",
"GET /learn/cookie",
"GET /learn/exception",
"POST /api/auth/login",
"GET /api/secure/me"
});
return info;
}
// GET /learn/params?name=xxx&age=18 - 查询参数
@GetMapping("/learn/params")
public Map<String, Object> params(
@RequestParam(required = false, defaultValue = "游客") String name,
@RequestParam(required = false, defaultValue = "0") Integer age
@RequestParam(required = false, defaultValue = "guest") String name,
@RequestParam(required = false, defaultValue = "0") Integer age
) {
Map<String, Object> result = new HashMap<>();
result.put("pattern", "@RequestParam");
result.put("name", name);
result.put("age", age);
result.put("tip", "使用 @RequestParam 接收查询参数");
result.put("tip", "Query parameters are useful for filters, pagination, and optional toggles.");
return result;
}
// POST /learn/body - 请求体
@PostMapping("/learn/body")
public Map<String, Object> body(@RequestBody Map<String, Object> data) {
Map<String, Object> result = new HashMap<>();
result.put("pattern", "@RequestBody");
result.put("received", data);
result.put("tip", "使用 @RequestBody 接收 JSON 请求体");
result.put("tip", "JSON request bodies fit create and update flows where the payload has structure.");
return result;
}
// GET /learn/path/{id} - 路径变量
@GetMapping("/learn/path/{id}")
public Map<String, Object> path(@PathVariable String id) {
Map<String, Object> result = new HashMap<>();
result.put("pattern", "@PathVariable");
result.put("id", id);
result.put("tip", "使用 @PathVariable 接收路径变量");
result.put("tip", "Path variables usually identify a concrete resource such as a user, order, or lesson.");
return result;
}
// GET /learn/header - 请求头
@GetMapping("/learn/header")
public Map<String, Object> header(@RequestHeader(value = "User-Agent", required = false) String userAgent) {
Map<String, Object> result = new HashMap<>();
result.put("pattern", "@RequestHeader");
result.put("userAgent", userAgent);
result.put("tip", "使用 @RequestHeader 获取请求头");
result.put("tip", "Headers often carry auth context, tracing ids, and client metadata.");
return result;
}
// GET /learn/cookie - Cookie
@GetMapping("/learn/cookie")
public Map<String, Object> cookie(@CookieValue(value = "JSESSIONID", required = false) String sessionId) {
Map<String, Object> result = new HashMap<>();
result.put("pattern", "@CookieValue");
result.put("sessionId", sessionId);
result.put("tip", "使用 @CookieValue 获取 Cookie");
result.put("tip", "Cookies help explain browser session state and why a request may look authenticated.");
return result;
}
// GET /learn/exception - 异常处理
@GetMapping("/learn/exception")
public String exception() {
throw new RuntimeException("这是一个测试异常");
throw new RuntimeException("Intentional demo exception from /learn/exception");
}
// 全局异常处理
@ExceptionHandler(RuntimeException.class)
public Map<String, Object> handleException(RuntimeException e) {
Map<String, Object> result = new HashMap<>();
result.put("pattern", "@ExceptionHandler");
result.put("error", e.getMessage());
result.put("tip", "使用 @ExceptionHandler 处理异常");
result.put("tip", "Spring can convert thrown exceptions into structured API responses without leaking stack traces.");
return result;
}
}
}

View File

@@ -1,64 +1,62 @@
package com.example.demo.controller;
import com.example.demo.common.ApiResponse;
import com.example.demo.dto.UserRequest;
import com.example.demo.dto.UserStatsResponse;
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);
@GetMapping("/stats")
public ApiResponse<UserStatsResponse> getUserStats() {
return ApiResponse.ok(userService.getStats());
}
// POST /api/users - 创建用户
@PostMapping
public User createUser(@RequestBody User user) {
return userService.save(user);
}
// PUT /api/users/{id} - 更新用户
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userService.save(user);
}
// DELETE /api/users/{id} - 删除用户
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
userService.delete(id);
return "用户 " + id + " 已删除";
}
// 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(required = false) String keyword,
@RequestParam(required = false) String name) {
String term = keyword != null && !keyword.isBlank() ? keyword : name;
return ApiResponse.ok(userService.search(term));
}
}
@GetMapping("/{id}")
public ApiResponse<User> getUserById(@PathVariable Long id) {
return ApiResponse.ok(userService.findById(id));
}
@PostMapping
public ApiResponse<User> createUser(@Valid @RequestBody UserRequest request) {
User user = new User(null, request.name(), request.email(), request.age());
return ApiResponse.ok("User created successfully", userService.create(user));
}
@PutMapping("/{id}")
public ApiResponse<User> updateUser(@PathVariable Long id, @Valid @RequestBody UserRequest request) {
User user = new User(id, request.name(), request.email(), request.age());
return ApiResponse.ok("User updated successfully", userService.update(id, user));
}
@DeleteMapping("/{id}")
public ApiResponse<Void> deleteUser(@PathVariable Long id) {
userService.delete(id);
return ApiResponse.ok("User deleted successfully", null);
}
}

View File

@@ -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"
));
}
}

View File

@@ -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 鉴权"
));
}
}

View File

@@ -0,0 +1,24 @@
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;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public record UserRequest(
@NotBlank(message = "Name is required")
@Size(max = 40, message = "Name must be at most 40 characters")
String name,
@NotBlank(message = "Email is required")
@Email(message = "Email format is invalid")
String email,
@NotNull(message = "Age is required")
@Min(value = 1, message = "Age must be at least 1")
@Max(value = 120, message = "Age must be at most 120")
Integer age
) {
}

View File

@@ -0,0 +1,9 @@
package com.example.demo.dto;
public record UserStatsResponse(
long totalUsers,
long adults,
long underThirty,
double averageAge
) {
}

View File

@@ -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
) {}

View File

@@ -1,80 +1,50 @@
package com.example.demo.event;
import com.example.demo.model.UserEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* 事件监听器 - 演示如何监听事件
*
* 学习点:
* - @EventListener 注解
* - @Async 异步处理
* - 多监听器协作
* - 事件驱动架构的优势
*/
@Component
public class UserEventListener {
// 存储事件历史(演示用)
private final List<UserEvent> eventHistory = new CopyOnWriteArrayList<>();
/**
* 监听用户事件 - 日志记录
*/
@EventListener
public void handleUserEvent(UserEvent event) {
System.out.println("[EventListener] 收到事件: " + event.getType() +
" - 用户: " + event.getUserName() +
" - 时间: " + event.getTimestamp());
// 记录到历史
System.out.println("[EventListener] Received " + event.getType() + " for " + event.getUserName()
+ " at " + event.getTimestamp());
eventHistory.add(event);
}
/**
* 监听用户创建事件 - 发送欢迎邮件(模拟)
*/
@EventListener(condition = "#event.type == T(com.example.demo.model.UserEvent$Type).CREATED")
@Async
public void handleUserCreated(UserEvent event) {
System.out.println("[EmailService] 发送欢迎邮件给: " + event.getUserName());
// 模拟邮件发送耗时
System.out.println("[EmailService] Simulate welcome email for " + event.getUserName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
}
System.out.println("[EmailService] 欢迎邮件发送完成");
System.out.println("[EmailService] Welcome email finished for " + event.getUserName());
}
/**
* 监听用户登录事件 - 更新登录统计
*/
@EventListener(condition = "#event.type == T(com.example.demo.model.UserEvent$Type).LOGIN")
public void handleUserLogin(UserEvent event) {
System.out.println("[LoginTracker] 记录用户登录: " + event.getUserName());
System.out.println("[LoginTracker] Track login for " + event.getUserName());
}
/**
* 监听应用启动完成事件
*/
@EventListener
public void onApplicationReady(ApplicationReadyEvent event) {
System.out.println("[EventListener] Spring Boot 应用启动完成!");
System.out.println("[EventListener] Spring Boot learning demo is ready.");
}
/**
* 获取事件历史
*/
public List<UserEvent> getEventHistory() {
return new ArrayList<>(eventHistory);
}
}
}

View File

@@ -1,55 +1,30 @@
package com.example.demo.event;
import com.example.demo.model.UserEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 事件发布器 - 演示如何发布事件
*
* 学习点:
* - ApplicationEventPublisher 接口
* - 依赖注入发布器
* - 解耦:发布者不需要知道监听者
*/
@Component
public class UserEventPublisher {
@Autowired
private ApplicationEventPublisher eventPublisher;
/**
* 发布用户事件
*/
public void publishEvent(UserEvent event) {
System.out.println("[EventPublisher] 发布事件: " + event.getType() + " - " + event.getUserName());
System.out.println("[EventPublisher] Publish event " + event.getType() + " for " + event.getUserName());
eventPublisher.publishEvent(event);
}
/**
* 便捷方法:发布用户创建事件
*/
public void publishUserEvent(Long userId, String userName, UserEvent.Type type, String detail) {
publishEvent(new UserEvent(type, userId, userName, detail));
}
public void publishUserCreated(Long userId, String userName) {
UserEvent event = new UserEvent(
UserEvent.Type.CREATED,
userId,
userName,
"新用户注册成功"
);
publishEvent(event);
publishUserEvent(userId, userName, UserEvent.Type.CREATED, "User created successfully");
}
/**
* 便捷方法:发布用户登录事件
*/
public void publishUserLogin(Long userId, String userName) {
UserEvent event = new UserEvent(
UserEvent.Type.LOGIN,
userId,
userName,
"用户登录成功"
);
publishEvent(event);
publishUserEvent(userId, userName, UserEvent.Type.LOGIN, "User login succeeded");
}
}
}

View File

@@ -0,0 +1,7 @@
package com.example.demo.exception;
public class DuplicateEmailException extends RuntimeException {
public DuplicateEmailException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,46 @@
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.time.Instant;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiResponse<Void>> handleNotFound(ResourceNotFoundException exception) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponse.fail(404, exception.getMessage()));
}
@ExceptionHandler(DuplicateEmailException.class)
public ResponseEntity<ApiResponse<Void>> handleDuplicateEmail(DuplicateEmailException exception) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(ApiResponse.fail(409, exception.getMessage()));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiResponse<Map<String, String>>> handleValidation(MethodArgumentNotValidException exception) {
Map<String, String> errors = new HashMap<>();
for (FieldError error : exception.getBindingResult().getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
return ResponseEntity.badRequest()
.body(new ApiResponse<>(400, "Validation failed", errors, Instant.now()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleAny(Exception exception) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponse.fail(500, "Unexpected server error"));
}
}

View File

@@ -0,0 +1,7 @@
package com.example.demo.exception;
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}

View File

@@ -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);
}
}

View 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();
}
}

View File

@@ -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();
}
}

View File

@@ -1,69 +1,112 @@
package com.example.demo.service;
import com.example.demo.dto.UserStatsResponse;
import com.example.demo.exception.DuplicateEmailException;
import com.example.demo.exception.ResourceNotFoundException;
import com.example.demo.model.User;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
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 List<User> users = new CopyOnWriteArrayList<>();
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));
users.add(new User(idGenerator.getAndIncrement(), "Alice Chen", "alice@example.com", 25));
users.add(new User(idGenerator.getAndIncrement(), "Brandon Li", "brandon@example.com", 30));
users.add(new User(idGenerator.getAndIncrement(), "Carol Wang", "carol@example.com", 28));
}
public List<User> findAll() {
return new ArrayList<>(users);
return users.stream()
.sorted((left, right) -> Long.compare(left.getId(), right.getId()))
.collect(Collectors.toList());
}
public User findById(Long id) {
return users.stream()
.filter(u -> u.getId().equals(id))
.filter(user -> user.getId().equals(id))
.findFirst()
.orElse(null);
.orElseThrow(() -> new ResourceNotFoundException("User not found: id=" + id));
}
public List<User> findByName(String name) {
public List<User> search(String keyword) {
if (keyword == null || keyword.isBlank()) {
return findAll();
}
String normalizedKeyword = keyword.trim().toLowerCase();
return users.stream()
.filter(u -> u.getName().contains(name))
.filter(user -> user.getName().toLowerCase().contains(normalizedKeyword)
|| user.getEmail().toLowerCase().contains(normalizedKeyword))
.sorted((left, right) -> Long.compare(left.getId(), right.getId()))
.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) {
ensureEmailAvailable(user.getEmail(), null);
User normalized = normalize(user, idGenerator.getAndIncrement());
users.add(normalized);
return normalized;
}
public User update(Long id, User user) {
findById(id);
ensureEmailAvailable(user.getEmail(), id);
User normalized = normalize(user, id);
for (int index = 0; index < users.size(); index++) {
if (users.get(index).getId().equals(id)) {
users.set(index, normalized);
return normalized;
}
}
return user;
throw new ResourceNotFoundException("User not found: id=" + id);
}
public void delete(Long id) {
users.removeIf(u -> u.getId().equals(id));
boolean removed = users.removeIf(user -> user.getId().equals(id));
if (!removed) {
throw new ResourceNotFoundException("User not found: id=" + id);
}
}
}
public UserStatsResponse getStats() {
long totalUsers = users.size();
long adults = users.stream().filter(user -> user.getAge() >= 18).count();
long underThirty = users.stream().filter(user -> user.getAge() < 30).count();
double averageAge = users.stream()
.mapToInt(User::getAge)
.average()
.orElse(0.0);
return new UserStatsResponse(totalUsers, adults, underThirty, averageAge);
}
private void ensureEmailAvailable(String email, Long currentUserId) {
String normalizedEmail = email == null ? "" : email.trim().toLowerCase();
boolean exists = users.stream()
.anyMatch(user -> user.getEmail().equalsIgnoreCase(normalizedEmail)
&& (currentUserId == null || !user.getId().equals(currentUserId)));
if (exists) {
throw new DuplicateEmailException("A user with email " + normalizedEmail + " already exists.");
}
}
private User normalize(User user, Long id) {
return new User(
id,
user.getName().trim(),
user.getEmail().trim().toLowerCase(),
user.getAge()
);
}
}

View File

@@ -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

View File

@@ -1,177 +1,229 @@
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AOP 切面编程 - Spring Boot</title>
<title>Spring AOP Lab</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; background: #f5f5f5; }
h1 { color: #6DB33F; margin: 20px 0; }
h2 { color: #333; border-bottom: 2px solid #6DB33F; padding-bottom: 10px; margin: 20px 0 15px; }
h3 { color: #6DB33F; margin: 15px 0 10px; }
.card { background: white; padding: 25px; margin: 15px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.btn { display: inline-block; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 500; cursor: pointer; border: none; }
.btn-primary { background: #6DB33F; color: white; }
.btn-primary:hover { background: #5da32f; }
.btn-info { background: #17a2b8; color: white; }
code { background: #f0f0f0; padding: 2px 8px; border-radius: 4px; font-family: 'Fira Code', monospace; }
pre { background: #2d2d2d; color: #f8f8f2; padding: 20px; border-radius: 8px; overflow-x: auto; margin: 15px 0; }
pre code { background: none; color: inherit; }
table { width: 100%; border-collapse: collapse; margin: 15px 0; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
th { background: #6DB33F; color: white; }
tr:nth-child(even) { background: #f9f9f9; }
.tip { background: #e7f3ff; padding: 15px; border-radius: 8px; margin: 15px 0; border-left: 4px solid #6DB33F; }
.warn { background: #fff3cd; padding: 15px; border-radius: 8px; margin: 15px 0; border-left: 4px solid #ffc107; }
.result-box { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 8px; font-family: monospace; white-space: pre-wrap; margin-top: 10px; }
.nav { margin-bottom: 20px; }
.nav a { margin-right: 15px; color: #6DB33F; text-decoration: none; }
.nav a:hover { text-decoration: underline; }
:root {
--bg: #eef7ef;
--panel: rgba(255,255,255,0.95);
--line: #d8e7d8;
--text: #102033;
--muted: #5c7184;
--brand: #3f8f2c;
--accent: #0f67b5;
--shadow: 0 20px 48px rgba(16, 32, 51, 0.12);
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: "Aptos", "Segoe UI", "Microsoft YaHei", sans-serif;
color: var(--text);
background:
radial-gradient(circle at top right, rgba(63, 143, 44, 0.14), transparent 30%),
radial-gradient(circle at bottom left, rgba(15, 103, 181, 0.1), transparent 24%),
var(--bg);
}
.page { max-width: 1280px; margin: 0 auto; padding: 24px; }
.hero, .card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 28px;
box-shadow: var(--shadow);
}
.hero { padding: 28px; margin-bottom: 18px; }
.eyebrow {
display: inline-flex;
padding: 7px 12px;
border-radius: 999px;
background: rgba(63, 143, 44, 0.1);
color: var(--brand);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
h1, h2, h3 { margin: 10px 0 12px; }
p { margin: 0; color: var(--muted); line-height: 1.8; }
.actions, .toolbar, .flow, .chips {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.btn, .btn-soft {
border: 0;
border-radius: 999px;
padding: 12px 18px;
font-weight: 700;
cursor: pointer;
}
.btn { background: linear-gradient(135deg, var(--brand), #62b049); color: #fff; }
.btn-soft { background: #eaf3ff; color: var(--accent); }
.grid {
display: grid;
gap: 18px;
grid-template-columns: 420px minmax(0, 1fr);
}
.card { padding: 22px; }
.list {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 14px;
}
.list-item, .flow-step {
padding: 14px;
border-radius: 18px;
border: 1px solid var(--line);
background: rgba(255,255,255,0.45);
}
.flow {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
margin-top: 14px;
}
.pill {
display: inline-flex;
padding: 6px 10px;
border-radius: 999px;
background: rgba(15, 103, 181, 0.08);
color: var(--accent);
font-size: 12px;
font-weight: 700;
}
pre {
margin: 0;
min-height: 280px;
padding: 16px;
border-radius: 18px;
background: #0f1621;
color: #deebff;
white-space: pre-wrap;
font-family: Consolas, "Courier New", monospace;
overflow: auto;
}
@media (max-width: 1060px) {
.grid, .flow { grid-template-columns: 1fr; }
}
@media (max-width: 720px) {
.page { padding: 14px; }
}
</style>
</head>
<body>
<div class="nav">
<a href="/">← 返回首页</a>
<a href="/users.html">用户管理</a>
<a href="/events.html">事件机制</a>
</div>
<h1>🔪 AOP 切面编程</h1>
<div class="card">
<h3>📊 实时性能统计</h3>
<p>AOP 自动统计所有 Controller 和 Service 方法的执行时间</p>
<button class="btn btn-primary" onclick="loadStats()">刷新统计数据</button>
<div class="result-box" id="statsResult">点击按钮查看...</div>
</div>
<h2>📚 AOP 核心概念</h2>
<div class="card">
<h3>1. 什么是 AOP</h3>
<p>AOP (Aspect-Oriented Programming) 面向切面编程,是将<strong>横切关注点</strong><strong>业务逻辑</strong>分离的编程范式。</p>
<div class="tip">
<strong>横切关注点:</strong>日志、事务、安全、性能监控等,散布在多个模块中的公共功能。
<div class="page">
<section class="hero">
<div class="eyebrow">AOP Lab</div>
<h1>Make cross-cutting behavior visible instead of abstract.</h1>
<p>
This page focuses on the parts students usually miss: where advice wraps controller and service methods,
how timing is collected, and why a validation failure still counts as observed runtime behavior.
</p>
<div class="actions" style="margin-top:18px;">
<a class="btn-soft" href="/">Back home</a>
<a class="btn-soft" href="/users.html">Open user lab</a>
<a class="btn-soft" href="/events.html">Open event lab</a>
</div>
</section>
<div class="grid">
<aside class="card">
<div class="eyebrow">Experiment Path</div>
<h2>Recommended AOP sequence</h2>
<div class="list">
<div class="list-item">
<strong>1. Trigger controller calls</strong>
<p>Run the list and stats endpoints to make sure both controller and service methods execute.</p>
</div>
<div class="list-item">
<strong>2. Trigger a validation failure</strong>
<p>Send an invalid user payload and compare the failed request with the successful ones.</p>
</div>
<div class="list-item">
<strong>3. Inspect aspect output</strong>
<p>Load the stats endpoint and compare call counts, total time, and average time.</p>
</div>
</div>
<div class="eyebrow" style="margin-top:18px;">Advice Map</div>
<div class="chips" style="margin-top:12px;">
<span class="pill">@Before</span>
<span class="pill">@After</span>
<span class="pill">@AfterReturning</span>
<span class="pill">@AfterThrowing</span>
<span class="pill">@Around</span>
</div>
<div class="flow">
<div class="flow-step"><strong>Before</strong><p>Inspect inputs or auth context.</p></div>
<div class="flow-step"><strong>Around</strong><p>Start timer and continue the join point.</p></div>
<div class="flow-step"><strong>Controller</strong><p>Delegate work to the service.</p></div>
<div class="flow-step"><strong>Service</strong><p>Apply business logic.</p></div>
<div class="flow-step"><strong>After*</strong><p>Record result or failure details.</p></div>
</div>
</aside>
<main class="card">
<div class="eyebrow">Live Runs</div>
<h2>Run requests and inspect collected metrics</h2>
<p>The buttons below help you create real traffic, then inspect the aspect output without switching tools.</p>
<div class="toolbar" style="margin-top:14px;">
<button class="btn" type="button" onclick="loadUsers()">Load users</button>
<button class="btn-soft" type="button" onclick="loadUserStats()">Load user stats</button>
<button class="btn-soft" type="button" onclick="sendInvalidUser()">Send invalid user</button>
<button class="btn-soft" type="button" onclick="loadAopStats()">Load AOP stats</button>
</div>
<div class="list" style="margin-top:18px;">
<div class="list-item">
<strong>What to observe in the console</strong>
<p>Look for controller and service timing lines. Compare success and failure paths to see how around advice still records method duration.</p>
</div>
<div class="list-item">
<strong>What to inspect in code</strong>
<p>Read <code>PerformanceAspect</code> first, then compare it with the user endpoints that it wraps.</p>
</div>
</div>
<pre id="resultBox">Run one of the experiments above to inspect live JSON output.</pre>
</main>
</div>
<div class="card">
<h3>2. 核心术语</h3>
<table>
<tr><th>术语</th><th>说明</th></tr>
<tr><td><strong>Aspect (切面)</strong></td><td>横切关注点的模块化封装</td></tr>
<tr><td><strong>JoinPoint (连接点)</strong></td><td>程序执行的某个点(方法调用、异常抛出等)</td></tr>
<tr><td><strong>Pointcut (切入点)</strong></td><td>匹配连接点的表达式</td></tr>
<tr><td><strong>Advice (通知)</strong></td><td>在连接点执行的动作</td></tr>
<tr><td><strong>Weaving (织入)</strong></td><td>将切面应用到目标对象的过程</td></tr>
</table>
</div>
<div class="card">
<h3>3. 五种通知类型</h3>
<table>
<tr><th>注解</th><th>执行时机</th><th>用途</th></tr>
<tr><td><code>@Before</code></td><td>方法执行前</td><td>参数校验、权限检查</td></tr>
<tr><td><code>@After</code></td><td>方法执行后(无论成功或异常)</td><td>资源清理</td></tr>
<tr><td><code>@AfterReturning</code></td><td>方法成功返回后</td><td>结果处理、日志记录</td></tr>
<tr><td><code>@AfterThrowing</code></td><td>方法抛出异常后</td><td>异常处理、错误日志</td></tr>
<tr><td><code>@Around</code></td><td>环绕方法执行(最强大)</td><td>性能统计、事务管理</td></tr>
</table>
</div>
<h2>💻 代码示例</h2>
<div class="card">
<h3>日志切面示例</h3>
<pre><code>@Aspect
@Component
public class LoggingAspect {
// 切入点:匹配所有 Controller 方法
@Pointcut("execution(* com.example.demo.controller.*.*(..))")
public void controllerMethods() {}
// 前置通知
@Before("controllerMethods()")
public void logBefore(JoinPoint jp) {
System.out.println("[AOP-Before] 方法开始: " + jp.getSignature().getName());
}
// 返回通知
@AfterReturning(pointcut = "controllerMethods()", returning = "result")
public void logAfterReturning(JoinPoint jp, Object result) {
System.out.println("[AOP-AfterReturning] 返回值: " + result);
}
}</code></pre>
</div>
<div class="card">
<h3>性能监控切面 (@Around)</h3>
<pre><code>@Aspect
@Component
public class PerformanceAspect {
@Around("execution(* com.example.demo..*.*(..))")
public Object measureTime(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
</div>
<script>
async function renderRequest(path, options = {}) {
const box = document.getElementById('resultBox');
box.textContent = 'Loading ' + path + ' ...';
try {
Object result = pjp.proceed(); // 执行目标方法
long duration = System.currentTimeMillis() - start;
System.out.println("[AOP] " + pjp.getSignature() + " 耗时: " + duration + "ms");
return result;
} catch (Throwable e) {
System.out.println("[AOP] 方法异常: " + e.getMessage());
throw e;
const response = await fetch(path, options);
const data = await response.json();
box.textContent = JSON.stringify(data, null, 2);
} catch (error) {
box.textContent = 'Request failed: ' + error.message;
}
}
}</code></pre>
</div>
<div class="card">
<h3>切入点表达式语法</h3>
<pre><code>// 匹配任意公共方法
execution(public * *(..))
// 匹配 com.example 包下所有方法
execution(* com.example.*.*(..))
async function loadUsers() {
await renderRequest('/api/users');
}
// 匹配 Controller 层所有方法
execution(* com.example.demo.controller.*.*(..))
async function loadUserStats() {
await renderRequest('/api/users/stats');
}
// 匹配所有 Service 层的 save 开头的方法
execution(* com.example.demo.service.*.save*(..))
async function loadAopStats() {
await renderRequest('/aop/aop/stats');
}
// 匹配带有 @Service 注解的类
@within(org.springframework.stereotype.Service)
// 匹配带有自定义注解的方法
@annotation(com.example.demo.aop.RateLimited)</code></pre>
</div>
<h2>🎯 实际应用场景</h2>
<div class="card">
<table>
<tr><th>场景</th><th>实现方式</th></tr>
<tr><td>日志记录</td><td>@Before + @AfterReturning</td></tr>
<tr><td>性能监控</td><td>@Around</td></tr>
<tr><td>事务管理</td><td>@Around (Spring 已内置)</td></tr>
<tr><td>权限检查</td><td>@Before</td></tr>
<tr><td>限流控制</td><td>@Around + 自定义注解</td></tr>
<tr><td>缓存</td><td>@Around (Spring Cache)</td></tr>
</table>
</div>
<p style="margin-top: 30px;"><a href="/">← 返回学习中心</a></p>
<script>
async function loadStats() {
const res = await fetch('/aop/stats');
const data = await res.json();
document.getElementById('statsResult').textContent = JSON.stringify(data, null, 2);
}
</script>
async function sendInvalidUser() {
await renderRequest('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: '', email: 'bad', age: 999 })
});
}
</script>
</body>
</html>
</html>

View File

@@ -1,213 +1,245 @@
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>事件机制 - Spring Boot</title>
<title>Spring Event Lab</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; background: #f5f5f5; }
h1 { color: #6DB33F; margin: 20px 0; }
h2 { color: #333; border-bottom: 2px solid #6DB33F; padding-bottom: 10px; margin: 20px 0 15px; }
h3 { color: #6DB33F; margin: 15px 0 10px; }
.card { background: white; padding: 25px; margin: 15px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.btn { display: inline-block; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 500; cursor: pointer; border: none; margin: 5px; }
.btn-primary { background: #6DB33F; color: white; }
.btn-primary:hover { background: #5da32f; }
.btn-info { background: #17a2b8; color: white; }
.btn-warning { background: #ffc107; color: #333; }
code { background: #f0f0f0; padding: 2px 8px; border-radius: 4px; font-family: 'Fira Code', monospace; }
pre { background: #2d2d2d; color: #f8f8f2; padding: 20px; border-radius: 8px; overflow-x: auto; margin: 15px 0; }
pre code { background: none; color: inherit; }
.tip { background: #e7f3ff; padding: 15px; border-radius: 8px; margin: 15px 0; border-left: 4px solid #6DB33F; }
.result-box { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 8px; font-family: monospace; white-space: pre-wrap; margin-top: 10px; max-height: 300px; overflow-y: auto; }
table { width: 100%; border-collapse: collapse; margin: 15px 0; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
th { background: #6DB33F; color: white; }
.event-flow { display: flex; align-items: center; justify-content: center; margin: 20px 0; }
.event-flow span { padding: 15px 25px; background: #6DB33F; color: white; border-radius: 8px; margin: 0 10px; }
.event-flow .arrow { font-size: 24px; color: #6DB33F; }
.nav { margin-bottom: 20px; }
.nav a { margin-right: 15px; color: #6DB33F; text-decoration: none; }
.nav a:hover { text-decoration: underline; }
:root {
--bg: #fff4ea;
--panel: rgba(255,255,255,0.95);
--line: #eed9c9;
--text: #132238;
--muted: #6a7484;
--brand: #dd6c1f;
--accent: #0f67b5;
--shadow: 0 22px 52px rgba(18, 32, 51, 0.12);
}
* { box-sizing: border-box; }
body {
margin: 0;
color: var(--text);
font-family: "Aptos", "Segoe UI", "Microsoft YaHei", sans-serif;
background:
radial-gradient(circle at top right, rgba(221, 108, 31, 0.16), transparent 28%),
radial-gradient(circle at bottom left, rgba(15, 103, 181, 0.1), transparent 22%),
var(--bg);
}
.page { max-width: 1280px; margin: 0 auto; padding: 24px; }
.hero, .card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 28px;
box-shadow: var(--shadow);
}
.hero { padding: 28px; margin-bottom: 18px; }
.eyebrow {
display: inline-flex;
padding: 7px 12px;
border-radius: 999px;
background: rgba(221, 108, 31, 0.1);
color: var(--brand);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
h1, h2, h3 { margin: 10px 0 12px; }
p { margin: 0; color: var(--muted); line-height: 1.8; }
.grid {
display: grid;
gap: 18px;
grid-template-columns: 420px minmax(0, 1fr);
}
.card { padding: 22px; }
.list {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 14px;
}
.item, .timeline-step {
padding: 14px;
border-radius: 18px;
border: 1px solid var(--line);
background: rgba(255,255,255,0.46);
}
.toolbar, .actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.btn, .btn-soft {
border: 0;
border-radius: 999px;
padding: 12px 18px;
font-weight: 700;
cursor: pointer;
}
.btn { background: linear-gradient(135deg, var(--brand), #f39a55); color: #fff; }
.btn-soft { background: #edf5ff; color: var(--accent); }
.fields {
display: grid;
gap: 12px;
grid-template-columns: repeat(3, minmax(0, 1fr));
margin-top: 14px;
}
label {
display: flex;
flex-direction: column;
gap: 8px;
font-size: 13px;
font-weight: 700;
color: #22394f;
}
input, select {
width: 100%;
border: 1px solid var(--line);
border-radius: 14px;
padding: 12px 14px;
background: transparent;
color: var(--text);
outline: none;
}
.timeline {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-top: 14px;
}
pre {
margin: 0;
min-height: 280px;
padding: 16px;
border-radius: 18px;
background: #111926;
color: #deebff;
white-space: pre-wrap;
font-family: Consolas, "Courier New", monospace;
overflow: auto;
}
@media (max-width: 1060px) {
.grid, .timeline, .fields { grid-template-columns: 1fr; }
}
@media (max-width: 720px) {
.page { padding: 14px; }
}
</style>
</head>
<body>
<div class="nav">
<a href="/">← 返回首页</a>
<a href="/users.html">用户管理</a>
<a href="/aop.html">AOP 切面</a>
</div>
<h1>📡 Spring 事件机制</h1>
<div class="card">
<h3>🎉 事件发布演示</h3>
<p>模拟用户登录事件,观察事件发布和监听过程</p>
<div style="margin: 15px 0;">
<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>
<div class="page">
<section class="hero">
<div class="eyebrow">Event Lab</div>
<h1>Understand publisher-listener decoupling through a visible event timeline.</h1>
<p>
This page helps you observe what usually stays hidden: the request can finish quickly while listeners keep
reacting in the background. Publish multiple event types and then inspect the shared event history.
</p>
<div class="actions" style="margin-top:18px;">
<a class="btn-soft" href="/">Back home</a>
<a class="btn-soft" href="/aop.html">Open AOP lab</a>
<a class="btn-soft" href="/users.html">Open user lab</a>
</div>
<div class="result-box" id="eventResult">等待事件发布...</div>
</section>
<div class="grid">
<aside class="card">
<div class="eyebrow">Event Story</div>
<h2>What to watch for</h2>
<div class="timeline">
<div class="timeline-step"><strong>Controller</strong><p>Receives the publish request.</p></div>
<div class="timeline-step"><strong>Publisher</strong><p>Builds a `UserEvent` and emits it.</p></div>
<div class="timeline-step"><strong>Listeners</strong><p>Track history and optional async work.</p></div>
<div class="timeline-step"><strong>History API</strong><p>Lets you inspect what actually happened.</p></div>
</div>
<div class="list">
<div class="item">
<strong>Experiment 1</strong>
<p>Publish LOGIN twice with different users and confirm the history list grows without changing controller code.</p>
</div>
<div class="item">
<strong>Experiment 2</strong>
<p>Publish CREATED and then refresh history to see the same endpoint support multiple listener paths.</p>
</div>
<div class="item">
<strong>Code pairing tip</strong>
<p>Read `UserEventPublisher` and `UserEventListener` side by side to see the decoupling boundary.</p>
</div>
</div>
</aside>
<main class="card">
<div class="eyebrow">Live Event Console</div>
<h2>Publish events and inspect history</h2>
<p>Use the form to publish events, then reload history to inspect type, user, detail, and timestamp.</p>
<div class="fields">
<label>
Event type
<select id="eventType">
<option value="LOGIN">LOGIN</option>
<option value="CREATED">CREATED</option>
<option value="UPDATED">UPDATED</option>
<option value="DELETED">DELETED</option>
</select>
</label>
<label>
User id
<input id="userId" value="21">
</label>
<label>
User name
<input id="userName" value="observer-demo">
</label>
</div>
<div class="toolbar" style="margin-top:14px;">
<button class="btn" type="button" onclick="publishEvent()">Publish event</button>
<button class="btn-soft" type="button" onclick="loadHistory()">Load history</button>
<button class="btn-soft" type="button" onclick="loadInfo()">Load event notes</button>
</div>
<div class="list" style="margin-top:18px;">
<div class="item">
<strong>Interpretation hint</strong>
<p>If the controller returns immediately but history keeps growing, you are seeing decoupled follow-up behavior in action.</p>
</div>
</div>
<pre id="resultBox">Publish an event or load history to inspect live output.</pre>
</main>
</div>
<h2>🔄 事件机制流程</h2>
<div class="event-flow">
<span>发布者</span>
<span class="arrow"></span>
<span>ApplicationEventPublisher</span>
<span class="arrow"></span>
<span>事件</span>
<span class="arrow"></span>
<span>监听者</span>
</div>
<div class="tip">
<strong>核心优势:</strong>
<ul style="margin-top: 10px; padding-left: 20px;">
<li><strong>解耦:</strong>发布者和监听者互不依赖</li>
<li><strong>扩展:</strong>新增监听器无需修改发布者</li>
<li><strong>异步:</strong>耗时操作不阻塞主流程</li>
</ul>
</div>
<h2>💻 代码实现</h2>
<div class="card">
<h3>1. 定义事件</h3>
<pre><code>public class UserEvent {
public enum Type { CREATED, UPDATED, DELETED, LOGIN }
private Type type;
private Long userId;
private String userName;
private LocalDateTime timestamp;
// constructor, getters...
}</code></pre>
</div>
<div class="card">
<h3>2. 发布事件</h3>
<pre><code>@Component
public class UserEventPublisher {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void publishUserLogin(Long userId, String userName) {
UserEvent event = new UserEvent(
UserEvent.Type.LOGIN,
userId,
userName,
"用户登录成功"
);
eventPublisher.publishEvent(event);
}
}</code></pre>
</div>
<div class="card">
<h3>3. 监听事件</h3>
<pre><code>@Component
public class UserEventListener {
// 基础监听
@EventListener
public void handleUserEvent(UserEvent event) {
System.out.println("收到事件: " + event.getType());
}
// 条件监听 - 只处理登录事件
@EventListener(condition = "#event.type == T(com.example.demo.model.UserEvent$Type).LOGIN")
public void handleLogin(UserEvent event) {
System.out.println("用户登录: " + event.getUserName());
}
// 异步监听 - 不阻塞主流程
@Async
@EventListener
public void sendWelcomeEmail(UserEvent event) {
// 发送邮件...
}
}</code></pre>
</div>
<div class="card">
<h3>4. 控制器中使用</h3>
<pre><code>@RestController
@RequestMapping("/aop")
public class AopEventController {
@Autowired
private UserEventPublisher eventPublisher;
@PostMapping("/event/publish")
public Map&lt;String, Object&gt; publishEvent(
@RequestParam Long userId,
@RequestParam String userName) {
// 发布事件
eventPublisher.publishUserLogin(userId, userName);
return Map.of(
"message", "事件已发布",
"userId", userId,
"userName", userName
);
}
}</code></pre>
</div>
<h2>🎯 应用场景</h2>
<div class="card">
<table>
<tr><th>场景</th><th>事件类型</th><th>处理逻辑</th></tr>
<tr><td>用户注册</td><td>UserCreatedEvent</td><td>发送欢迎邮件、初始化数据</td></tr>
<tr><td>订单创建</td><td>OrderCreatedEvent</td><td>扣库存、发送通知</td></tr>
<tr><td>支付成功</td><td>PaymentSuccessEvent</td><td>更新订单状态、发送短信</td></tr>
<tr><td>用户登录</td><td>UserLoginEvent</td><td>记录登录日志、更新在线状态</td></tr>
</table>
</div>
<div class="card">
<h3>💡 最佳实践</h3>
<ul style="line-height: 2; padding-left: 20px;">
<li>事件类应该是<strong>不可变</strong>的(只读属性)</li>
<li>使用 <code>@Async</code> 处理耗时操作</li>
<li>避免在监听器中抛出异常</li>
<li>使用 <code>condition</code> 过滤不需要的事件</li>
<li>复杂场景考虑使用消息队列RabbitMQ/Kafka</li>
</ul>
</div>
<p style="margin-top: 30px;"><a href="/">← 返回学习中心</a></p>
<script>
async function publishEvent() {
const userId = document.getElementById('userId').value;
const userName = document.getElementById('userName').value;
try {
const res = await fetch(`/aop/event/publish?userId=${userId}&userName=${encodeURIComponent(userName)}`, {
method: 'POST'
});
const data = await res.json();
const resultBox = document.getElementById('eventResult');
resultBox.textContent = `[${new Date().toLocaleTimeString()}] 事件已发布\n\n` +
JSON.stringify(data, null, 2) + '\n\n' +
'📊 查看控制台日志可以看到监听器的输出:\n' +
'[EventPublisher] 发布事件: LOGIN - ' + userName + '\n' +
'[EventListener] 收到事件: LOGIN - 用户: ' + userName + '\n' +
'[LoginTracker] 记录用户登录: ' + userName;
} catch (e) {
document.getElementById('eventResult').textContent = '错误: ' + e.message;
}
</div>
<script>
async function renderRequest(path, options = {}) {
const box = document.getElementById('resultBox');
box.textContent = 'Loading ' + path + ' ...';
try {
const response = await fetch(path, options);
const data = await response.json();
box.textContent = JSON.stringify(data, null, 2);
} catch (error) {
box.textContent = 'Request failed: ' + error.message;
}
</script>
}
async function publishEvent() {
const type = document.getElementById('eventType').value;
const userId = document.getElementById('userId').value.trim() || '21';
const userName = document.getElementById('userName').value.trim() || 'observer-demo';
const params = new URLSearchParams({ userId, userName, eventType: type });
await renderRequest('/aop/event/publish?' + params.toString(), { method: 'POST' });
}
async function loadHistory() {
await renderRequest('/aop/event/history');
}
async function loadInfo() {
await renderRequest('/aop/event');
}
</script>
</body>
</html>
</html>

View File

@@ -1,221 +1,408 @@
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spring Boot 学习中心</title>
<title>Spring Boot Learning Cockpit</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; background: #f5f5f5; }
h1 { color: #6DB33F; text-align: center; margin: 30px 0; font-size: 2.5em; }
h2 { color: #333; border-bottom: 3px solid #6DB33F; padding-bottom: 10px; margin: 20px 0 15px; }
.card { background: white; padding: 25px; margin: 15px 0; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.card h3 { color: #6DB33F; margin-bottom: 15px; font-size: 1.3em; }
.btn-group { display: flex; flex-wrap: wrap; gap: 10px; margin: 15px 0; }
.btn { display: inline-block; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 500; transition: all 0.3s; }
.btn-primary { background: #6DB33F; color: white; }
.btn-primary:hover { background: #5da32f; transform: translateY(-2px); }
.btn-secondary { background: #333; color: white; }
.btn-secondary:hover { background: #444; }
.btn-info { background: #17a2b8; color: white; }
.btn-info:hover { background: #138496; }
.btn-warning { background: #ffc107; color: #333; }
.btn-warning:hover { background: #e0a800; }
code { background: #f0f0f0; padding: 2px 8px; border-radius: 4px; font-family: 'Fira Code', monospace; font-size: 14px; }
pre { background: #2d2d2d; color: #f8f8f2; padding: 20px; border-radius: 8px; overflow-x: auto; margin: 15px 0; }
pre code { background: none; color: inherit; }
ul { line-height: 2; padding-left: 20px; }
.feature-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; }
.feature-item { background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid #6DB33F; transition: all 0.3s; }
.feature-item:hover { transform: translateY(-3px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.feature-item h4 { color: #333; margin-bottom: 8px; font-size: 1.1em; }
.feature-item p { color: #666; font-size: 14px; margin: 0; }
.feature-item a { color: inherit; text-decoration: none; }
.api-test { background: #f8f9fa; padding: 15px; margin: 10px 0; border-radius: 8px; }
.api-test input, .api-test select { padding: 10px; border: 1px solid #ddd; border-radius: 4px; margin: 5px; }
.api-test button { padding: 10px 20px; background: #6DB33F; color: white; border: none; border-radius: 4px; cursor: pointer; }
.api-test button:hover { background: #5da32f; }
#result { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 8px; margin-top: 10px; white-space: pre-wrap; font-family: monospace; font-size: 14px; }
.footer { text-align: center; margin-top: 40px; padding: 20px; color: #666; border-top: 1px solid #ddd; }
.nav-links { display: flex; justify-content: center; gap: 15px; margin-bottom: 30px; }
.nav-links a { padding: 10px 20px; background: white; border-radius: 8px; text-decoration: none; color: #6DB33F; font-weight: 500; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.nav-links a:hover { background: #6DB33F; color: white; }
.nav-links a.active { background: #6DB33F; color: white; }
:root {
--bg: #eef5ff;
--panel: rgba(255, 255, 255, 0.94);
--line: #d8e4f0;
--text: #122033;
--muted: #5d7288;
--brand: #177245;
--accent: #0f67b5;
--warm: #f08c2b;
--shadow: 0 22px 54px rgba(18, 32, 51, 0.12);
}
* { box-sizing: border-box; }
body {
margin: 0;
color: var(--text);
font-family: "Aptos", "Segoe UI", "Microsoft YaHei", sans-serif;
background:
radial-gradient(circle at top left, rgba(23, 114, 69, 0.14), transparent 28%),
radial-gradient(circle at bottom right, rgba(15, 103, 181, 0.14), transparent 26%),
var(--bg);
}
a { color: inherit; text-decoration: none; }
button, input, select { font: inherit; }
.page { max-width: 1380px; margin: 0 auto; padding: 24px; }
.hero, .card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 28px;
box-shadow: var(--shadow);
backdrop-filter: blur(10px);
}
.hero { padding: 28px; margin-bottom: 18px; }
.eyebrow {
display: inline-flex;
padding: 7px 12px;
border-radius: 999px;
background: rgba(23, 114, 69, 0.1);
color: var(--brand);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
h1, h2, h3 { margin: 10px 0 12px; }
p { margin: 0; color: var(--muted); line-height: 1.8; }
.hero-grid, .workspace, .triple {
display: grid;
gap: 18px;
}
.hero-grid {
grid-template-columns: 1.3fr 0.9fr;
align-items: start;
}
.actions, .chip-list, .toolbar, .demo-links {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.btn, .btn-soft {
display: inline-flex;
align-items: center;
justify-content: center;
border: 0;
border-radius: 999px;
padding: 12px 18px;
cursor: pointer;
font-weight: 700;
}
.btn {
color: #fff;
background: linear-gradient(135deg, var(--brand), #35a465);
}
.btn-soft {
color: var(--accent);
background: #eaf3ff;
}
.card { padding: 22px; }
.stats {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-top: 18px;
}
.stat {
padding: 16px;
border-radius: 18px;
border: 1px solid var(--line);
background: rgba(255,255,255,0.5);
}
.stat span { display: block; color: var(--muted); font-size: 12px; margin-bottom: 8px; }
.stat strong { font-size: 28px; }
.workspace {
grid-template-columns: 380px minmax(0, 1fr);
align-items: start;
}
.triple {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.flow {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
gap: 12px;
margin-top: 14px;
}
.step, .lab, .note, .code-card {
border: 1px solid var(--line);
border-radius: 20px;
padding: 16px;
background: rgba(255,255,255,0.45);
}
.step strong, .lab strong, .code-card strong { display: block; margin-bottom: 8px; }
.lab small, .step small, .note small { color: var(--muted); display: block; line-height: 1.7; }
.field {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 12px;
}
label { font-size: 13px; font-weight: 700; color: #21384f; }
input, select {
width: 100%;
border: 1px solid var(--line);
border-radius: 14px;
padding: 12px 14px;
background: transparent;
color: var(--text);
outline: none;
}
.console {
margin-top: 14px;
border-radius: 18px;
overflow: hidden;
border: 1px solid #d6e2ef;
background: #0e1723;
}
.console-head {
padding: 12px 14px;
border-bottom: 1px solid rgba(216, 228, 240, 0.14);
color: #bdd2ea;
font-weight: 700;
}
pre {
margin: 0;
min-height: 240px;
padding: 16px;
color: #dceaff;
white-space: pre-wrap;
font-family: Consolas, "Courier New", monospace;
overflow: auto;
}
.pill {
display: inline-flex;
padding: 6px 10px;
border-radius: 999px;
background: rgba(15, 103, 181, 0.08);
color: var(--accent);
font-size: 12px;
font-weight: 700;
}
.list {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 14px;
}
.list-item {
padding: 14px;
border-radius: 18px;
border: 1px solid var(--line);
background: rgba(255,255,255,0.45);
}
.list-item p { margin-top: 8px; }
@media (max-width: 1180px) {
.hero-grid, .workspace, .triple, .flow, .stats { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 780px) {
.page { padding: 14px; }
.hero-grid, .workspace, .triple, .flow, .stats { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<h1>🍃 Spring Boot 学习中心</h1>
<div class="nav-links">
<a href="/" class="active">首页</a>
<a href="/users.html">用户管理</a>
<a href="/aop.html">AOP 切面</a>
<a href="/events.html">事件机制</a>
</div>
<div class="card">
<h3>📚 学习模块</h3>
<div class="feature-grid">
<a href="/users.html" class="feature-item">
<h4>👥 用户管理</h4>
<p>RESTful API 设计、CRUD 操作、参数绑定</p>
</a>
<a href="/aop.html" class="feature-item">
<h4>🔪 AOP 切面编程</h4>
<p>日志记录、性能监控、限流控制</p>
</a>
<a href="/events.html" class="feature-item">
<h4>📡 事件机制</h4>
<p>发布/订阅模式、解耦业务逻辑</p>
</a>
<div class="page">
<section class="hero">
<div class="hero-grid">
<div>
<div class="eyebrow">Spring Boot Learning Cockpit</div>
<h1>Use one workspace to understand MVC, validation, security, AOP, and application events.</h1>
<p>
This homepage is now a guided study cockpit. Instead of only linking to pages, it explains the request
path, suggests experiment sequences, and lets you call real endpoints to observe how the demo behaves.
</p>
<div class="actions" style="margin-top:18px;">
<a class="btn" href="/users.html">Open user lab</a>
<a class="btn-soft" href="/aop.html">Open AOP lab</a>
<a class="btn-soft" href="/events.html">Open event lab</a>
<a class="btn-soft" href="/learn">Open MVC learn API</a>
</div>
<div class="stats">
<div class="stat"><span>Core labs</span><strong>4</strong></div>
<div class="stat"><span>Major layers</span><strong>6</strong></div>
<div class="stat"><span>Interactive pages</span><strong>4</strong></div>
<div class="stat"><span>Tested backend paths</span><strong>2+</strong></div>
</div>
</div>
<div class="card" style="padding:0;">
<div class="card" style="box-shadow:none; border:none; border-radius:28px;">
<div class="eyebrow">Start Here</div>
<h2>Recommended study order</h2>
<div class="list">
<div class="list-item">
<strong>1. Learn endpoint binding</strong>
<p>Hit the live API explorer below and compare query, path, header, cookie, and JSON body patterns.</p>
</div>
<div class="list-item">
<strong>2. Study users and validation</strong>
<p>Open the user lab to inspect CRUD, duplicate email handling, and aggregate stats.</p>
</div>
<div class="list-item">
<strong>3. Watch cross-cutting behavior</strong>
<p>Move to AOP and events to see timing, rate limiting, and listener history.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<h2>🔗 快速链接</h2>
<div class="card">
<div class="btn-group">
<a class="btn btn-primary" href="/learn">API 接口列表</a>
<a class="btn btn-info" href="/api/users">用户 JSON</a>
<a class="btn btn-secondary" href="/actuator/health">健康检查</a>
</div>
</div>
<h2>🧪 接口测试</h2>
<div class="card">
<h3>GET 参数示例</h3>
<div class="api-test">
<input type="text" id="param-name" placeholder="姓名" value="张三">
<input type="number" id="param-age" placeholder="年龄" value="25">
<button onclick="testParams()">测试</button>
<div id="result-params"></div>
</div>
<p><code>GET /learn/params?name=xxx&age=18</code></p>
</div>
<div class="card">
<h3>路径变量示例</h3>
<div class="api-test">
<input type="text" id="path-id" placeholder="ID" value="123">
<button onclick="testPath()">测试</button>
<div id="result-path"></div>
</div>
<p><code>GET /learn/path/{id}</code></p>
</div>
<div class="card">
<h3>POST JSON 示例</h3>
<div class="api-test">
<input type="text" id="post-data" placeholder='JSON 数据' value='{"name":"test","value":123}' style="width: 300px;">
<button onclick="testPost()">测试</button>
<div id="result-post"></div>
</div>
<p><code>POST /learn/body</code></p>
</div>
<h2>📖 学习路径</h2>
<div class="card">
<h3>1. IOC 容器</h3>
<ul>
<li><code>@Component</code>, <code>@Service</code>, <code>@Repository</code>, <code>@Controller</code></li>
<li><code>@Autowired</code> 依赖注入</li>
<li><code>@Configuration</code> + <code>@Bean</code> 配置类</li>
</ul>
</div>
<div class="card">
<h3>2. Web 开发</h3>
<ul>
<li><code>@RestController</code> = <code>@Controller</code> + <code>@ResponseBody</code></li>
<li><code>@RequestMapping</code>, <code>@GetMapping</code>, <code>@PostMapping</code></li>
<li><code>@PathVariable</code>, <code>@RequestParam</code>, <code>@RequestBody</code></li>
</ul>
</div>
<div class="card">
<h3>3. AOP 切面编程</h3>
<pre><code>@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.*.*(..))")
public void logBefore(JoinPoint jp) {
System.out.println("方法调用: " + jp.getSignature());
}
}</code></pre>
</div>
<div class="card">
<h3>4. 事件机制</h3>
<pre><code>// 发布事件
@Autowired
ApplicationEventPublisher publisher;
publisher.publishEvent(new UserEvent(...));
</section>
// 监听事件
@EventListener
public void onEvent(UserEvent event) {
// 处理事件
}</code></pre>
<section class="card" style="margin-bottom:18px;">
<div class="eyebrow">Architecture</div>
<h2>How one request travels through the demo</h2>
<div class="flow">
<div class="step"><strong>Browser</strong><small>Form submit or fetch call starts the request.</small></div>
<div class="step"><strong>Security</strong><small>JWT demo routes decide whether the request is public or protected.</small></div>
<div class="step"><strong>Controller</strong><small>Spring binds params, body, headers, and cookies into method arguments.</small></div>
<div class="step"><strong>Service</strong><small>Business rules run, such as duplicate email checks or stats calculation.</small></div>
<div class="step"><strong>AOP / Events</strong><small>Cross-cutting timing or event listeners react without cluttering core logic.</small></div>
<div class="step"><strong>Response</strong><small>Structured JSON or HTML returns to the page and becomes visible feedback.</small></div>
</div>
</section>
<div class="workspace">
<aside class="card">
<div class="eyebrow">Lab Tracks</div>
<h2>What to practice in each area</h2>
<div class="list">
<div class="lab">
<strong>User management</strong>
<small>Create a user, trigger duplicate email protection, search records, and compare stats before and after changes.</small>
</div>
<div class="lab">
<strong>MVC parameter binding</strong>
<small>Use `/learn` routes to compare `@RequestParam`, `@PathVariable`, `@RequestBody`, `@RequestHeader`, and `@CookieValue`.</small>
</div>
<div class="lab">
<strong>AOP tracing</strong>
<small>Trigger `/api/users` and `/api/users/stats`, then inspect `/aop/aop/stats` to see which methods were counted.</small>
</div>
<div class="lab">
<strong>Application events</strong>
<small>Publish LOGIN or CREATED events and refresh event history to understand publisher-listener decoupling.</small>
</div>
</div>
<div class="eyebrow" style="margin-top:20px;">Code Reading Map</div>
<h2>Files worth reading next</h2>
<div class="list">
<div class="code-card">
<strong>UserController -> UserService</strong>
<small>Shows validation, CRUD orchestration, search, and stats aggregation.</small>
</div>
<div class="code-card">
<strong>LearningSecurityConfig + LearningJwtFilter</strong>
<small>Explains why most labs stay public while `/api/secure/**` stays protected.</small>
</div>
<div class="code-card">
<strong>PerformanceAspect + UserEventPublisher + UserEventListener</strong>
<small>Shows the two cleanest examples of cross-cutting and event-driven behavior.</small>
</div>
</div>
</aside>
<main class="triple">
<section class="card" style="grid-column: 1 / -1;">
<div class="eyebrow">Live Explorer</div>
<h2>Call real endpoints without leaving the page</h2>
<p>Use these controls to inspect real JSON responses while you read the code. This makes the project easier to connect to concrete behavior.</p>
<div class="toolbar" style="margin-top:14px;">
<button class="btn" type="button" onclick="loadEndpoint('/actuator/health')">Health</button>
<button class="btn-soft" type="button" onclick="loadEndpoint('/api/users/stats')">User stats</button>
<button class="btn-soft" type="button" onclick="loadEndpoint('/learn')">Learn overview</button>
<button class="btn-soft" type="button" onclick="loadEndpoint('/aop/aop/stats')">AOP stats</button>
<button class="btn-soft" type="button" onclick="loadEndpoint('/aop/event/history')">Event history</button>
</div>
<div class="triple" style="margin-top:16px;">
<div class="card" style="padding:0; box-shadow:none; background:transparent; border:none;">
<div class="field">
<label for="eventType">Publish demo event</label>
<select id="eventType">
<option value="LOGIN">LOGIN</option>
<option value="CREATED">CREATED</option>
<option value="UPDATED">UPDATED</option>
<option value="DELETED">DELETED</option>
</select>
</div>
</div>
<div class="card" style="padding:0; box-shadow:none; background:transparent; border:none;">
<div class="field">
<label for="eventUserId">User id</label>
<input id="eventUserId" value="99">
</div>
</div>
<div class="card" style="padding:0; box-shadow:none; background:transparent; border:none;">
<div class="field">
<label for="eventUserName">User name</label>
<input id="eventUserName" value="learning-user">
</div>
</div>
</div>
<div class="toolbar" style="margin-top:14px;">
<button class="btn" type="button" onclick="publishEvent()">Publish event</button>
<button class="btn-soft" type="button" onclick="loadEndpoint('/api/users')">Load users</button>
</div>
<div class="console">
<div class="console-head">Endpoint output</div>
<pre id="consoleOutput">Select an experiment above to load live output.</pre>
</div>
</section>
<section class="card">
<div class="eyebrow">Experiment 1</div>
<h2>Trace validation</h2>
<p>Open the user lab, create a user, then repeat with the same email. Compare the frontend error with `DuplicateEmailException` and the global exception handler.</p>
<div class="chip-list" style="margin-top:12px;">
<span class="pill">UserController</span>
<span class="pill">UserService</span>
<span class="pill">GlobalExceptionHandler</span>
</div>
</section>
<section class="card">
<div class="eyebrow">Experiment 2</div>
<h2>Trace AOP timing</h2>
<p>Load users and stats several times, then call `/aop/aop/stats`. Watch how controller and service methods accumulate timing and call count data.</p>
<div class="chip-list" style="margin-top:12px;">
<span class="pill">PerformanceAspect</span>
<span class="pill">@Around</span>
<span class="pill">Cross-cutting</span>
</div>
</section>
<section class="card">
<div class="eyebrow">Experiment 3</div>
<h2>Trace event decoupling</h2>
<p>Publish CREATED and LOGIN events, then reload event history. This shows how the request can finish while listeners keep handling side effects.</p>
<div class="chip-list" style="margin-top:12px;">
<span class="pill">Publisher</span>
<span class="pill">Listener</span>
<span class="pill">@Async</span>
</div>
</section>
</main>
</div>
<h2>📁 项目结构</h2>
<div class="card">
<pre><code>├── src/main/java/com/example/demo/
├── DemoApplication.java # 启动类
├── controller/ # 控制器层
├── LearnController.java # 学习示例
├── UserController.java # 用户 API
└── AopEventController.java
├── service/ # 业务逻辑层
├── model/ # 实体类
│ ├── aop/ # AOP 切面
├── LoggingAspect.java
├── PerformanceAspect.java
└── RateLimitAspect.java
│ └── event/ # 事件机制
├── UserEventPublisher.java
│ └── UserEventListener.java
├── src/main/resources/
│ ├── static/ # 静态资源
│ │ ├── index.html
│ │ ├── users.html
│ │ ├── aop.html
│ │ └── events.html
│ └── application.properties # 配置文件
└── pom.xml # Maven 配置</code></pre>
</div>
<div class="footer">
<p>🍃 Spring Boot 学习脚手架 | <a href="https://spring.io" style="color: #6DB33F;">Spring 官网</a></p>
</div>
<script>
async function testParams() {
const name = document.getElementById('param-name').value;
const age = document.getElementById('param-age').value;
const res = await fetch(`/learn/params?name=${encodeURIComponent(name)}&age=${age}`);
const data = await res.json();
document.getElementById('result-params').innerHTML = '<div id="result">' + JSON.stringify(data, null, 2) + '</div>';
</div>
<script>
async function loadEndpoint(path, options = {}) {
const output = document.getElementById('consoleOutput');
output.textContent = 'Loading ' + path + ' ...';
try {
const response = await fetch(path, options);
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
const json = await response.json();
output.textContent = JSON.stringify(json, null, 2);
} else {
output.textContent = await response.text();
}
} catch (error) {
output.textContent = 'Request failed: ' + error.message;
}
async function testPath() {
const id = document.getElementById('path-id').value;
const res = await fetch(`/learn/path/${id}`);
const data = await res.json();
document.getElementById('result-path').innerHTML = '<div id="result">' + JSON.stringify(data, null, 2) + '</div>';
}
async function testPost() {
const data = document.getElementById('post-data').value;
const res = await fetch('/learn/body', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: data
});
const result = await res.json();
document.getElementById('result-post').innerHTML = '<div id="result">' + JSON.stringify(result, null, 2) + '</div>';
}
</script>
}
async function publishEvent() {
const type = document.getElementById('eventType').value;
const userId = document.getElementById('eventUserId').value.trim() || '99';
const userName = document.getElementById('eventUserName').value.trim() || 'learning-user';
const params = new URLSearchParams({
userId,
userName,
eventType: type
});
await loadEndpoint('/aop/event/publish?' + params.toString(), { method: 'POST' });
}
</script>
</body>
</html>
</html>

View File

@@ -1,225 +1,466 @@
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户管理 - Spring Boot</title>
<title>User Management Lab</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; background: #f5f5f5; }
h1 { color: #6DB33F; margin: 20px 0; }
h2 { color: #333; margin: 20px 0 10px; }
.card { background: white; padding: 20px; margin: 15px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
table { width: 100%; border-collapse: collapse; margin: 15px 0; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
th { background: #6DB33F; color: white; }
tr:nth-child(even) { background: #f9f9f9; }
tr:hover { background: #f0f0f0; }
.btn { display: inline-block; padding: 8px 16px; border-radius: 4px; text-decoration: none; font-size: 14px; cursor: pointer; border: none; }
.btn-primary { background: #6DB33F; color: white; }
.btn-primary:hover { background: #5da32f; }
.btn-danger { background: #dc3545; color: white; }
.btn-danger:hover { background: #c82333; }
.btn-secondary { background: #6c757d; color: white; }
.btn-success { background: #28a745; color: white; }
.form-group { margin: 15px 0; }
.form-group label { display: block; margin-bottom: 5px; font-weight: bold; }
.form-group input { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; }
.modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); }
.modal.active { display: flex; justify-content: center; align-items: center; }
.modal-content { background: white; padding: 30px; border-radius: 8px; width: 400px; }
.modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.modal-header h3 { margin: 0; }
.close-btn { background: none; border: none; font-size: 24px; cursor: pointer; }
.btn-group { display: flex; gap: 10px; margin-top: 20px; }
.tip { background: #e7f3ff; padding: 15px; border-radius: 4px; margin: 15px 0; border-left: 4px solid #6DB33F; }
code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; }
pre { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 4px; overflow-x: auto; }
:root {
--bg: linear-gradient(135deg, #f4fff2 0%, #eef6ff 100%);
--card: rgba(255, 255, 255, 0.94);
--line: #dde7f3;
--text: #123;
--muted: #5c7289;
--green: #3f8f2c;
--blue: #0f6db5;
--red: #d64545;
--shadow: 0 18px 45px rgba(17, 47, 80, 0.12);
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: "Segoe UI", "PingFang SC", sans-serif;
background: var(--bg);
color: var(--text);
}
.page {
max-width: 1120px;
margin: 0 auto;
padding: 28px 18px 48px;
}
.card {
background: var(--card);
border: 1px solid rgba(255,255,255,0.8);
border-radius: 24px;
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.hero {
display: grid;
gap: 18px;
grid-template-columns: minmax(0, 1.6fr) minmax(280px, 0.9fr);
margin-bottom: 22px;
}
.hero-main,
.hero-side,
.table-card,
.tool-card {
padding: 24px;
}
.eyebrow {
display: inline-flex;
padding: 8px 14px;
border-radius: 999px;
background: rgba(63, 143, 44, 0.12);
color: #2d6e20;
font-size: 12px;
font-weight: 700;
letter-spacing: .06em;
text-transform: uppercase;
}
h1 {
margin: 18px 0 12px;
font-size: clamp(32px, 5vw, 50px);
line-height: 1.05;
}
h2, h3 { margin: 0; }
p { color: var(--muted); line-height: 1.7; }
.hero-actions,
.toolbar,
.modal-actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.btn {
border: 0;
border-radius: 14px;
padding: 12px 18px;
font-weight: 700;
cursor: pointer;
}
.btn-primary { background: linear-gradient(135deg, var(--green), #59b83f); color: #fff; }
.btn-secondary { background: rgba(15, 109, 181, 0.08); color: var(--blue); }
.btn-danger { background: rgba(214, 69, 69, 0.12); color: var(--red); }
.stats {
display: grid;
gap: 16px;
grid-template-columns: repeat(4, minmax(0, 1fr));
margin-bottom: 22px;
}
.stat {
padding: 18px 20px;
}
.stat small {
color: var(--muted);
font-size: 12px;
text-transform: uppercase;
letter-spacing: .08em;
}
.stat strong {
display: block;
margin-top: 10px;
font-size: 34px;
}
.workspace {
display: grid;
gap: 18px;
grid-template-columns: minmax(0, 1.45fr) minmax(280px, 0.8fr);
}
.section-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
.pill {
display: inline-flex;
align-items: center;
padding: 6px 12px;
border-radius: 999px;
background: rgba(63, 143, 44, 0.1);
color: #2d6e20;
font-size: 12px;
font-weight: 700;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 13px 12px;
border-bottom: 1px solid var(--line);
text-align: left;
}
th {
color: var(--muted);
font-size: 12px;
text-transform: uppercase;
letter-spacing: .08em;
}
tr:last-child td { border-bottom: 0; }
.segment {
display: inline-flex;
padding: 5px 10px;
border-radius: 999px;
background: rgba(15, 109, 181, 0.08);
color: var(--blue);
font-size: 12px;
font-weight: 700;
}
label {
display: grid;
gap: 8px;
font-size: 14px;
font-weight: 700;
}
input {
width: 100%;
padding: 12px 14px;
border-radius: 14px;
border: 1px solid var(--line);
font: inherit;
}
input:focus {
outline: 2px solid rgba(15, 109, 181, 0.18);
border-color: rgba(15, 109, 181, 0.45);
}
.status {
min-height: 22px;
margin-top: 12px;
color: var(--muted);
font-size: 14px;
}
.status.error { color: var(--red); }
.status.success { color: #2d6e20; }
.empty {
border: 1px dashed var(--line);
border-radius: 18px;
text-align: center;
padding: 28px;
color: var(--muted);
}
.modal {
position: fixed;
inset: 0;
display: none;
justify-content: center;
align-items: center;
background: rgba(13, 26, 46, 0.5);
padding: 18px;
}
.modal.active { display: flex; }
.modal-card {
width: min(100%, 460px);
padding: 24px;
}
.close {
border: 0;
background: transparent;
font-size: 24px;
color: var(--muted);
cursor: pointer;
}
@media (max-width: 920px) {
.hero, .stats, .workspace { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<h1>👥 用户管理 - RESTful API 示例</h1>
<div class="card">
<div style="display: flex; justify-content: space-between; align-items: center;">
<h2>用户列表</h2>
<button class="btn btn-primary" onclick="openModal()">+ 添加用户</button>
</div>
<table id="userTable">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="card">
<h2>📖 学习要点</h2>
<div class="tip">
<strong>RESTful API 设计:</strong>
<ul style="margin-top: 10px; padding-left: 20px;">
<li><code>GET /api/users</code> - 获取所有用户</li>
<li><code>GET /api/users/{id}</code> - 获取单个用户</li>
<li><code>POST /api/users</code> - 创建用户</li>
<li><code>PUT /api/users/{id}</code> - 更新用户</li>
<li><code>DELETE /api/users/{id}</code> - 删除用户</li>
</ul>
</div>
<h3>Controller 代码示例</h3>
<pre><code>@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public List&lt;User&gt; getAllUsers() { ... }
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) { ... }
@PostMapping
public User createUser(@RequestBody User user) { ... }
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) { ... }
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) { ... }
}</code></pre>
</div>
<div class="card">
<h2>🔧 Spring 注解说明</h2>
<table>
<tr><th>注解</th><th>说明</th></tr>
<tr><td><code>@RestController</code></td><td>= @Controller + @ResponseBody</td></tr>
<tr><td><code>@RequestMapping</code></td><td>定义路由映射</td></tr>
<tr><td><code>@GetMapping</code></td><td>GET 请求映射</td></tr>
<tr><td><code>@PostMapping</code></td><td>POST 请求映射</td></tr>
<tr><td><code>@PathVariable</code></td><td>获取路径变量</td></tr>
<tr><td><code>@RequestBody</code></td><td>获取请求体 JSON</td></tr>
<tr><td><code>@RequestParam</code></td><td>获取查询参数</td></tr>
</table>
</div>
<p><a href="/">← 返回学习中心</a></p>
<!-- 添加/编辑用户模态框 -->
<div class="modal" id="userModal">
<div class="modal-content">
<div class="modal-header">
<h3 id="modalTitle">添加用户</h3>
<button class="close-btn" onclick="closeModal()">&times;</button>
<div class="page">
<section class="hero">
<div class="card hero-main">
<span class="eyebrow">Spring Boot demo</span>
<h1>User management that feels production-ready.</h1>
<p>This page now uses backend stats, keyword search, and clear API error handling instead of a static CRUD example.</p>
<div class="hero-actions">
<button class="btn btn-primary" onclick="openCreateModal()">Create user</button>
<button class="btn btn-secondary" onclick="refreshDashboard()">Refresh</button>
<button class="btn btn-secondary" onclick="window.location.href='/'">Back home</button>
</div>
<form id="userForm">
<input type="hidden" id="userId">
<div class="form-group">
<label>姓名</label>
<input type="text" id="userName" required>
</div>
<div class="card hero-side">
<h3>Highlights</h3>
<p>Duplicate emails return a `409`. Validation errors are displayed inline. Search matches both names and emails.</p>
</div>
</section>
<section class="stats">
<div class="card stat"><small>Total users</small><strong id="totalUsers">0</strong></div>
<div class="card stat"><small>Adults</small><strong id="adultUsers">0</strong></div>
<div class="card stat"><small>Under 30</small><strong id="youngUsers">0</strong></div>
<div class="card stat"><small>Average age</small><strong id="averageAge">0.0</strong></div>
</section>
<section class="workspace">
<div class="card table-card">
<div class="section-head">
<div>
<h2>User directory</h2>
<p>Search results stay in sync with the API.</p>
</div>
<div class="form-group">
<label>邮箱</label>
<input type="email" id="userEmail" required>
<span class="pill" id="resultCount">0 users</span>
</div>
<div id="tableArea"></div>
</div>
<div class="card tool-card">
<div class="section-head">
<div>
<h2>Search</h2>
<p>Use a keyword to match names or emails.</p>
</div>
<div class="form-group">
<label>年龄</label>
<input type="number" id="userAge" required>
</div>
<div class="btn-group">
<button type="submit" class="btn btn-primary">保存</button>
<button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
</div>
<form onsubmit="searchUsers(event)">
<label>
Keyword
<input id="searchInput" type="text" placeholder="Try: alice or example.com">
</label>
<div class="toolbar" style="margin-top:14px;">
<button class="btn btn-primary" type="submit">Search</button>
<button class="btn btn-secondary" type="button" onclick="clearSearch()">Clear</button>
</div>
</form>
<p>The frontend now explains server-side validation and duplicate email errors instead of silently failing.</p>
<div class="status" id="pageStatus"></div>
</div>
</section>
</div>
<div class="modal" id="userModal">
<div class="card modal-card">
<div class="section-head">
<div>
<h2 id="modalTitle">Create user</h2>
<p id="modalSubtitle">Add a new user to the in-memory store.</p>
</div>
<button class="close" onclick="closeModal()" aria-label="Close">&times;</button>
</div>
<form id="userForm">
<input type="hidden" id="userId">
<label>Name<input id="userName" maxlength="40" required></label>
<label>Email<input id="userEmail" type="email" maxlength="80" required></label>
<label>Age<input id="userAge" type="number" min="1" max="120" required></label>
<div class="status" id="formStatus"></div>
<div class="modal-actions">
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-secondary" type="button" onclick="closeModal()">Cancel</button>
</div>
</form>
</div>
<script>
// 加载用户列表
async function loadUsers() {
const res = await fetch('/api/users');
const users = await res.json();
const tbody = document.querySelector('#userTable tbody');
tbody.innerHTML = users.map(u => `
<tr>
<td>${u.id}</td>
<td>${u.name}</td>
<td>${u.email}</td>
<td>${u.age}</td>
<td>
<button class="btn btn-primary" onclick="editUser(${u.id}, '${u.name}', '${u.email}', ${u.age})">编辑</button>
<button class="btn btn-danger" onclick="deleteUser(${u.id})">删除</button>
</td>
</tr>
`).join('');
</div>
<script>
const state = { users: [] };
async function request(url, options) {
const response = await fetch(url, options);
const payload = await response.json();
if (!response.ok || payload.code !== 0) {
const error = new Error(payload.message || 'Request failed');
error.details = payload.data;
throw error;
}
// 打开模态框
function openModal() {
document.getElementById('userModal').classList.add('active');
document.getElementById('modalTitle').textContent = '添加用户';
document.getElementById('userForm').reset();
document.getElementById('userId').value = '';
return payload;
}
function setStatus(id, message, type = '') {
const el = document.getElementById(id);
el.textContent = message;
el.className = type ? `status ${type}` : 'status';
}
function renderStats(stats) {
document.getElementById('totalUsers').textContent = stats.totalUsers;
document.getElementById('adultUsers').textContent = stats.adults;
document.getElementById('youngUsers').textContent = stats.underThirty;
document.getElementById('averageAge').textContent = Number(stats.averageAge).toFixed(1);
}
function renderTable() {
const area = document.getElementById('tableArea');
document.getElementById('resultCount').textContent = `${state.users.length} users`;
if (!state.users.length) {
area.innerHTML = '<div class="empty">No users matched the current query.</div>';
return;
}
// 关闭模态框
function closeModal() {
document.getElementById('userModal').classList.remove('active');
area.innerHTML = `
<table>
<thead>
<tr><th>ID</th><th>Name</th><th>Email</th><th>Age</th><th>Segment</th><th>Actions</th></tr>
</thead>
<tbody>
${state.users.map((user) => `
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
<td>${user.age}</td>
<td><span class="segment">${user.age >= 18 ? 'Adult' : 'Minor'}</span></td>
<td>
<button class="btn btn-secondary" onclick="openEditModal(${user.id})">Edit</button>
<button class="btn btn-danger" onclick="removeUser(${user.id})">Delete</button>
</td>
</tr>
`).join('')}
</tbody>
</table>
`;
}
function openCreateModal() {
document.getElementById('userForm').reset();
document.getElementById('userId').value = '';
document.getElementById('modalTitle').textContent = 'Create user';
document.getElementById('modalSubtitle').textContent = 'Add a new user to the in-memory store.';
setStatus('formStatus', '');
document.getElementById('userModal').classList.add('active');
}
function openEditModal(id) {
const user = state.users.find((item) => item.id === id);
if (!user) return;
document.getElementById('userId').value = user.id;
document.getElementById('userName').value = user.name;
document.getElementById('userEmail').value = user.email;
document.getElementById('userAge').value = user.age;
document.getElementById('modalTitle').textContent = 'Edit user';
document.getElementById('modalSubtitle').textContent = 'Update the user and keep the email unique.';
setStatus('formStatus', '');
document.getElementById('userModal').classList.add('active');
}
function closeModal() {
document.getElementById('userModal').classList.remove('active');
}
async function refreshDashboard(message = 'Dashboard updated.', type = 'success') {
try {
const [usersPayload, statsPayload] = await Promise.all([
request('/api/users'),
request('/api/users/stats')
]);
state.users = usersPayload.data;
renderStats(statsPayload.data);
renderTable();
setStatus('pageStatus', message, type);
} catch (error) {
setStatus('pageStatus', error.message, 'error');
}
// 编辑用户
function editUser(id, name, email, age) {
document.getElementById('userModal').classList.add('active');
document.getElementById('modalTitle').textContent = '编辑用户';
document.getElementById('userId').value = id;
document.getElementById('userName').value = name;
document.getElementById('userEmail').value = email;
document.getElementById('userAge').value = age;
}
async function searchUsers(event) {
event.preventDefault();
const keyword = document.getElementById('searchInput').value.trim();
try {
if (!keyword) {
await refreshDashboard('Showing all users.', 'success');
return;
}
const payload = await request(`/api/users/search?keyword=${encodeURIComponent(keyword)}`);
state.users = payload.data;
renderTable();
setStatus('pageStatus', `Search completed for "${keyword}".`, 'success');
} catch (error) {
setStatus('pageStatus', error.message, 'error');
}
// 保存用户
document.getElementById('userForm').addEventListener('submit', async (e) => {
e.preventDefault();
const id = document.getElementById('userId').value;
const user = {
name: document.getElementById('userName').value,
email: document.getElementById('userEmail').value,
age: parseInt(document.getElementById('userAge').value)
};
}
async function clearSearch() {
document.getElementById('searchInput').value = '';
await refreshDashboard('Showing all users.', 'success');
}
async function removeUser(id) {
if (!confirm(`Delete user #${id}?`)) return;
try {
await request(`/api/users/${id}`, { method: 'DELETE' });
await refreshDashboard('User deleted successfully.', 'success');
} catch (error) {
setStatus('pageStatus', error.message, 'error');
}
}
document.getElementById('userForm').addEventListener('submit', async (event) => {
event.preventDefault();
const id = document.getElementById('userId').value;
const payload = {
name: document.getElementById('userName').value,
email: document.getElementById('userEmail').value,
age: Number(document.getElementById('userAge').value)
};
try {
if (id) {
await fetch(`/api/users/${id}`, {
await request(`/api/users/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...user, id: parseInt(id) })
body: JSON.stringify(payload)
});
closeModal();
await refreshDashboard('User updated successfully.', 'success');
} else {
await fetch('/api/users', {
await request('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user)
body: JSON.stringify(payload)
});
closeModal();
await refreshDashboard('User created successfully.', 'success');
}
closeModal();
loadUsers();
});
// 删除用户
async function deleteUser(id) {
if (confirm('确定删除此用户?')) {
await fetch(`/api/users/${id}`, { method: 'DELETE' });
loadUsers();
} catch (error) {
if (error.details && typeof error.details === 'object') {
const firstIssue = Object.values(error.details)[0];
setStatus('formStatus', String(firstIssue), 'error');
} else {
setStatus('formStatus', error.message, 'error');
}
}
// 初始化
loadUsers();
</script>
});
refreshDashboard('Latest users loaded.', 'success');
</script>
</body>
</html>
</html>

View 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"));
}
}

View File

@@ -0,0 +1,91 @@
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.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 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": "Demo User",
"email": "demo-user@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("Demo User"));
}
@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));
}
@Test
void shouldRejectDuplicateEmail() throws Exception {
String json = """
{
"name": "Another User",
"email": "alice@example.com",
"age": 29
}
""";
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isConflict())
.andExpect(jsonPath("$.code").value(409));
}
@Test
void shouldExposeUserStats() throws Exception {
mockMvc.perform(get("/api/users/stats"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.totalUsers").isNumber())
.andExpect(jsonPath("$.data.adults").isNumber())
.andExpect(jsonPath("$.data.averageAge").isNumber());
}
}

View File

@@ -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

Binary file not shown.

View File

@@ -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>

View File

@@ -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>

View File

@@ -68,6 +68,10 @@
<h4>📡 事件机制</h4>
<p>发布/订阅模式、解耦业务逻辑</p>
</a>
<a href="/learn" class="feature-item">
<h4>🔐 鉴权演示(学习用)</h4>
<p>最小 JWT 流程:登录、携带 Token、访问受保护接口</p>
</a>
</div>
</div>

View File

@@ -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.

View File

@@ -1,3 +0,0 @@
artifactId=demo
groupId=com.example
version=0.0.1-SNAPSHOT

View File

@@ -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

View File

@@ -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

View File

@@ -0,0 +1,2 @@
com/example/demo/controller/UserControllerTest.class
com/example/demo/controller/AuthFlowTest.class

View File

@@ -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

View File

@@ -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

View File

@@ -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