欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java操作Cookie|java开发平台,

来源: javaer 分享于  点击 2151 次 点评:262

Java操作Cookie|java开发平台,


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;
  }

}

相关文章

    暂无相关文章
相关栏目:

用户点评