日期:2014-05-18  浏览次数:20582 次

把以前做的项目改成struts2的形式后,以前的cookie不管用了,购物车只是一次会话内有效,请大家帮我看看,哪出问题了
这是查看购物车的代码,关了浏览器上次放入购物车中的物品就没了
//查看购物车

public String getCart() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
HttpServletRequest req  = ServletActionContext.getRequest(); 
CookieCartService ck = new CookieCartService();
String name=null;
ck.getCart(name);
Map<Book,String> map = new HashMap<Book,String>();
try{
Cookie [] cookie = req.getCookies();
for(int i=0;i<cookie.length;++i){
if(!cookie[i].getName().equals("JSESSIONID")){
 name = cookie[i].getName();
 Book book = ck.getCart(name);
if(book!=null){
map.put(book, cookie[i].getValue());
}
}
}
HttpSession session = req.getSession();
session.setAttribute("map", map);
for(Book bk : map.keySet()) {
System.out.print("------------------"+map.get(getPrice()));
}
}catch(Exception e){
return "error";
}

return "success";
}
Cookie Struts String 浏览器

------解决方案--------------------
引用:
添加购物车的代码
public String addGood() throws SQLException {
// TODO Auto-generated method stub
int qut = 1;
HttpServletRequest req  = ServletActionContext.getRequest();
Cookie [] cookie = req.getCookies();

boolean flag=false;
for(int i=0;i<cookie.length;++i){
//Cookie里有要添加的书
if(isbn.equals(cookie[i].getName())){
 qut = Integer.parseInt(cookie[i].getValue());
cookie[i].setValue(++qut + "");//数量加1
ServletActionContext.getResponse().addCookie(cookie[i]);
flag=true;
break;
}
}
if(flag==false){
Cookie ck = new Cookie(isbn,"1");
ServletActionContext.getResponse().addCookie(ck);
ck.setMaxAge(30000);
}


代码中,Coockie new出来之后,应该先设置最大存活时间,再添加到Response中,这样你设置的时间才有效。在添加之后设置时间没有用的,Cookie已经写于到响应中去了。