Cookie记住登陆用户名
2019-05-22 / JAVA / 934 次围观 / 0 次吐槽 /public class Demo6Servlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); //获取数据 String username = req.getParameter("username"); String password = req.getParameter("password"); String remember = req.getParameter("remember"); //简单判断登陆 String success = ("admin".equals(username) && "123".equals(password)) ? "登陆成功" : "登陆失败"; resp.getWriter().write(success); //把remember和username存在cookie中 if("true".equals(remember) && "登陆成功".equals(success)) { Cookie cookie1 = new Cookie("remember",remember); cookie1.setMaxAge(60*60); resp.addCookie(cookie1); Cookie cookie2 = new Cookie("username",username); cookie2.setMaxAge(60*60); resp.addCookie(cookie2); }else { Cookie[] cookies = req.getCookies(); if(cookies != null) { for(Cookie cookie : cookies) { cookie.setMaxAge(0);//删除cookie resp.addCookie(cookie); } } } } }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>login</title> <script type="text/javascript"> var cookies = document.cookie.split(';'); //通过key获取cookie的值 function getCK(mkey) { for(var i = 0;i<cookies.length;i++){ var kv = cookies[i].split('='); //key有可能空字符串 if( kv[0].trim() == mkey){ return kv[1].trim(); } } return ''; } window.onload = function(){ var remember = getCK('remember'); var username = getCK('username'); console.log(remember + "---"); console.log(username); if(remember == 'true'){//记住密码 //console.log('记住密码'); var userNameInput = document.getElementById('username'); userNameInput.value = username; var rememberInput = document.getElementById('remember'); rememberInput. checked="checked"; } } </script> </head> <body> <form action="/day6/Demo6Servlet" method="post"> <table> <tr> <td>用户名:</td> <td><input id="username" type="text" name="username"></td> </tr> <tr> <td>密码:</td> <td><input id="password" type="password" name="password"></td> </tr> <tr> <td colspan="2"> <input id="remember" type="checkbox" name="remember" value="true">记住用户名 </td> </tr> <tr> <td colspan="2"> <input type="submit" value="登录"> </td> </tr> </table> </form> </body> </html>
- 上一篇:Session&Cookie
- 下一篇:Cookie模拟查看书的历史记录
Powered By Cheug's Blog
Copyright Cheug Rights Reserved.