feat: add guided learning cockpit

This commit is contained in:
Codex
2026-03-19 13:53:49 +08:00
parent 00306082fb
commit 09574c3400
8 changed files with 967 additions and 800 deletions

View File

@@ -1,222 +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; }
.lab { background:#fff7e6; border-left:4px solid #fa8c16; padding:15px; border-radius:8px; margin:15px 0; }
.lab h4 { color:#ad6800; margin-bottom:8px; }
: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="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>
<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>
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>
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>