⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cookieutils.java

📁 这是一个轻便的j2ee的web应用框架,是一个在多个项目中运用的实际框架,采用struts,hebinate,xml等技术,有丰富的tag,role,navigation,session,dictio
💻 JAVA
字号:
/*
 * 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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -