Java快速开发平台

www.fastunit.com

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  23 Posts :: 0 Stories :: 273 Comments :: 0 Trackbacks
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

  
public static Cookie getCookie(HttpServletRequest request, String name) {
    Cookie cookies[] 
= request.getCookies();
    
if (cookies == null || name == null || name.length() == 0) {
      
return null;
    }
    
for (int i = 0; i < cookies.length; i++) {
      
if (name.equals(cookies[i].getName())
          
&& request.getServerName().equals(cookies[i].getDomain())) {
        
return cookies[i];
      }
    }
    
return null;
  }

  
public static void deleteCookie(HttpServletRequest request,
      HttpServletResponse response, Cookie cookie) {
    
if (cookie != null) {
      cookie.setPath(getPath(request));
      cookie.setValue(
"");
      cookie.setMaxAge(
0);
      response.addCookie(cookie);
    }
  }

  
public static void setCookie(HttpServletRequest request,
      HttpServletResponse response, String name, String value) {
    setCookie(request, response, name, value, 
0x278d00);
  }

  
public static void setCookie(HttpServletRequest request,
      HttpServletResponse response, String name, String value, 
int maxAge) {
    Cookie cookie 
= new Cookie(name, value == null ? "" : value);
    cookie.setMaxAge(maxAge);
    cookie.setPath(getPath(request));
    response.addCookie(cookie);
  }

  
private static String getPath(HttpServletRequest request) {
    String path 
= request.getContextPath();
    
return (path == null || path.length()==0? "/" : path;
  }

}
posted on 2008-03-25 17:19 FastUnit 阅读(9360) 评论(5)  编辑  收藏 所属分类: Java

Feedback

# 顶顶顶 2008-03-26 16:28 草包书生
可以这样,但现在好多PC的主人都不愿意保存cookie了呀。

我决定把这个收藏起来  回复  更多评论
  

# re: Java操作Cookie 2008-06-02 15:09 懒人
@草包书生
没有用,还烦  回复  更多评论
  

# re: Java操作Cookie 2008-07-17 10:23 larry_qr
草包,这咋能没有用呢?为什么?别这么不负责任的乱说  回复  更多评论
  

# re: Java操作Cookie 2009-01-20 13:55 wangs130
very good!  回复  更多评论
  

# re: Java操作Cookie 2014-08-13 12:15 雪莱
已收藏  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: