Cookie——获取上次来访时间
程序员文章站
2024-03-20 13:59:34
...
CookieDemo类:
package com.itheima.servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itheima.util.CookieUtil;
@SuppressWarnings("serial")
public class CookieDemo03 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "123".equals(password)) {
//获取Cookie
Cookie[] cookies = request.getCookies();
//在数组里面找出我们想要的cookie
Cookie cookie = CookieUtil.findCookie(cookies, "last");
if (cookie == null) {
Cookie c = new Cookie("last", System.currentTimeMillis()+"");
c.setMaxAge(60*60);
response.addCookie(c);
response.getWriter().write("登录成功,欢迎您 "+username);
}else {
//1.取以前的cookie
long lastVisitTime = Long.parseLong(cookie.getValue());
//2.输出到界面
response.getWriter().write("登录成功,欢迎您 "+username+",上次来访时间是"+new Date(lastVisitTime));
//3.重置登录的时间
cookie.setValue(System.currentTimeMillis()+"");
response.addCookie(cookie);
}
}else {
response.getWriter().write("登录失败");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
用到的CookieUtil类
package com.itheima.util;
import javax.servlet.http.Cookie;
public class CookieUtil {
/*
* 从一个cookie数组中找到具体我们想要的对象
*/
public static Cookie findCookie(Cookie[] cookies,String name) {
if (cookies != null) {
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
}
return null;
}
}
Cookie_login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="CookieDemo03">
账号:<input type="text" name="username"/><br>
密码:<input type="password" name="password"/><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>
xml配置
<servlet>
<servlet-name>CookieDemo03</servlet-name>
<servlet-class>com.itheima.servlet.CookieDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieDemo03</servlet-name>
<url-pattern>/CookieDemo03</url-pattern>
</servlet-mapping>
正在尝试写博客,把会的分享给你们,如有写的不好的地方,希望指点一下,谢谢!