使用Cookie保存用户和密码然后自动登录
login.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>登陆</title> 6 </head> 7 <body> 8 <form method="post" action="Login"> 9 <input type="text" name="user" id="user"> 10 <input type="password" name="pwd" id="pwd"> 11 <input type="submit" name="登陆" id="bt"> 12 </form> 13 <script> 14 var cookie=document.cookie; 15 console.log(cookie) 16 var u=new Array(); 17 var user=document.getElementById("user"); 18 var pwd=document.getElementById("pwd"); 19 var cks=cookie.split(";"); 20 for (var i=0;i<cks.length;i++){ 21 var kv=cks[i].split("="); 22 //alert(kv[0]); 23 u=kv[1]; 24 // alert(kv[1]); 25 if(kv[0].trim()=="user") user.value=kv[1];//去掉前后空格.trim() 26 if(kv[0].trim()=="password") pwd.value=kv[1];//第二次登陆直接把密码填入框中 27 if(user.value!=""&&pwd.value!=""){ 28 document.getElementById("bt").click();//模拟点击,直接登陆 29 } 30 for (var j=0;j<kv.length;j++){ 31 console.log(kv[1]) 32 } 33 } 34 console.log(u) 35 </script> 36 </body> 37 </html>
Servlet的Login.java
1 package control; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.*; 6 import java.io.IOException; 7 import java.io.PrintWriter; 8 9 @WebServlet("/Login") 10 public class Login extends HttpServlet { 11 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 12 request.setCharacterEncoding("utf-8"); 13 response.setContentType("text/html;charset=utf-8"); 14 Cookie[] cookie=request.getCookies(); 15 for (Cookie c:cookie){ 16 System.out.println(c.getName()+"\t"+c.getValue()); 17 } 18 HttpSession session=request.getSession(); 19 String user=request.getParameter("user"); 20 String pwd=request.getParameter("pwd"); 21 PrintWriter out =response.getWriter(); 22 if (user.equals("admin")&& pwd.equals("123")){ 23 Cookie u=new Cookie("user","admin"); 24 Cookie p=new Cookie("password","123"); 25 u.setMaxAge(60*60*24);//设置Cookie生存时长60*60*24一天 26 p.setMaxAge(60*60*24); 27 response.addCookie(u); 28 response.addCookie(p); 29 session.setAttribute("isLogin",true); 30 out.write("成功"); 31 }else out.write("失败"); 32 } 33 34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 36 } 37 }