Cookie

目录

 

简介

存和取cookie

一次存放多个cookie

获取上次登录时间

登录login.html

CookieUtil.java类

结果

添加或删除浏览记录

流程图

list.jsp

ListServlet.java

Clear.java


简介

Cookie是服务器发送给客户端、保存在客户端中的一段数据

应用场景:记住密码,浏览记录、购物车

存和取cookie

package com.zhujunwei.servlet;

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 Demo01 extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		//设置返回给客户端的编码格式
		response.setContentType("text/html;charset=utf-8");
		
		
		//发送cookie给客户端
		Cookie cookie = new Cookie("aa", "bb");
		//给响应,添加一个cookie
		response.addCookie(cookie);
		response.getWriter().write("请求成功了...");
		
		//获取客户端带过来的cookie
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for (Cookie c : cookies) {
				String cookieName = c.getName();
				String cookieValue = c.getValue();
				System.out.println(cookieName + " = "+ cookieValue);
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

 第一次访问下面链接时在后台看不到数据,因为我们刚存进去cookie,第二此可以看到aa=bb的结果。

http://localhost:8080/Cookie/Demo01

一次存放多个cookie

这个例子一次添加了两个cookie[name=zhangsan,age=18]

package com.zhujunwei.servlet;

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 Demo02 extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//取客户端发送过来的cookie.
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for (Cookie cookie : cookies) {
				System.out.println(cookie.getName()+" = "+cookie.getValue());
			}
		}
		
		
		
		//1. 先写cookie 可以给客户端返回多个cookie
		Cookie cookie = new Cookie("name", "zhangsan");
		
		//2. 这个cookie的有效期。  默认情况下 ,
		
		//关闭浏览器后,cookie就没有了。 ---> 针对没有设置cookie的有效期。
		//有效期以秒计算。
		//正值 : 表示 在这个数字过后,cookie将会失效。
		//负值: 关闭浏览器,那么cookie就失效, 默认值是 -1
		cookie.setMaxAge(60 * 60 * 24 * 7);
		
		//赋值新的值
		//cookie.setValue(newValue);
		
		//用于指定只有请求了指定的域名,才会带上该cookie
//		cookie.setDomain(".zhujunwei.com");
		
		//只有访问该域名下的cookieDemo的这个路径地址才会带cookie
//		cookie.setPath("/CookieDemo");
		
		response.addCookie(cookie);
		
		Cookie cookie2 = new Cookie("age", "18");
		response.addCookie(cookie2);
		
		response.getWriter().write("hello Cookie...");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

获取上次登录时间

登录login.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
</head>
<body>
	<h2>请输入账号密码登录</h2>
	<form action="Demo03" method="get">
		账号:<input type="text" name="username"><br>
		密码:<input type="text" name="password"><br>
		<input type="submit" value="登录">
	</form>
</body>
</html>

CookieUtil.java类

接收一个Cookie数据和cookie的名字,如果在该数组中找到该cookie就返回该cookie,如果找不到就返回null

package com.zhujunwei.util;

import javax.servlet.http.Cookie;

public class CookieUtil {

	/**
	 * 从一个cookie数组中找到具体我们想要的cookie对象
	 * @param cookies
	 * @param name
	 * @return
	 */
	public static Cookie findCookie(Cookie[] cookies , String name){
		if(cookies != null){
			for (Cookie cookie : cookies) {
				if(name.equals(cookie.getName())){
					return cookie;
				}
			}
		}
		return null;
	}
}

Demo03.java

用来获取上次登录的时间,并对时间进行更新

package com.zhujunwei.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.zhujunwei.util.CookieUtil;
/**
 * 获取上次登录时间
 * @author Administrator
 *
 */
public class Demo03 extends HttpServlet {

	private static final long serialVersionUID = 1L;

	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 last-name --- >
			Cookie [] cookies = request.getCookies();
			
			//从数组里面找出我们想要的cookie
			Cookie cookie = CookieUtil.findCookie(cookies, "last");
			
			//是第一次登录,没有cookie
			if(cookie == null){
				Cookie c = new Cookie("last", System.currentTimeMillis()+"");
				c.setMaxAge(60*60); //一个小时
				response.addCookie(c);
				response.getWriter().write("欢迎您, "+userName);
			}else{
				//1. 去以前的cookie第二次登录,有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("登陆失败 ");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

结果

第一次登录

第二次登录

添加或删除浏览记录

流程图

list.jsp

浏览器中显示

<%@page import="com.zhujunwei.util.CookieUtil"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="ListServlet?id=1">商品1</a><br>
	<a href="ListServlet?id=2">商品2</a>	<br>
	<a href="ListServlet?id=3">商品3</a>	<br>
	<a href="ListServlet?id=4">商品4</a>	<br>
	<a href="ListServlet?id=5">商品5</a>	<br>
	<hr>
	<!-- 展示浏览记录 -->
	<%
		Cookie[] cookies = request.getCookies();
		Cookie cookie = CookieUtil.findCookie(cookies, "history");
		if (cookie == null) {
	%>
	<h2>您没有浏览任何商品。</h2>
	<%
		} else {
			String[] ids = cookie.getValue().split("#");
			for (String id : ids) {
				System.out.println(id);
	%>
				商品<%=id %>
	<%
			}
		}
	%>
	<!-- 删除浏览记录 -->
	<br>
	<a href="Clear">删除浏览记录</a>
</body>
</html>

ListServlet.java

处理cookie的添加

package com.zhujunwei;

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

import com.zhujunwei.util.CookieUtil;

/**
 * 用来添加浏览记录的cookie
 * @author Administrator
 *
 */
@WebServlet("/ListServlet")
public class ListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取当前用户浏览的商品id
		String id = request.getParameter("id");
		Cookie[] cookies = request.getCookies();
		Cookie cookie = CookieUtil.findCookie(cookies, "history");

		// 第一次浏览
		if (cookie == null) {
			Cookie c = new Cookie("history", id);
			c.setMaxAge(60 * 60 * 24);
			c.setPath("/Cookie2");
			response.addCookie(c);
			System.out.println("cookie=" + id);
		}
		// 不是第一次浏览
		else {
			String ids = cookie.getValue();
			cookie.setValue(id + "#" + ids);
			cookie.setMaxAge(60 * 60 * 24);
			cookie.setPath("/Cookie2");
			response.addCookie(cookie);
			System.out.println("cookies=" + cookie.getValue());
		}
		response.sendRedirect("list.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

Clear.java

清除浏览记录的Cookie

package com.zhujunwei;

import java.io.IOException;
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("/Clear")
public class Clear extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Cookie cookie = new Cookie("history","");
		cookie.setMaxAge(0);//设置立即删除
		cookie.setPath("/Cookie2");
		response.addCookie(cookie);
		response.sendRedirect("list.jsp");
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 

posted @ 2019-01-07 12:35  雨中遐想  阅读(6)  评论(0编辑  收藏  举报  来源