Package Com.ken.cookie;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Getcookieservlet extends HttpServlet {private static final long serialversionuid = 1L;
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Obtaining data for cookies carried by the client cookie[] cookies = request.getcookies ();
Obtain the desired cookie by the cookie name for (cookie cookie:cookies) {//Get the name of the cookie String cookiename = Cookie.getname ();
if (cookiename.equals ("name")) {//Gets the value of the cookie String cookievalue = Cookie.getvalue ();
System.out.println (Cookievalue); }}} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOE
xception {doget (request, response); }
}
Operation Result:
Show user's last access time:
Package com.ken.lastAccessTime;
Import java.io.IOException;
Import Java.text.SimpleDateFormat;
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;
public class Lastaccesstimeservlet extends HttpServlet {private static final long serialversionuid = 1L;
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Gets the current time date date = new Date ();
SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss");
String currenttime = Format.format (date);
1. Create a cookie that records the current latest access time cookie cookie = new Cookie ("LastAccessTime", currenttime);
Cookie.setmaxage (60 * 10 * 500);
Response.addcookie (cookie);
2. Obtain the cookie that the client carries-----lastaccesstime String lastaccesstime = null;
cookie[] cookies = request.getcookies (); if (cookies!)= null) {for (Cookie coo:cookies) {if (Coo.getname (). Equals ("LastAccessTime")) {LastAccessTime = Coo.getv
Alue ();
}}} response.setcontenttype ("Text/html;charset=utf-8");
if (LastAccessTime = = null) {Response.getwriter (). Write ("You are the first to visit");
} else {response.getwriter (). Write ("Your last access Time was:" + currenttime); }} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcep
tion {doget (request, response); }
}