电商网站中我的足迹/浏览历史实现关键代码
2016-05-17 12:00
633 查看
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(); } }
相关文章推荐
- iOS 图片素材网站
- wvs_patcher批量测试网站
- 简单一招破解网站内容不能复制+图片不能右击(naver blog有效)
- 网站渗透思路(一)
- 网站
- Golang开发工具与常用网站
- 万网虚拟主机如何建立两个博客网站?
- iis本地无法通过ip地址访问网站
- rpm包下载网站
- 理解RESTful架构
- Lucene学习总结之二:Lucene的总体架构
- Web API应用架构设计分析(2)
- 支付宝架构师:从工程师到架构师的成长之路
- 架构的本质
- keepalived实现lvs高可用并负载均衡lamp
- 免费的论文查重网站
- 构建高性能.NET应用之配置高可用IIS服务器-第二篇 IIS请求处理模型
- 架构漫谈(五):什么是软件
- 怎样建一个众筹网站?
- Twitter 架构优化之路--Twitter是如何做到每秒处理3000张图片的