java浏览器下载Cookie实现商品浏览记录--⽅式⼀:Java实现
⽅式⼀:Java代码⽅式实现:此种⽅式实现思路较为顺畅。
难点在于,如何实现将最近浏览的产品显⽰在最前⾯:实现⽅式是借助LinkedList提供的remove()⽅法,先将此id从列表中移除,然后再借助addFirst()⽅法将此id插⼊到最前⾯。具体实现如下:
(1). 在JSP页⾯中,显⽰所有的商品列表。当我们选择某⼀款产品时,通过超链接跳转到Servlet中,并将此产品的ID⼀并传过去。
```
<dt><a href="<%=path %>/servlet/do_home_control?param=recode&ep_id=${ep.ep_id}" target="_self"><img src="images/product/1.jpg" /> </a></dt>
```
(2). 在Servlet中,接收产品id。
```
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String param = Parameter("param");
String path = ContextPath();
PrintWriter out = Writer();
//......
if("recode".equals(param)) {
String ep_id = Parameter("ep_id");
// 如果是⾸页显⽰,则ep_id为null,则只显⽰cookie中的值即可。
// 根据cookie的name,重设对应的value
String cvalue = Tool.BuildCookie("productRecode", ep_id, request);
/
/ 将新的cookie写⼊
Cookie cookie = new Cookie("productRecode", cvalue);
cookie.setMaxAge(3600 * 1000);
cookie.setPath("/");
response.addCookie(cookie);
// 根据id获得对应的产品集合,最终将产品列表显⽰到jsp页⾯中
List<Easybuy_Product> eps = new ArrayList<Easybuy_Product>();
for (String c : cvalue.split(",")) {
eps.ProductByEp_Id(Integer.parseInt(c)));
}
response.ContextPath()
+ "/product-view.jsp?ep_id=" + ep_id);
}
}
```
(3). 上⾯涉及到⼀个⽅法,将此⽅法写到⼯具类中了。
```
//Tool.java⼯具类中写了下⾯的两个⽅法
/**
* 将id添加到cookie中,并返回最终的Cookie字符串
* @param cookieName
* @param ep_id
* @param request
* @return String
*/
public static String BuildCookie(String cookieName, String ep_id,
HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
String recodeValue = getCookieValue(cookieName, request);
// 判断cookie的value值中是否包含此id
if (recodeValue == null) {
// 判断ep_id是否为空。如果为空,则为⾸页显⽰
if (ep_id == null || "".equals(ep_id)) {
return null;
}
return ep_id;
} else {
//转换成LinkedList很有必要。普通的ArrayList想要实现最近浏览的产品移动到最前⾯⽐较困难,不如LinkedList提供的⽅法来的直接。
LinkedList<String> s = new LinkedList<String>(
Arrays.asList(recodeValue.split(",")));
// 判断ep_id是否为空。如果为空,则为⾸页显⽰
//如果ep_id不为空,则判断LinkedList中是否包含此ID。如果包含,则移除掉。然后将此ID放置到列表中的第⼀个位置。            if (ep_id != null) {
if (s.contains(ep_id)) {
}
//商品显⽰3条
if (s.size() > 3) {
}
s.addFirst(ep_id);
}
for (String bid : s) {
sb.append(bid + ",");
}
return sb.deleteCharAt(sb.length() - 1).toString();
}
}
/**
* 根据cookieName获取cookie对应的value值
*
* @param cookieName
* @return
*/
public static String getCookieValue(String cookieName,
HttpServletRequest request) {
Cookie[] cookies = Cookies();
String recodeValue = null;
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
if (cookieName.Name())) {
recodeValue = Value();
break;
}
}
}
return recodeValue;
}
```
这个功能就这样实现了!如果你有想法,咱们⼀起探讨!