servlet和Cookie实现记住账号密码功能
1.实现jQuery异步登录
https://www.cnblogs.com/YorkZhangYang/p/12539726.html
2.jQuery获取checkbox选项组的值
https://www.cnblogs.com/YorkZhangYang/p/12587155.html
2.1在1和2的基础上,Login.jsp页面按钮提交事件submitBtn.onclick=function(){}中增加以下代码
//获取checkbox是否已选中 let chkbox = $("input[name='remember']:checkbox").prop("checked");
2.2在$.ajax({})方法data属性中做以下改变,将checkbox是否选中状态的true和false值提交到servlet
data:{username:strName,password:strPwd,validateCode:strCode,chkbox:chkbox}
3.在servlet类中做如下改变
(1)获取前端传过来的checkbox是否选中的状态值。
String chkbox = request.getParameter("chkbox");
如果用户名,密码,验证码都正确(登录成功),在将用户名,密码存入session对象的代码后增加以下代码:
(2)验证获取checkbox的checked状态值等于true(已勾选“记住我”选项),则创建cookie对象,并将用户名和密码存入cookie对象,并保存到客户端。
(3)若获取checkbox的checked状态值等于false(未勾选“记住我”选项),则遍历客户端的cookie对象,找到名为用户名和密码的cookie对象,将时效赋值为0(相当于删除已经保存的用户名和密码)。
//将用户名和密码存储到cookie对象 if(chkbox!=null&&!chkbox.isEmpty()&&chkbox.equals("true")) { Cookie cookie1 = new Cookie("username", name); Cookie cookie2 = new Cookie("password", pwd); //设置cookie的时效 cookie1.setMaxAge(60*60*24*7); cookie2.setMaxAge(60*60*24*7); //保存到客户端 response.addCookie(cookie1); response.addCookie(cookie2); } else //设置原来保存的cookie时效为0(相当于删除Cookie) { Cookie [] cookies = request.getCookies(); //寻找是否已经存在之前保存过的cookie for (Cookie cookie:cookies) { if (cookie.getName().equals("username")) { cookie.setMaxAge(0); response.addCookie(cookie); } if (cookie.getName().equals("password")) { cookie.setMaxAge(0); response.addCookie(cookie); } } }
4.Login.jsp页面提取保存到客户端的cookie对象,将用户名和密码作为input文本表单的默认value值显示。
<% String username = ""; String password = ""; Cookie[] cookies = request.getCookies(); if(cookies!=null&&cookies.length>0) { for(Cookie c:cookies) { if(c.getName().equals("username")) { username = c.getValue(); } if(c.getName().equals("password")) { password = c.getValue(); } } } out.print(username); %>
5.完整代码
Login.jsp
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录界面</title> <!-- Bootstrap --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="js/jquery-1.11.1.min.js"></script> <style> .bg{ height: 600px; background-image:url(images/bg.jpg); background-size:cover; } .form{ padding: 40px; margin-top: 175px; background: rgba(255,255,255,0.2); } .footer{ height: 60px; padding-top:20px; font-size: 14px; font-weight: bold; text-align: center; } </style> </head> <body> <% String username = ""; String password = ""; Cookie[] cookies = request.getCookies(); if(cookies!=null&&cookies.length>0) { for(Cookie c:cookies) { if(c.getName().equals("username")) { username = c.getValue(); } if(c.getName().equals("password")) { password = c.getValue(); } } } out.print(username); %> <div class="page-header"> <h1>XXXX信息系统登录界面</h1> </div> <div class="container-fluid"> <div class="row bg"> <div class="col-md-offset-6 col-md-4 col-sm-offset-3 col-sm-7 col-xs-offset-2 col-xs-8 col-lg-offset-6 col-lg-3 form"> <form class="form-horizontal" id="loginForm" action="${pageContext.request.contextPath}/LoginServlet" method="post"> <div class="form-group"> <label for="username" class="col-sm-4 control-label">用户名</label> <div class="col-sm-8"> <input type="text" class="form-control" id="username" name="username" value="<%=username %>" placeholder="请输入用户名" onblur="validateusername();"> </div> </div> <div class="form-group"> <label for="password" class="col-sm-4 control-label">密码</label> <div class="col-sm-8"> <input type="password" class="form-control" id="password" name="password" value="<%=password %>" placeholder="请输入密码" > </div> </div> <div class="form-group"> <label for="validateCode" class="col-sm-4 control-label">验证码</label> <div class="col-sm-4"> <input type="text" class="form-control" id="validateCode" name="validateCode" placeholder="请输入验证码"> </div> <div class="col-sm-4"> <img id="verifyCode" src="${pageContext.request.contextPath}/VerifyCodeImg" alt="Loading" width="75px" height="35px" onclick="changeCode()"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox" name="remember" value="selected">记住我 </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="button" id="submitBtn" class="btn btn-success" style="width: 50%;" >登录</button> </div> </div> </form> <span style="color: red;" id="tip"></span> </div> </div> <div class="footer"> <p>©版权所有:XXXXX学院南宁市仙葫大道XXX号</p> <p>邮编:530001联系邮箱:xxxxxxx@163.com</p> </div> </div> <script type="text/javascript"> function changeCode() { var codeImg=document.getElementById("verifyCode"); //这里URL后追加随机数,使程序每次访问的都是不同的资源,防止浏览器缓存,即产生不同的验证码 codeImg.src="/LoginTest/VerifyCodeImg?d="+Math.random(); } //首先获取表单的Input对象 let username = document.getElementById("username"); let password = document.getElementById("password"); let validateCode = document.getElementById("validateCode"); let span = document.getElementById("tip"); let submitBtn = document.getElementById("submitBtn"); console.log(validateCode); password.onblur = function() { validatepassword(); } validateCode.onblur = function() { validatecode(); } function validateusername() { let value = username.value; if(!value) { span.innerHTML="用户名不能为空"; return false; } else if(value.length<2||value.length>11) { span.innerHTML="用户名的长度2-12位"; return false; } else{ span.innerHTML=""; return true; } } function validatepassword() { let value = password.value; if(!value) { span.innerHTML="密码不能为空"; return false; } else if(value.length<2||value.length>11) { span.innerHTML="密码的长度2-12位"; return false; } else{ span.innerHTML=""; return true; } } function validatecode() { let value = validateCode.value; if(!value) { span.innerHTML="验证码不能为空"; return false; } else{ span.innerHTML=""; return true; } } submitBtn.onclick=function(){ if(validateusername()&&validatepassword()&&validatecode()) { //document.getElementById("loginForm").submit(); let strName = username.value; let strPwd = $("#password").val(); let strCode = validateCode.value; //获取checkbox是否已选中 let chkbox = $("input[name='remember']:checkbox").prop("checked"); console.log(strName); console.log(strPwd); console.log(strCode); $.ajax({ url:"${pageContext.request.contextPath}/LoginServlet",//LoginTest/LoginServlet type:"post", dataType:"text", data:{username:strName,password:strPwd,validateCode:strCode,chkbox:chkbox}, beforeSend:function(){ $("#tip").html("登录中......."); }, success:function(data){ //是从servlet传回来的 if(data=="ok") { $("#tip").html("登录成功!"); window.location.href="adminindex.jsp"; } else if(data=="namepwdstr") { $("#tip").html("用户名或密码有错!"); } else if(data=="codestr") { $("#tip").html("验证码有错!"); } }, error:function() { $("#tip").html("登录失败!"); } }); } else { span.innerHTML="表单为空或不符合要求"; return false; } } </script> <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) --> <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script> <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script> </body> </html>
LoginServlet.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package servlet; import java.io.IOException; import java.io.PrintWriter; 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 javax.websocket.Session; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.设置获取表单字符集 request.setCharacterEncoding("utf-8"); //2.设置响应的类型 //response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("username"); String pwd = request.getParameter("password"); String code = request.getParameter("validateCode"); String chkbox = request.getParameter("chkbox"); String str=""; PrintWriter out = response.getWriter(); if(name.equals("")||name==null||pwd.equals("")||pwd==null||code.equals("")||code==null) { out.print("表单不能为空"); return; } //将前端页面获取的验证码转换为小写 String codelower = code.toLowerCase(); boolean IsName =name.equals("admin"); boolean IsPwd = pwd.equals("123"); boolean IsCode = codelower.equals(request.getSession().getAttribute("code").toString().toLowerCase()); if(IsName&&IsPwd&&IsCode) { request.getSession().setAttribute("username", name); request.getSession().setAttribute("password", pwd); //response.sendRedirect("adminindex.jsp"); //将用户名和密码存储到cookie对象 if(chkbox!=null&&!chkbox.isEmpty()&&chkbox.equals("true")) { Cookie cookie1 = new Cookie("username", name); Cookie cookie2 = new Cookie("password", pwd); //设置cookie的时效 cookie1.setMaxAge(60*60*24*7); cookie2.setMaxAge(60*60*24*7); //保存到客户端 response.addCookie(cookie1); response.addCookie(cookie2); } else //设置原来保存的cookie时效为0(相当于删除Cookie) { Cookie [] cookies = request.getCookies(); //寻找是否已经存在之前保存过的cookie for (Cookie cookie:cookies) { if (cookie.getName().equals("username")) { cookie.setMaxAge(0); response.addCookie(cookie); } if (cookie.getName().equals("password")) { cookie.setMaxAge(0); response.addCookie(cookie); } } } str = "ok"; out.print(str); } else { if(!IsName||!IsPwd) { str = "namepwdstr"; out.print(str); } if(!IsCode) { str = "codestr"; out.print(str); } //response.sendRedirect("Login.jsp"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
6.演示效果
转载文章链接已标明,如有侵权请告知。文章仅作为知识记忆所用,如有错误,敬请指正。