seesion和cookie
(1)cookie创建,使用 .
(2)简单的一个实现自动登录的功能
1.前端简单页面
login.jsp
<%
String userName = null;
String password = null;
Cookie[] cookies = request.getCookies();
for (Cookie c:cookies) {
if (c.getName().equals("userName")){
userName = c.getValue();
}
if (c.getName().equals("password")){
password = c.getValue();
}
}
if (userName!=null&&password!=null){
pageContext.setAttribute("userName",userName);
pageContext.setAttribute("password",password);
pageContext.setAttribute("remember","rem");
}
%>
<script>
$(function () {
//点击记住我按钮之后
//设置多少秒之后执行toLogin方法实现自动登录(单位ms)
setTimeout(toLogin,5000);
})
function toLogin() {
let ischecked = $("input:eq(2)").is(":checked");
if (ischecked){
let userName = $("#us").val();
let password = $("#pw").val();
location.href="login?userName="+userName+"&password="+password;
}
}
</script>
<body>
<form action="login" method="post">
用户名:<input type="text" id="us" name="userName" value="${userName}"><br>
密 码:<input type="password" id="pw" name="password" value="${password}"><br>
自动登录 <input type="checkbox" name="remember" <c:if test="${remember=='rem'}">checked</c:if> value="rem"><br>
<input type="submit" value="登录">
</form>
</body>
2.登录成功跳转的页面
welcome.jsp
<body>
欢迎--<span style="color: red">${user}</span>--登录
</body>
3.后端接收请求,设置cookie以及 < 记住我的 > 处理
cookieServlet
@WebServlet("/login")
public class cookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userName = req.getParameter("userName");
String password = req.getParameter("password");
String remember = req.getParameter("remember");
if ("admin123".equals(userName)&&"123".equals(password)){
req.getSession().setAttribute("user",userName);
if("rem".equals(remember)){
Cookie un = new Cookie("userName",userName);
//设置存储cookie的时长(单位s)
un.setMaxAge(30);
resp.addCookie(un);
Cookie pw = new Cookie("password",password);
un.setMaxAge(30);
resp.addCookie(pw);
}else {
Cookie[] cookies = req.getCookies();
System.out.println(cookies.length);
for (Cookie c: cookies) {
if (c.getName().equals("userName")){
c.setMaxAge(0);
resp.addCookie(c);
}
if (c.getName().equals("password")){
c.setMaxAge(0);
resp.addCookie(c);
}
}
}
req.getRequestDispatcher("welcome.jsp").forward(req,resp);
}else {
resp.sendRedirect("login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}