首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java Web 實現可自定義樣式的登出確認對話框

     編輯:程式設計綜合問答

需求

JSP 頁面點擊「登出」按鈕,彈出可自定義樣式(如淘寶風格)的確認對話框,確認後才執行登出邏輯。

方案一:原生 JS + CSS(零依賴,最輕量)

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

方案二:引入成熟 UI 庫(功能豐富、樣式生態完善)

  • SweetAlert2:`Swal.fire({title:'確定登出?', showCancelButton:true, confirmButtonText:'確定'}).then(r=>{if(r.isConfirmed) logout();})`
  • Layer (layui):國產輕量彈層,語法簡單,中文文檔友好。
  • Bootstrap Modal:若專案已用 Bootstrap,直接用 `

方案三:jQuery UI Dialog / DialogPolyfill(較舊專案常見)

若專案已引入 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 或原生 `

` 元素(現代瀏覽器支援);舊專案沿用現有 UI 庫組件。核心流程:前端攔截點擊 → 彈框 → 確認後導向/提交登出 Servlet → 後端銷毀 Session → 導回登入頁。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved