cookie的使用
cookie的使用
通过简单的登录验证,保存用户Cookie,
并在第二次访问登录时判断Cookie是否存在,从而区别新旧用户。
实验结果
Servlet doGet方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String password = request.getParameter("password"); String boxvalue = request.getParameter("boxcookie"); System.out.println(boxvalue); List<String> info = new ArrayList<String>(); if (name == null || "".equals(name)) { // 用户名输入格式问题 info.add("用户名不能为空"); System.out.println("用户名不能为空"); } /* * if (password == null || "".equals(password)) {// 密码输入格式问题 info.add("密码不能为空"); * System.out.println("密码不能为空"); } */ if (info.size() == 0) { User user = new User(); user.setName(name); user.setPassword(password); // 检查Cookie boolean isolduser = false; Cookie cookie = null; Cookie[] cookies = null; cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; if (cookie.getName().compareTo(user.getName()) == 0) { // 判断cookie是否已存在 isolduser = true; break; } } if (isolduser) {// 老用户 info.add("欢迎用户" + user.getName() + "回来!"); if (boxvalue.compareTo("zero") == 0) { // 如果有,删除cookie for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; if (cookie.getName().compareTo(user.getName()) == 0) { cookie.setMaxAge(0); response.addCookie(cookie); System.out.println("Deleted cookie " + cookie.getName() + cookie.getValue()); } } } } else {// 新用户 UserDAOProxy userDAOProxy = new UserDAOProxy(); try { if (userDAOProxy.findLogin(user)) { info.add("用户登录成功,欢迎" + user.getName() + "光临!"); if (boxvalue.compareTo("zero") != 0) { // 设置cookie Cookie cookieuser = new Cookie(user.getName(), user.getName()); cookieuser.setMaxAge(60 * 60 * 24); response.addCookie(cookieuser); System.out.println( "ADD cookie Key: " + cookieuser.getName() + "Value: " + cookieuser.getValue()); } } else { info.add("用户登录失败,错误的用户名和密码"); } } catch (Exception e) { e.printStackTrace(); } } // 对新旧用户有效 } System.out.println("USER " + name); System.out.println("PASSWD " + password); request.setAttribute("outputMessage", info);// 保存错误信息 request.getRequestDispatcher("NewFile.jsp").forward(request, response);// 跳转 }
百度云
链接: https://pan.baidu.com/s/14cp6t_CURLfYEbl_xpsSEw 提取码: edry 复制这段内容后打开百度网盘手机App,操作更方便哦