cookie使用

public ActionForward sdsd(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {


    
String openid=request.getParameter("openid");
Cookie cok=getCookieByName(request, "openid1");
if (cok==null) {
// 创建一个Cookie,包含(key,value).
    Cookie cookie = new Cookie("openid1", openid);
    // 设置Cookie的生命周期,假设设置为负值的话,关闭浏览器就失效.
    cookie.setMaxAge(60*60*24*365);
    //设置路径,这个路径即该project下都能够訪问该cookie 假设不设置路径,那么仅仅有设置该cookie路径及其子路径能够訪问
    cookie.setPath("/");
    // 输出Cookie
    response.addCookie(cookie);
}else {
System.out.println("coolie:"+cok.getValue());
}
System.out.println("openid:"+openid);
return null;
}
/**
* 将cookie封装到Map里面
* @param request
* @return
*/
private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){  
   Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
   Cookie[] cookies = request.getCookies();
   if(null!=cookies){
       for(Cookie cookie : cookies){
           cookieMap.put(cookie.getName(), cookie);
       }
   }
   return cookieMap;
}

/**
* 依据名字获取cookie
* @param request
* @param name cookie名字
* @return
*/
public static Cookie getCookieByName(HttpServletRequest request,String name){
   Map<String,Cookie> cookieMap = ReadCookieMap(request);
   if(cookieMap.containsKey(name)){
       Cookie cookie = (Cookie)cookieMap.get(name);
       return cookie;
   }else{
       return null;
   }   
}
posted @ 2017-05-31 14:36  yfceshi  阅读(121)  评论(0编辑  收藏  举报