Servlet------>cookie

 cookie原理:

在访问第一个servlet的时候创建一个cookie写给浏览器,然后浏览器存储在缓存或者硬盘,下次访问servlet2的时候通过request带过去

demo1:(通过cookie得到上次访问时间)

@WebServlet("/cookieDemo1")
public class cookieDemo1 extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		response.setCharacterEncoding("UTF_8");
		response.setContentType("text/html;charset=UTF-8");
		
		PrintWriter out=response.getWriter();
		out.print("您上次访问时间</br>");
		
		//获得用户的时间的cookie
		Cookie cookies[]=request.getCookies();//从客户端获得cookie
		for(int i=0;cookies!=null&&i<cookies.length;i++){
			if(cookies[i].getName().equals("lastAccessTime")){
				Long cookieValue=Long.parseLong(cookies[i].getValue());//得到了用户的上次访问时间
				Date date=new Date(cookieValue);
				out.print(date.toLocaleString());
			}
		}
		//创建用户的cookie
		Cookie cookie=new Cookie("lastAccessTime", System.currentTimeMillis()+"");
		cookie.setMaxAge(1*30*24*3600);//按照毫秒设置有效期(生命周期)不设置默认是关闭浏览器就失效---(设置为0,则是命令删除该cookie)
		cookie.setPath("/day06");//能带进去的有效路径,给浏览器看的 不设置默认是/day06/servlet  setDomain是表示能带入cookie的域(www.snowing.com)
		
		response.addCookie(cookie);//写给浏览器
		
		
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		doGet(request, response);
	}

}

 浏览器输出:

cookie细节一------->

浏览器一般只允许存放300个cookie,每个站点一般存放20个,每个cookie大小限制为4kb

 cookie模仿购物车推荐你曾经阅读过的东西:demo

首页分两部分,一部分是现实全部产品,另一部分是曾经阅读过的,当点击链接去阅读想阅读的书的时候把书id带过来,然后创建cookie发送给浏览器

下次访问首页,通过cookie把id读到,在曾阅读部分下显示

 

@WebServlet("/cookieDemo2")
public class cookieDemo2 extends HttpServlet {
	//代表首页的servlet
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF_8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
    //1.输出网站所有商品
		out.write("本网站有如下商品<br/>");
		Map<String, Book> map=Db.getAll();
		for(Map.Entry<String,Book> entry:map.entrySet()){
			Book book=entry.getValue();
			out.print("<a href='/day06/cookieDemo3?id="+book.getId()+"' target='_blank'>"+book.getName() +"</a><br/>");
		}
		
	//2.显示用户曾经看过的商品
		out.print("<br/>您曾经看过如下商品:<br/>");
		Cookie cookies[]=request.getCookies();
		for(int i=0;cookies!=null&&i<cookies.length;i++){
			if(cookies[i].getName().equals("bookHistory")){
				String ids[]=cookies[i].getValue().split("\,");
				String idss[]=new String[3];
				if(ids.length>=3){
						for(int j=0;j<3;j++){
							idss[j]=ids[j].toString();	
						}
						for(String id:idss){
							Book book2=map.get(id);
							out.print("<a href='/day06/cookieDemo3?id="+book2.getId()+"' target='_blank'>"+book2.getName() +"</a><br/>");
							}
				}
				else{
						for(String id:ids){
						Book book2=map.get(id);
						out.print("<a href='/day06/cookieDemo3?id="+book2.getId()+"' target='_blank'>"+book2.getName() +"</a><br/>");
						}
				}
				}
		}
		
		
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		doGet(request, response);
	}

}
class Db{
	private static Map<String,Book> map=new LinkedHashMap();
	static{
		map.put("1",new Book("1","java1111开发","老张","一本好书"));
		map.put("2",new Book("2","java2222开发","老张","一本好书"));
		map.put("3",new Book("3","java3333开发","老张","一本好书"));
		map.put("4",new Book("4","java4444开发","老张","一本好书"));
	}
	public static Map getAll(){
		return map;
	}
}
class Book{
	private String id;
	private String name;
	private String author;
	private String description;
	
	
	
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(String id, String name, String author, String description) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.description = description;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
}
@WebServlet("/cookieDemo3")
//显示商品详细信息的servlet
public class cookieDemo3 extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF_8");
		response.setContentType("text/html;charset=UTF-8");
		//根据用户带过来的id号,显示商品详细信息
		String id=request.getParameter("id");
		Map<String, Book> map=Db.getAll();
		PrintWriter out=response.getWriter();
		Book book=map.get(id);
		out.print(book.getId()+book.getName() +"<br/>");

		
		//构建cookie回写给浏览器
		String cookieValue=buildCookie(request,id);
		Cookie cookie=new Cookie("bookHistory",cookieValue);
		cookie.setMaxAge(1*30*24*3600);//按照毫秒设置有效期(生命周期)不设置就是关闭浏览器就失效
		cookie.setPath("/day06");//能带进去的有效路径,给浏览器看的   
		response.addCookie(cookie);//写给浏览器
		
	}
	private String buildCookie(HttpServletRequest request, String id) {
		Cookie cookies[]=request.getCookies();
		String cookieValue = null;
		int flag=0;
		for(int i=0;null!=cookies&&i<cookies.length;i++){
			if(cookies[i].getName().equals("bookHistory")){
				String ids[]=cookies[i].getValue().split("\,");
				for(String id1:ids){		
					if(id1.equals(id)){
						flag=1+flag;
						cookieValue=id1+","+cookieValue;
						}
					else{
					 //cookieValue=request.getCookies()[i].getValue();
						if(cookieValue==null){
							cookieValue=id1;
						}
						else{
					   cookieValue=cookieValue+","+id1;}
					 }
					}
				}
		}
		if(flag==1){
			return cookieValue;
		}
		if(flag==0){
			if(request.getCookies()==null){
				return id;
			}
			cookieValue=id+","+cookieValue;
			return cookieValue;
		}
		
		
		return request.getCookies()+"";
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		doGet(request, response);
	}

}
既往不恋,未来不迎,当下不杂
原文地址:https://www.cnblogs.com/SnowingYXY/p/6673803.html