java购物车的实现 基于Session和Cookie的购物车(二)

2014-11-24 08:22:27 · 作者: · 浏览: 4
param name
* Cookie 的名字
* @param value
* Cookie 的值
* @param maxAge
* Cookie 的存活时间
*/
public static void addCookie(HttpServletResponse response, String name,
String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
if (maxAge > 0)
cookie.setMaxAge(maxAge);
// 添加到客户端
response.addCookie(cookie);
}
/**
* 取出硬盘中所有的 Cookie
*
* @param request
* @return
*/ www.2cto.com
public static Map getAllCookies(HttpServletRequest request) {
Map cookie_map = new HashMap();
Cookie[] cookies = request.getCookies();
// 如果存在 cookie, 就存入 Map
if (cookies!= null ){
for ( int i = 0; i < cookies. length ; i++) {
cookie_map.put(cookies.getName(), cookies);
}
}
return cookie_map;
}
/**
* 在 Cookie 中通过 Cookie 名称获得Session中的 SessionId
* @param request
* @param name
* @return
*/
public static String getSessionIdByNameInCookie(HttpServletRequest request,String name){
Map cookie_map=getAllCookies (request);
if (cookie_map.containsKey(name)){
Cookie cookie = cookie_map.get(name);
return cookie.getValue();
}
return null ;
}
}