1. 程式人生 > >案例33-用戶退出功能

案例33-用戶退出功能

context eat pos ttr res blog gpo direct rec

1 LogoutServlet代碼

package www.test.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
javax.servlet.http.HttpSession; public class LogoutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); //退出的實質就是從session中將user刪除 session.removeAttribute("user");
// 將存儲在客戶端的cookie刪除 Cookie cookie_username = new Cookie("cookie_username", ""); Cookie cookie_password = new Cookie("cookie_password", ""); // 設置 cookie 的持久化時間 cookie_username.setMaxAge(0); cookie_password.setMaxAge(0); // 設置 cookie 的攜帶路徑 cookie_username.setPath(request.getContextPath()); cookie_password.setPath(request.getContextPath());
// 發送 cookie response.addCookie(cookie_username); response.addCookie(cookie_password); //轉發到登錄頁面 response.sendRedirect(request.getContextPath()+"/login.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

案例33-用戶退出功能