1.编写jsp页面的checkbox
2.编写servlet(登入成功的状态下存储cookie)
package stu.adam.control; import stu.adam.entity.Customer; import stu.adam.service.CustomerService; import stu.adam.service.Impl.CustomerServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(name="customerlogin",urlPatterns = "/CustomerServlet") public class CustomerServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); CustomerService customerService=new CustomerServiceImpl(); String account=request.getParameter("username"); String password=request.getParameter("password"); //获取 是否《记住密码》 选项 String remember=request.getParameter("remember"); Customer customer=new Customer(account,password); Customer tempcustomer=customerService.customerLogin(customer); if(tempcustomer!=null){ //登入成功 if("true".equals(remember)){ Cookie cookie =new Cookie(account,password); //cookie有效期 //一个月 cookie.setMaxAge(60*60*24*30); //cookie发送到浏览器 response.addCookie(cookie); } response.sendRedirect("classinfo?type=show"); }else { //登入失败 PrintWriter out=response.getWriter(); out.write("登入失败,账号或者密码错误"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
3.浏览器查看是否存储成功
4.这段代码可以验证cookie是否存在(有需要情况下可以跳过数据库验证)
/* * 如果用记住密码选项,并且cookie存在于服务端的cookies里面那么就不需要验证密码 * */ boolean flagCookie = false; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(account)) { flagCookie = true; break; } }