Cookie工具类 - CookieUtil.java

Cookie工具类,提供Cookie的创建、获取、删除方法。

 

源码如下:(点击下载 -CookieUtil.java )

 1 import javax.servlet.http.Cookie;
 2 import javax.servlet.http.HttpServletRequest;
 3 import javax.servlet.http.HttpServletResponse;
 4 
 5 /**
 6  * Cookie工具类
 7  * 
 8  */
 9 public class CookieUtil {
10 
11     private CookieUtil() {
12     }
13 
14     /**
15      * 添加cookie
16      * 
17      * @param response
18      * @param name
19      * @param value
20      * @param maxAge
21      */
22     public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
23         Cookie cookie = new Cookie(name, value);
24         cookie.setPath("/");
25         if (maxAge > 0) {
26             cookie.setMaxAge(maxAge);
27         }
28         response.addCookie(cookie);
29     }
30 
31     /**
32      * 删除cookie
33      * 
34      * @param response
35      * @param name
36      */
37     public static void removeCookie(HttpServletResponse response, String name) {
38         Cookie uid = new Cookie(name, null);
39         uid.setPath("/");
40         uid.setMaxAge(0);
41         response.addCookie(uid);
42     }
43 
44     /**
45      * 获取cookie值
46      * 
47      * @param request
48      * @return
49      */
50     public static String getUid(HttpServletRequest request,String cookieName) {
51         Cookie cookies[] = request.getCookies();
52         for (Cookie cookie : cookies) {
53             if (cookie.getName().equals(cookieName)) {
54                 return cookie.getValue();
55             }
56         }
57         return null;
58     }
59 }

 

posted @ 2016-02-19 12:35  小周JAVA技术分享  阅读(9244)  评论(1编辑  收藏  举报