View Javadoc
1   /**
2    * CookieUtil.java 初始创建时间:Jun 24, 2009
3    * Copright(t)2009-2010 www.glodon.com.cn,All Rigths Reserved
4    */
5   package gboat2.base.bridge.util.http;
6   
7   import javax.servlet.http.Cookie;
8   import javax.servlet.http.HttpServletRequest;
9   import javax.servlet.http.HttpServletResponse;
10  
11  /**
12   * Cookie 工具类
13   * 
14   * @author zengjm
15   * @sinace 1.0
16   */
17  public class CookieUtil {
18  
19      /**
20       * 添加cookie
21       * 
22       * @param name cookie的key
23       * @param value cookie的value
24       * @param domain domain
25       * @param path path
26       * @param maxage 最长存活时间 单位为秒
27       * @param response 响应对象
28       */
29      public static void addCookie(String name, String value, String domain,
30              int maxage, String path, HttpServletResponse response) {
31          Cookie cookie = new Cookie(name, value);
32          if (domain != null) {
33              cookie.setDomain(domain);
34          }
35          cookie.setMaxAge(maxage);
36          cookie.setPath(path);
37          response.addCookie(cookie);
38      }
39  
40      /**
41       * 往根下面存一个cookie
42       * @param name cookie的key
43       * @param value cookie的value
44       * @param domain domain
45       * @param maxage 最长存活时间 单位为秒
46       * @param response 响应对象
47       */
48      public static void addCookie(String name, String value, String domain,
49              int maxage, HttpServletResponse response) {
50          addCookie(name, value, domain, maxage, "/", response);
51      }
52  
53      /**
54       * 从cookie值返回cookie值,如果没有返回 null
55       * 
56       * @param request 请求对象
57       * @param name 参数name
58       * @return cookie的值
59       */
60      public static String getCookie(HttpServletRequest request, String name) {
61          Cookie[] cookies = request.getCookies();
62          if (cookies == null)
63              return null;
64          for (int i = 0; i < cookies.length; i++) {
65              if (cookies[i].getName().equals(name)) {
66                  return cookies[i].getValue();
67              }
68          }
69          return null;
70      }
71  }