cookie获取上次访问时间
程序员文章站
2024-03-20 13:51:16
...
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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 org.apache.commons.lang3.StringUtils;
/**
* 使用cookie记录上次登录时间
* @author hongxiaotong
* @date 2020年5月1日 下午3:55:12
*/
@WebServlet("/CookieDemo")
public class CookieDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String COOKIE_KEY_LASTTIME = "cookie_key_lasttime";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf8");
String lastTimeString = null;
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for (Cookie cookie : cookies) {
if(COOKIE_KEY_LASTTIME.equals(cookie.getName())) {
lastTimeString = cookie.getValue();
break;
}
}
}
if(StringUtils.isEmpty(lastTimeString)) {
response.getWriter().write("您是首次访问");
}else {
response.getWriter().write("您上次访问时间为:"+ lastTimeString);
}
String dateFormat = new SimpleDateFormat("yyyyMMdd-HH:mm:ss").format(new Date());
Cookie cookie = new Cookie(COOKIE_KEY_LASTTIME, dateFormat);
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
}
}
上一篇: Cookie案例--上次访问时间
下一篇: 顺序表接口的实现