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); } }