在线商品系统的最近浏览商品列表

实现方式 Cookie 


1.对最近浏览商品的实现需要用到cookie,一下代码可以获取cookie:

View Code
 1 /**
2 * 获取cookie的值
3 * @param request
4 * @param name cookie的名称
5 * @return
6 */
7 public static String getCookieByName(HttpServletRequest request, String name) {
8 Map<String, Cookie> cookieMap = WebUtil.readCookieMap(request);
9 if(cookieMap.containsKey(name)){
10 Cookie cookie = (Cookie)cookieMap.get(name);
11 return cookie.getValue();
12 }else{
13 return null;
14 }
15 }
16
17 protected static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
18 Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
19 Cookie[] cookies = request.getCookies();
20 if (null != cookies) {
21 for (int i = 0; i < cookies.length; i++) {
22 cookieMap.put(cookies[i].getName(), cookies[i]);
23 }
24 }
25 return cookieMap;
26 }

 

 readCookieMap先获取request里面的所有cookie,然后以键值对的形式存放到一个Map中。在getCookieByName方法中,先调用readCookieMap方法来获取所有的cookie,然后在查询自己想要查找的那个cookie的值。

2.完成了获取cookie值之后,我们就可以对cookie里面的浏览记录进行修改排序:

View Code
 1 public String buildViewHistory(HttpServletRequest request, Integer currentProductId){
2 //23-2-6-5
3 //1.如果当前浏览的id已经在浏览历史里了,我们要把移到最前面
4 //2.如果浏览历史里已经达到了10个产品了,我们需要把最选进入的元素删除
5 String cookieValue = WebUtil.getCookieByName(request, "productViewHistory");
6 LinkedList<Integer> productids = new LinkedList<Integer>();
7 if(cookieValue!=null && !"".equals(cookieValue.trim())){
8 String[] ids = cookieValue.split("-");
9 for(String id : ids){
10 productids.offer(new Integer(id.trim()));
11 }
12 if(productids.contains(currentProductId)) productids.remove(currentProductId);
13 if(productids.size()>=10) productids.poll();
14 }
15 productids.offer(currentProductId);
16 StringBuffer out = new StringBuffer();
17 for(Integer id : productids){
18 out.append(id).append('-');
19 }
20 out.deleteCharAt(out.length()-1);
21 return out.toString();
22 }

为了方便排序 cookie的值是:用户浏览过的商品的id加横杠分隔符结合而成的。如:23-2-6-5。

3.排序结束后我们又可以将新的cookie存入浏览器中:

View Code
 1 /**
2 * 添加cookie
3 * @param response
4 * @param name cookie的名称
5 * @param value cookie的值
6 * @param maxAge cookie存放的时间(以秒为单位,假如存放三天,即3*24*60*60; 如果值为0,cookie将随浏览器关闭而清除)
7 */
8 public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
9 Cookie cookie = new Cookie(name, value);
10 cookie.setPath("/");
11 if (maxAge>0) cookie.setMaxAge(maxAge);
12 response.addCookie(cookie);
13 }

 该方法的调用如下:

View Code
1 WebUtil.addCookie(response, "productViewHistory", 
2 buildViewHistory(request, formbean.getProductid()), 30*24*60*60);

 这样就完成了将用户最近浏览过的产品以cookie的形式存入浏览器。

posted @ 2012-04-07 22:02  jerry_xing8  阅读(1868)  评论(0编辑  收藏  举报