package com.itcast.web.action.product;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.stereotype.Controller;
import com.itcast.util.WebUtil;
import com.itcast.web.formbean.product.FrontProductForm;
@Controller("/product/view")
public class ViewProductAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
FrontProductForm fromBean = (FrontProductForm)form;
//向cookie数组中添加(或覆盖)viewCookie
WebUtil.addCookie(response, "viewCookie", buildViewHistory(request,fromBean.getProductid()), 30*24*60*60);
return mapping.findForward("product");
}
public String buildViewHistory(HttpServletRequest request,Integer productid){
//先通过cookie的名字viewCookie得到相应的cookie,然后下一步才可以向该cookie中保存数据,
//得到cookie的值格式是5-6-7-8
String valueStr = WebUtil.getCookieByName(request, "viewCookie");
//这里用一个LinkedList对象来储存浏览过的产品id
LinkedList<Integer> val = new LinkedList<Integer>();
if(null != valueStr && !"".equals(valueStr.trim())){
String[] valueStrs = valueStr.split("-");
for(String entry : valueStrs){
//val中的内容格式是3 4 5
//offer()方法是在链表的最后添加一个元素,和add()方法差不多
val.offer(new Integer(entry));
}
if(val.contains(productid)) val.remove(productid);
while(val.size()>2){
//从链表头部删除一个元素
val.poll();
}
}
val.add(productid);
//这时候val中的内容格式是3 4 5 ,下边就要构建成3-4-5的格式,然后再返回,让重新保存到对应的cookie中去
StringBuffer sb = new StringBuffer();
for(Integer entry : val){
sb.append(entry).append("-");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
}