複雜報表導出、大數據匯入、視頻轉碼等**長時間運行任務**若同步阻塞 HTTP 請求:
┌─────────┐ 1. POST /startTask ┌──────────────┐
│ Browser │ ──────────────────────────→ │ Controller │
└─────────┘ │ (啟動異步線程) │
▲ └──────┬───────┘
│ │
│ 3. 定時 GET /progress?id=xxx │ 2. 返回 taskId
│ ◀──────────────────────────────────────┘
│ │
│ 4. JSON {percent: 45, status: RUNNING}│
│ ◀──────────────────────────────────────┘
│ (重複 3-4 直到 100%)
│
│ 5. 完成 → 重導向 /result.jsp 或直接顯示結果
▼
public class TaskBean implements Runnable, Serializable {
private static final long serialVersionUID = 1L;
private volatile int progress = 0; // 0-100
private volatile boolean running = false;
private volatile boolean completed = false;
private volatile boolean cancelled = false;
private Object result; // 任務完成後的結果物件
private final Object lock = new Object();
// 供 JSP/Controller 讀取
public int getProgress() { return progress; }
public boolean isRunning() { return running; }
public boolean isCompleted() { return completed; }
public boolean isCancelled() { return cancelled; }
public Object getResult() { return result; }
// 任務邏輯
@Override
public void run() {
synchronized (lock) { running = true; }
try {
for (int i = 1; i <= 100; i++) {
synchronized (lock) {
if (cancelled) return;
progress = i;
}
doHeavyWork(i); // 真實業務:SQL、XML 解析、外部 API 呼叫...
Thread.sleep(100); // 模擬耗時
}
synchronized (lock) {
completed = true;
result = "任務完成,總計: " + computeResult();
}
} catch (Exception e) {
// 記錄錯誤,標記失敗
} finally {
synchronized (lock) { running = false; }
}
}
public void cancel() { synchronized (lock) { cancelled = true; } }
private void doHeavyWork(int step) { /* 實際業務 */ }
private Object computeResult() { return 5050; }
}
@WebServlet("/task/*")
public class TaskController extends HttpServlet {
private static final Map<String, TaskBean> TASK_REGISTRY = new ConcurrentHashMap<>();
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String action = req.getPathInfo(); // /start, /progress, /cancel
if ("/start".equals(action)) {
TaskBean task = new TaskBean();
String taskId = UUID.randomUUID().toString();
TASK_REGISTRY.put(taskId, task);
new Thread(task).start(); // 或提交給 ThreadPoolExecutor
resp.setContentType("application/json");
resp.getWriter().write("{\"taskId\":\"" + taskId + "\"}");
} else if ("/progress".equals(action)) {
String taskId = req.getParameter("taskId");
TaskBean task = TASK_REGISTRY.get(taskId);
if (task == null) { resp.sendError(404); return; }
resp.setContentType("application/json");
resp.getWriter().write(String.format(
"{\"progress\":%d,\"running\":%b,\"completed\":%b,\"cancelled\":%b}",
task.getProgress(), task.isRunning(), task.isCompleted(), task.isCancelled()));
} else if ("/cancel".equals(action)) {
String taskId = req.getParameter("taskId");
TaskBean task = TASK_REGISTRY.get(taskId);
if (task != null) task.cancel();
resp.getWriter().write("{\"ok\":true}");
}
}
}
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>長任務進度演示</title>
<style>
#progressBar { width: 300px; height: 20px; border: 1px solid #ccc; border-radius: 10px; overflow: hidden; }
#progressFill { height: 100%; background: #4caf50; width: 0%; transition: width 0.3s; text-align: center; color: white; line-height: 20px; }
.hidden { display: none; }
</style>
</head>
<body>
<h2>資料匯入任務</h2>
<button id="btnStart" onclick="startTask()">開始任務</button>
<button id="btnCancel" class="hidden" onclick="cancelTask()">取消</button>
<div id="progressBar" class="hidden"><div id="progressFill">0%</div></div>
<p id="status"></p>
<script>
let taskId = null, timer = null;
function startTask() {
document.getElementById('btnStart').classList.add('hidden');
document.getElementById('btnCancel').classList.remove('hidden');
document.getElementById('progressBar').classList.remove('hidden');
document.getElementById('status').textContent = '任務啟動中...';
fetch('/task/start', {method: 'POST'})
.then(r => r.json())
.then(data => { taskId = data.taskId; pollProgress(); });
}
function pollProgress() {
fetch('/task/progress?taskId=' + taskId)
.then(r => r.json())
.then(data => {
document.getElementById('progressFill').style.width = data.progress + '%';
document.getElementById('progressFill').textContent = data.progress + '%';
document.getElementById('status').textContent = data.running ? '處理中...' : (data.completed ? '完成!' : data.cancelled ? '已取消' : '異常');
if (data.running) {
timer = setTimeout(pollProgress, 1000); // 1秒輪詢
} else {
clearTimeout(timer);
if (data.completed) {
// 可選:重導向結果頁或顯示結果
window.location.href = '/task/result?taskId=' + taskId;
}
}
});
}
function cancelTask() {
fetch('/task/cancel?taskId=' + taskId, {method: 'POST'});
clearTimeout(timer);
}
</script>
</body>
</html>