java 之cookie

cookies是用户访问Web服务器时由Web服务器写入用户计算机特定目录的一小段信息, Java Servlet中提供了Cookie类,可以对Cookie进行操作。在特定时候将Cookie写入用户计算机,在需要时可再取出来使用。

下面是操作cookie的工具类

package com.xyj.com.tool.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @className:CookieUtil.java
* @classDescription:cookie操作工具类
* @author:xiayingjie
* @createTime:2010-10-27
*/

public class CookieUtil {

/**
* 增加cookie
*
* @param response
* @param name
* @param value
*/
public static void addCookie(HttpServletResponse response, String name,
String value) {
addCookie(response,name,value,-1,null,null);
}
/**
* 增加cookie
*
* @param response
* @param name
* @param value
* @param time
* 以分钟来算
*/
public static void addCookie(HttpServletResponse response, String name,
String value, int time) {

addCookie(response,name,value,time,null,null);
}
/**
* 增加cookie
*
* @param response
* @param name
* @param value
* @param time
* 以分钟来算
* @param domain
* 域名
*/
public static void addCookie(HttpServletResponse response, String name,
String value, int time, String path,String domain) {

// 创建Cookie
Cookie cookie = new Cookie(name, value);

// 设置过期时间 以秒为单位
if (time > 0) {
cookie.setMaxAge(time * 60);
}
// 设置路径
if (!"".equals(path) && null != path) {
cookie.setPath(path);
}
// 设置域
if (!"".equals(domain) && null != domain) {
cookie.setDomain(domain);
}

response.addCookie(cookie);
}

/**
* 删除cookie
*
* @param request
* @param response
* @param name
* @param domain
*/
public static void deleteCookie(HttpServletResponse response, String name) {
deleteCookie(response,name,null,null);
}

/**
* 删除cookie
*
* @param request
* @param response
* @param name
* @param path
* @param domain
*/
public static void deleteCookie(HttpServletResponse response, String name, String path,String domain) {
Cookie c=new Cookie(name,"");
// 设置路径
if (!"".equals(path) && null != path) {
c.setPath(path);
}
// 设置域
if (!"".equals(domain) && null != domain) {
c.setDomain(domain);
}
c.setMaxAge(0);
response.addCookie(c);
}


/**
* 获取cookie
*
* @param request
* @param name
* @return
*/
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie c = null;
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
c = cookie;
}
}
}
return c;
}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值