Java Web Cookie网上购物实例

package cn.com;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

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 CookieDemo3 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	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.write("本网站有如下商品:<br/>");
		Map<String ,Book > map=Db.getAll();
		for(Map.Entry<String, Book> entry:map.entrySet())
		{
			Book book=entry.getValue();
			out.print("<a href='/Cookie/CookieDemo4?id="+book.getId()+"' target='_blank' >"+book.getName()+"</a><br/>");
		}
		
		
		//显示用户曾经看过的商品
		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("\\,");
				for(String id:ids)
				{
					Book book=(Book)Db.getAll().get(id);
					out.print(book.getName()+"<br/>");
				}
			}
		}
		
		
	}

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

}
//Db作为数据库
class Db
{
	private static Map<String ,Book> map=new LinkedHashMap();
	static
	{
		map.put("1", new Book("1","Java WEB开发","WY","好书"));
		map.put("2", new Book("2","WEB开发","zt","一般"));
		map.put("3", new Book("3","程序设计","df","较好书"));
		map.put("4", new Book("4","计算机组成","as","一般好书"));
		map.put("5", new Book("5","编译原理","ty","很好书"));
		map.put("6", new Book("6","网络维护","hj","非常好书"));
	}
	
	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;
	}
	
	
}
package cn.com;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CookieDemo4
 */
public class CookieDemo4 extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	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();
		
		//根据用户带过来的id ,显示响应商品的详细信息
		String id=request.getParameter("id");
		Book book=(Book)Db.getAll().get(id);
		
 		out.write(book.getId()+"<br/>");
 		out.write(book.getAuthor()+"<br/>");
 		out.write(book.getDescription()+"<br/>");
 		out.write(book.getName()+"<br/>");
		
		//构建Cookie ,回写给浏览器
		String cookieValue=buildCookie(id,request);
		Cookie cookie=new Cookie("bookHistory",cookieValue);
		cookie.setMaxAge(30*24*3600);
		cookie.setPath("/Cookie");
		response.addCookie(cookie);
	}

	
	private String buildCookie(String id, HttpServletRequest request) {
		// TODO Auto-generated method stub
		//如果用户没有带任何的Cookie过来
		
		//如果用户带了Cookie来了包含在看过的id中,则要把id删掉
		
		//带了Cookie过来了但是没有包含看过的id
		
		//带了Cookie过来但是没有包含
		
		String bookHistory=null;
		Cookie cookies[]=request.getCookies();
		for(int i=0;cookies!=null&&i<cookies.length;i++)
		{
			if(cookies[i].getName().equals("bookHistory"))
			{
				bookHistory=cookies[i].getValue();
			}
		}
		if(bookHistory==null)
		{
			return id;
		}
		LinkedList list=new LinkedList(Arrays.asList(bookHistory.split("\\,")));
//		if(list.contains(id))
//		{
//			list.remove(id);
//			list.addFirst(id);
//		}
//		else 
//		{
//			if(list.size()>=3)
//			{
//				list.removeLast();
//				list.addFirst(id);
//			}
//			else
//			{
//				list.addFirst(id);
//			}
//		}
		
		if(list.contains(id))
		{
			list.remove(id);
		}
		else if(list.size()>=3)
		{
			list.removeLast();
		}
		list.addFirst(id);
		
		StringBuffer sb=new StringBuffer();
		
		Iterator it=list.iterator();
		while(it.hasNext())
		{
			String bid=(String)it.next();
			sb.append(bid+",");
		}
		return sb.deleteCharAt(sb.length()-1).toString();
	}

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

}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值