Java web cookie
1 import javax.servlet.ServletException; 2 import javax.servlet.http.Cookie; 3 import javax.servlet.http.HttpServlet; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 import java.io.IOException; 7 import java.io.PrintWriter; 8 import java.util.Date; 9 10 public class CookieDemo01 extends HttpServlet { 11 @Override 12 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 13 //解决中文乱码 14 req.setCharacterEncoding("utf-8"); 15 resp.setCharacterEncoding("utf-8"); 16 17 PrintWriter out = resp.getWriter(); 18 19 Cookie[] cookies = req.getCookies(); 20 21 if (cookies != null){ 22 out.write("您上次访问的时间是:"); 23 for (int i = 0; i < cookies.length; i++) { 24 Cookie cookie = cookies[i]; 25 if (cookie.getName().equals("LastLoginTime")){ 26 long lastLoginTime = Long.parseLong(cookie.getValue()); 27 Date date = new Date(lastLoginTime); 28 out.write(date.toLocaleString()); 29 } 30 } 31 }else { 32 out.write("这是您第一次访问本站"); 33 } 34 35 Cookie cookie = new Cookie("LastLoginTime", System.currentTimeMillis()+""); 36 resp.addCookie(cookie); 37 } 38 39 @Override 40 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 41 doGet(req, resp); 42 } 43 }