單頁面應用(SPA)雛形:主頁面 main.jsp 左側導覽,右側容器 <div id="userlist"> 需無刷新載入 userlist.jsp 的表格資料。
main.jsp (框架頁) ├─ 左側導覽:按鈕「使用者列表」 └─ 右側容器:<div id="userlist"></div> userlist.jsp (片段頁) └─ 純 HTML 表格片段(含 JSTL forEach 迴圈),無 html/head/body 標籤
function doAjax(targetId, actionUrl) {
// targetId: 容器 ID,如 'userlist'
// actionUrl: 後端處理路徑,如 '/user/list.action'
$('#' + targetId).load(actionUrl);
}
// 導覽按鈕綁定
$('#btnUserList').click(function() {
doAjax('userlist', '/user/list.action');
});
request.setAttribute("users", list);userlist.jsp 渲染片段。.load() 自動注入容器。<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<table class="table">
<thead><tr><th>ID</th><th>姓名</th><th>Email</th></tr></thead>
<tbody>
<c:forEach items="${users}" var="u">
<tr>
<td>${u.id}</td>
<td>${u.name}</td>
<td>${u.email}</td>
</tr>
</c:forEach>
</tbody>
</table>
| 優點 | 缺點 |
|---|---|
| 前端極簡,無需手拼 HTML / JSON 解析 | 伺服器端渲染,增加伺服器負載 |
| 直接重用既有 JSP 模板,維護容易 | 難以支援複雜客戶端互動(排序、分頁需再請求) |
| 避免 iframe 載入完整頁面的效能問題 | SEO 不友善(內容非初始 HTML) |
function doAjax(targetId, actionUrl) {
var $container = $('#' + targetId);
$container.html('<div class="loading">載入中...</div>');
$container.load(actionUrl, function(response, status, xhr) {
if (status === 'error') {
$container.html('<div class="error">載入失敗:' + xhr.status + '</div>');
}
});
}