java页面
package com.yin; 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 java.io.IOException; import java.io.PrintWriter; import java.util.Date; public class CookieDemo extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); PrintWriter out =resp.getWriter(); Cookie[] cookies=req.getCookies(); if(cookies!=null){ out.write("你上次访问时间:"); for (int i = 0; i <cookies.length ; i++) { Cookie cookie=cookies[i]; if(cookie.getName().equals("lastLoginTime")){ long lastLogintime=Long.parseLong(cookie.getValue()); Date date=new Date(lastLogintime); out.write(date.toLocaleString()); }; } } else{ out.write("你这是第一次访问本站"); } Cookie cookie=new Cookie("lastLoginTime",System.currentTimeMillis()+""); cookie.setMaxAge(24*60*60); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
XML添加路径
<servlet> <servlet-name>name</servlet-name> <servlet-class>com.yin.CookieDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>name</servlet-name> <url-pattern>/cook</url-pattern> </servlet-mapping>
查看运行情况
package com.yin;标签:http,resp,req,cookie,使用,import,servlet,javax From: https://www.cnblogs.com/insoon/p/17057544.html
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
public class CookieDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out =resp.getWriter();
Cookie[] cookies=req.getCookies();
if(cookies!=null){
out.write("你上次访问时间:");
for (int i = 0; i <cookies.length ; i++) {
Cookie cookie=cookies[i];
if(cookie.getName().equals("lastLoginTime")){
long lastLogintime=Long.parseLong(cookie.getValue());
Date date=new Date(lastLogintime);
out.write(date.toLocaleString());
};
}
}
else{
out.write("你这是第一次访问本站");
}
Cookie cookie=new Cookie("lastLoginTime",System.currentTimeMillis()+"");
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}