Cookie的实现例子

3/8/2017来源:ASP.NET技巧人气:952

1.新建一个web项目  

这是项目的一个目录

2.代码的实现

package cookie;

import java.io.IOException;
import java.io.PRintWriter;
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;

@WebServlet("/CookieExampleServlet")
public class CookieExampleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public CookieExampleServlet() {
		super();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=UTF-8");
		PrintWriter out = resp.getWriter();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowtime = sdf.format(new Date());

		String LastVisitTime = "";
		int Count = 0;
		// 从客户端获得所有的cookies
		Cookie[] cookies = req.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("LastVisitTime".equals(cookie.getName())) {
					LastVisitTime = cookie.getValue();
				}
				if ("Count".equals(cookie.getName())) {
					Count = Integer.valueOf(cookie.getValue());
				}
			}
		}

		// 如果曾经访问过,则输出访问的时间 和访问的次数
		if (!"".equals(LastVisitTime))
			out.print("您上一次访问的时间是:" + LastVisitTime);
		out.print("您是第" + (Count + 1) + "次访问本网站");

		Cookie pLastVisitTime = new Cookie("LastVisitTime", nowtime);
		Cookie pCount = new Cookie("Count", "" + (Count + 1));
		// 设置最大存活时间为一年
		pLastVisitTime.setMaxAge(365 * 24 * 60 * 60);
		pCount.setMaxAge(365 * 24 * 60 * 60);
		// 新建cookie响应到客户端
		resp.addCookie(pCount);
		resp.addCookie(pLastVisitTime);
	}
}3.在网页中输入url

http://localhost:8080/CookieExample/CookieExampleServlet