登录页面的下次自动登录
1.jsp页面
1 <% 2 String name =""; 3 String pwd=""; 4 String checked=""; 5 Cookie[] cookies = request.getCookies(); 6 if(cookies != null && cookies.length >0){ 7 for(Cookie cookie : cookies){ 8 if("name".equals(cookie.getName())){ 9 name=cookie.getValue(); 10 checked="checked"; 11 } 12 if("pwd".equals(cookie.getName())){ 13 pwd = cookie.getValue(); 14 } 15 } 16 } 17 18 %> 19 20 21 <input name="rem_u" type="checkbox" id="rem_u" value="rem_u" <%=checked %> /> 22 <span for="rem_u">下次自动登录</span>
2.后台代码
1 // 把用户名,密码添加到cookie 2 Cookie nameCookie = new Cookie("name",name); 3 Cookie pwdCookie = new Cookie("pwd",pwd); 4 nameCookie.setPath(request.getContextPath()+"/");//设置Cookie的保存路径 5 pwdCookie.setPath(request.getContextPath()+"/"); 6 7 String rem_u =request.getParameter("rem_u");//下次自动登录的checkbox 8 if(rem_u == null){ 9 nameCookie.setMaxAge(0);//删除Cookie 10 pwdCookie.setMaxAge(0); 11 }else{ 12 nameCookie.setMaxAge(7*24*60*60); 13 pwdCookie.setMaxAge(7*24*60*60); 14 } 15 response.addCookie(nameCookie);//写入Cookie 16 response.addCookie(pwdCookie);