这是查看购物车的代码,关了浏览器上次放入购物车中的物品就没了
//查看购物车 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";
}CookieStrutsString浏览器
//查看购物车 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";
}CookieStrutsString浏览器
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);
}
要想长期有效,可以新建一个cookie,设置有效时期。
代码中,Coockie new出来之后,应该先设置最大存活时间,再添加到Response中,这样你设置的时间才有效。在添加之后设置时间没有用的,Cookie已经写于到响应中去了。
代码中,Coockie new出来之后,应该先设置最大存活时间,再添加到Response中,这样你设置的时间才有效。在添加之后设置时间没有用的,Cookie已经写于到响应中去了。这样是对的,我试过了,太谢谢你了