JAVA EE之Cookie記住我
阿新 • • 發佈:2018-12-11
1:form
<form action="/show/login.do" method="post"> <div class="field-wrap"> <label>Name</label> <input type="text"required autocomplete="off" name="username" value="<%=username%>"/> </div> <div class="field-wrap"> <label>Password</label> <input type="password"required autocomplete="off" name="password" value="<%=password%>"/> </div> <p> <input type="checkbox" value="" name="ok" > <label>Remember Me</label> </p> <button type="submit" class="button button-block"/>Log In</button> </form>
2: servlet
//接收form傳來的記住我 String remember=req.getParameter("ok"); //建立一個cookie,存放制定值 Cookie nameCookie = new Cookie("username", username); Cookie passwordCookie = new Cookie("password", password); //設定失效時間 if (null!=remember && "ok".equals(remember)){ nameCookie.setMaxAge(7*24*60*60); passwordCookie.setMaxAge(7*24*60*60); }else { nameCookie.setMaxAge(0); passwordCookie.setMaxAge(0); } //將Cookie存放到response中 resp.addCookie(nameCookie); resp.addCookie(passwordCookie);
3:jsp
<% String username = ""; String password = ""; Cookie [] cookies = request.getCookies(); for (int i = 0; i <cookies.length ; i++) { if ("username".equals(cookies[i].getName())){ username=cookies[i].getValue(); }else if("password".equals(cookies[i].getName())){ password=cookies[i].getValue(); } } %>
設定form中的value="<%=username%" value="<%=password%>"