JSP 頁面點擊「登出」按鈕,彈出可自定義樣式(如淘寶風格)的確認對話框,確認後才執行登出邏輯。
<!-- HTML -->
<button id="btnLogout">登出</button>
<div id="logoutModal" class="modal-hidden">
<div class="modal-box">
<p>確定要離開嗎?</p>
<button id="confirmLogout">確定</button>
<button id="cancelLogout">取消</button>
</div>
</div>
<style>
.modal-hidden { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.4); z-index:999; }
.modal-box { position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); background:#fff; padding:20px; border-radius:8px; text-align:center; min-width:280px; box-shadow:0 4px 12px rgba(0,0,0,0.15); }
.modal-box button { margin:0 10px; padding:6px 18px; border:none; border-radius:4px; cursor:pointer; }
#confirmLogout { background:#e74c3c; color:#fff; }
#cancelLogout { background:#95a5a6; color:#fff; }
</style>
<script>
document.getElementById('btnLogout').onclick = function() {
document.getElementById('logoutModal').style.display = 'block';
};
document.getElementById('confirmLogout').onclick = function() {
// 提交登出表單或跳轉登出 Servlet
document.getElementById('logoutForm').submit(); // 或 window.location.href = '/logout';
};
document.getElementById('cancelLogout').onclick = function() {
document.getElementById('logoutModal').style.display = 'none';
};
</script>
若專案已引入 jQuery UI,可用 `$('#dialog').dialog({modal:true, buttons:{'確定':logout, '取消':close}})`。
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session = req.getSession(false);
if (session != null) session.invalidate();
resp.sendRedirect(req.getContextPath() + "/login.jsp");
}
}
「可自定義樣式的確認框」純屬前端呈現邏輯,**不需 Java 後端參與**。推薦:新專案用 SweetAlert2 或原生 `