cookieutils.java

来自「这是一个轻便的j2ee的web应用框架,是一个在多个项目中运用的实际框架,采用s」· Java 代码 · 共 97 行

JAVA
97
字号
/*
 * Created on 2004-8-18
 *
 */
package com.esimple.framework.web.util;

import javax.servlet.http.*;

/**
 * 操作浏览器cookie的工具类
 * @author steven
 *
 */
public class CookieUtils {
	
	/**cokkie保存一年时的maxAge值 */
	public static final int ONE_YEAR_AGE 	= 31536000;
	/**cokkie保存一天时的maxAge值 */
	public static final int ONE_DAY_AGE 	= 86400;
	/**cokkie保存一月时的maxAge值 */
	public static final int ONE_MONTH_AGE 	= 2592000;
	/**cokkie保存一小时时的maxAge值 */
	public static final int ONE_HOUR_AGE 	= 3600;
	/**cokkie保存在浏览器进程的maxAge值 */
	public static final int NOW_SESSION_AGE = 0;

	/**
	 * 读取浏览器cookie中的信息
	 * @param req HttpServletRequest
	 * @param name cookie的名字
	 * @return
	 */
	public static String getValue(HttpServletRequest req, String name) {
		Cookie cookies[] = req.getCookies();
		Cookie cookie = null;
		String rtValue = null;
		
		if( cookies == null ) return rtValue;
		
		for (int i = 0; i < cookies.length; i++) {
			cookie = cookies[i];
			
			if( cookie == null )continue;
			System.out.println("cookie.getName:"+ cookie.getName());
			if (cookie.getName().equalsIgnoreCase(name)) {
				rtValue = cookie.getValue();
				break;
			} else {
				continue;
			} //if end
		}
		System.out.println(rtValue);
		return rtValue;
	}
	
	/**
	 * 设置浏览器cookie
	 * @param req HttpServletRequest
	 * @param res HttpServletRequest
	 * @param name cookie的名字
	 * @param value cookie的值
	 * @param maxAge cookie保存时间,以秒为单位
	 */
	public static void setValue(
		HttpServletRequest req,
		HttpServletResponse res,
		String name,
		String value,
		int maxAge ) {
			
		Cookie cookies[] = req.getCookies();
		Cookie cookie = null;
		boolean hasCookie = false;
		for (int i = 0; i < cookies.length; i++) {
			cookie = cookies[i];
			if (cookie.getName().equalsIgnoreCase(name)) {
				hasCookie = true;
				break;
			} else {
				continue;
			} //if end
		}
		
		if (hasCookie) {
			cookie.setValue(value);
			cookie.setMaxAge(maxAge);
		} else {
			cookie = new Cookie(name, value);
			cookie.setMaxAge(maxAge);
		}
		res.addCookie( cookie );
		
		
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?