电商网站中我的足迹/浏览历史实现关键代码

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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.oraclewdp.utils.ConvertUtil;

@WebServlet(name="history",urlPatterns="/history")
public class HistoryAction extends HttpServlet {
	@Override
	public void init() throws ServletException {
		super.init();
	}
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String producthistoryid="";
		String id=req.getParameter("id");
		//获取Cookie数据并遍历,看是否已经存在producthistoryid这个Cookie
		Cookie[] cookies=req.getCookies();
		if(cookies!=null&&cookies.length>0){
			for (Cookie cookie : cookies) {
				String name=cookie.getName();
				String value=cookie.getValue();
				if(name.equals("producthistoryid")){
				    //存在producthistoryid这个cookie的话,就将它赋值给producthistoryid这个变量
					producthistoryid=value;
				}
			}
		}
		//当遍历=之后发现没有这个Cookie是,就创建producthistoryid这个Cookie,并将商品id保存到其中
		if(producthistoryid==null||producthistoryid.equals("")){
			id+=",";
			System.out.println(id);
			Cookie producthistoryCookie=new Cookie("producthistoryid",id);
			resp.addCookie(producthistoryCookie);
		}else{
		    //存在producthistoryid这个Cookie时,就将最近浏览的id添加到字符串的最前面
		    //要保证最新浏览的商品id在最前面,有两种实现方式,当最下面哪种更简便
		    //方式一:
//			String historyid="";
//			List<String> maskList=new ArrayList<String>();
//			String[] masks=producthistoryid.split(",");
//			for (String mask: masks){
//				if(!mask.equals(id)){
//					maskList.add(mask);
//				}
//			}
//         //ConvertUtil是将ArrayList里面的内容转换成字符串的一个帮助类
//			String rs=ConvertUtil.convertByMask(maskList, ",");
//			rs=id+","+rs;
			//或者这样实现,三行代码就可以搞定
			producthistoryid=","+producthistoryid;
			producthistoryid=producthistoryid.replace(","+id+",", ",");
			String rs=id+producthistoryid;
			
			Cookie producthistoryCookie=new Cookie("producthistoryid",rs);
			resp.addCookie(producthistoryCookie);
		}
		resp.sendRedirect(req.getContextPath()+"/productList");
	}
	@Override
	public void destroy() {
		super.destroy();
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doPost(req, resp);
	}
	public HistoryAction() {
		super();
	}

}

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值