java代码:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet("/Cookie1")
public class Cookie1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Cookie[] cookies = request.getCookies();
//条件判断
if ("zhangsan".equals(username) && "123456".equals(password)&&cookies.length==1) {
request.setAttribute("one", "第一次登录");
//对当前时间编码
String encode = URLEncoder.encode( gettime(),"utf-8");
Cookie cookie = new Cookie("ltime", encode);
cookie.setMaxAge(30);
//更新cookie
response.addCookie(cookie);
//页面跳转
request.getRequestDispatcher("/sucess.jsp").forward(request,response);
} else if ("zhangsan".equals(username) && "123456".equals(password)) {
//遍历
for (Cookie c:cookies) {
if(c.getName().equals("ltime")){
String value=c.getValue();
//解码
String decode = URLDecoder.decode(value, "utf-8");
request.setAttribute("m", "上次登录时间"+decode);
}
}
String encode = URLEncoder.encode(gettime(),"utf-8" );
Cookie cookie = new Cookie("ltime", encode);
cookie.setMaxAge(30);
//更新cookie
response.addCookie(cookie);
request.getRequestDispatcher("/sucess.jsp").forward(request,response);
}else {
request.setAttribute("msg", "用户名或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
//自定义当前时间获取方法
public String gettime(){
Date date = new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String time = dateFormat.format(date);
return time;
}
}
jsp代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/Cookie1" method="post">
账号:<input name="username" type="text"><br>
密码:<input name="password" type="password"><br>
<button type="submit">提交</button>
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录成功</h1>
${requestScope.one}
${requestScope.m}
</body>
</html>
结果截图: