当前位置:首页 > 开发 > 编程语言 > Java > 正文

java web系统 cookie 管理

发表于: 2014-05-16   作者:annan211   来源:转载   浏览次数:
摘要: 第一步  写一个cookieUtil工具类 package com.gdiex.sts.util; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import javax.servlet.http.C
第一步  写一个cookieUtil工具类


package com.gdiex.sts.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

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


/**
 * Cookie操作类
 * 
 * @author 
 */
public class CookieUtil {
	
	private HttpServletRequest request;
	
	private HttpServletResponse response;
	
	private String path = "/"; // 默认路径
	
	private String domain = ".zzzzzz.com"; // 域
	
	private int maxAge = 0; // 最大有效期

	public CookieUtil(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	/**
	 * @param name
	 * @return
	 */
	public Cookie getCookie(String name) {
		Cookie[] cookies = request.getCookies();
		
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				//System.out.println(cookies[i].getName()+":"+cookies[i].getValue());
				if (name.equals(cookies[i].getName())) {
					return cookies[i];
				}
			}
		}
		return null;
	}

	/**
	 * 删除cookie
	 * 
	 * @param name
	 */
	public void deleteCookie(String name) {
		//setCookie(name, "", -1);
		setCookie(name, "", 0);
	}

	/**
	 * @param name
	 * @param value
	 */
	public void setCookie(String name, String value) {
		setCookie(name, value, maxAge);
	}

	/**
	 * 增加cookie
	 * 
	 * @param name
	 * @param value
	 * @param maxage
	 */
	public void setCookie(String name, String value, int cookieMaxAge) {
		setCookie(name, value, cookieMaxAge, path, domain);
	}

	/**
	 * 增加cookie
	 * 
	 * @param name
	 * @param value
	 * @param path
	 * @param domain
	 * @param cookieMaxAge
	 */
	public void setCookie(String name, String value, int cookieMaxAge, String path,
			String domain) {
		try {
			Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
			if (path != null) {
				cookie.setPath(path);
			}
			if (domain != null) {
				cookie.setDomain(domain);
			}
			if (cookieMaxAge != 0) {
				cookie.setMaxAge(cookieMaxAge);
			}
	
			response.addCookie(cookie);
		} catch (Exception e) {
			
		}
	}

	/**
	 * 得到COOKIE中的字符串
	 * 
	 * @param name
	 * @return
	 */
	public String getString(String name) {
		Cookie cookie = getCookie(name);
		if (cookie == null)
			return null;
		String value = cookie.getValue();
		if ("null".equals(value))
			return null;
		if (value != null) {
			try {
				value = URLDecoder.decode(value, "UTF-8");
			} catch (UnsupportedEncodingException e) {
			}
		}
		return value;
	}

	/**
	 * 返回整数型cookie值
	 * 
	 * @param name
	 * @return 异常返回-1
	 */
	public int getInt(String name) {
		return Integer.parseInt(getString(name)==null || "".equals(getString(name))?"-1":getString(name));
	}

	/**
	 * 返回浮点数cookie值
	 * 
	 * @param name
	 * @return 异常返回 -1.0d;
	 */
	public double getDouble(String name) {
		return Double.parseDouble(getString(name)==null || "".equals(getString(name))?"-1":getString(name));
	}
	
	/**
	 * 设置默认的PATH
	 * 
	 * @param path
	 */
	public void setPath(String path) {
		this.path = path;
	}

	/**
	 * 设置默认的DOMAIN
	 * 
	 * @param domain
	 */
	public void setDomain(String domain) {
		this.domain = domain;
	}

	/**
	 * 设置默认的MAX_AGE
	 * 
	 * @param age
	 */
	public void setMaxAge(int age) {
		this.maxAge = age;
	}

	public static void main(String[] args) {

	}
}



第二步  写一个 自定义类 校验

package com.gdiex.sts.util;

import java.net.URLDecoder;
import java.net.URLEncoder;

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

/**
 * 用户校验类
 *
 * @author 
 *
 */
public class FrontAuthencation {

	private CookieUtil cookieUtil = null;

	// added 

	public FrontAuthencation(HttpServletRequest request,
			HttpServletResponse response) {
		cookieUtil = new CookieUtil(request, response);
		cookieUtil.setDomain(SysopConstant.SYSTEM_DOMAIN);
		cookieUtil.setPath("/");
	}

	/**
	 * 保存用户名到 cookie
	 *
	 * @param userId
	 *            - 用户ID
	 * @param userName
	 *            - 用户名
	 */
	public void saveUserName(int userId, String userName, String nickName) {
		if (null == userName) {
			userName = "";
		}
		userName = userName.trim();
		if (null == nickName) {
			nickName = "";
		}
		nickName = nickName.trim();
		String code = AuthencationHelper.getCode(userName, userId);
		cookieUtil.setCookie(SysopConstant.KEY_USER_NAME_FRONT, userName);
		cookieUtil.setCookie(SysopConstant.KEY_NICK_NAME_FRONT,
				URLEncoder.encode(nickName));
		cookieUtil.setCookie(SysopConstant.KEY_USER_ID_FRONT, "" + userId);
		cookieUtil.setCookie(SysopConstant.KEY_IDENTIFYING_CODE_FRONT, code);
	}

	/**
	 * 删除cookie会话数据
	 */
	public void clearCookie() {

		cookieUtil.setPath("/");
		cookieUtil.setMaxAge(0);

		cookieUtil.deleteCookie(SysopConstant.KEY_USER_NAME_FRONT);
		cookieUtil.deleteCookie(SysopConstant.KEY_NICK_NAME_FRONT);
		cookieUtil.deleteCookie(SysopConstant.KEY_USER_ID_FRONT);
		cookieUtil.deleteCookie(SysopConstant.KEY_IDENTIFYING_CODE_FRONT);
	}

	/**
	 * 保存需要强行检验的code
	 *
	 * @param code
	 */
	public void saveVerifyCode(String code) {
		cookieUtil.setCookie(SysopConstant.KEY_VERIFY_CODE, code);
	}

	/**
	 * 是否为合法用户
	 *
	 * @return
	 */
	public boolean isValidUser() {
		String userName = getUserName();
		int userId = getUserId();
													   //KEY_IDENTIFYING_CODE_FRONT
		String code = cookieUtil.getString(SysopConstant.KEY_IDENTIFYING_CODE_FRONT);
		if (code == null) {
			return false;
		}
		String idCode = AuthencationHelper.getCode(userName, userId);
		return (idCode.equals(code));
	}

	/**
	 * 获取是否第一次访问的标识
	 *
	 * @return
	 */
	public static String getFirstRequest(HttpServletRequest request,
			HttpServletResponse response) {
		// 需要配置为进程内的域名cookie
		CookieUtil cookie = new CookieUtil(request, response);
		String domain = request.getServerName();
		// 设置的域名不能带http协议与端口
		cookie.setDomain(domain);

		cookie.setPath("/");
		cookie.setMaxAge(-1);
		return cookie.getString(SysopConstant.FIRST_REQUEST);
	}

	/**
	 * 设置第一次访问的标识
	 */
	public static void setFirstRequest(HttpServletRequest request,
			HttpServletResponse response) {
		// 需要配置为进程内的域名cookie
		CookieUtil cookie = new CookieUtil(request, response);
		String domain = request.getServerName();
		// 设置的域名不能带http协议与端口
		cookie.setDomain(domain);

		cookie.setPath("/");
		// 设置了该值不会生效
		cookie.setMaxAge(-1);

		cookie.setCookie(SysopConstant.FIRST_REQUEST,
				SysopConstant.FIRST_REQUEST);
	}

	/**
	 * 标识需要清除菜单缓存
	 *
	 * @param request
	 * @param response
	 */
	public static void setClearMenu(HttpServletRequest request,
			HttpServletResponse response) {
		// 需要配置为进程内的域名cookie
		CookieUtil cookie = new CookieUtil(request, response);
		String domain = request.getServerName();
		// 设置的域名不能带http协议与端口
		cookie.setDomain(domain);

		cookie.setPath("/");
		// 设置了该值不会生效
		cookie.setMaxAge(-1);

		cookie.setCookie("clearMenu", "clearMenu");
	}

	/**
	 * 删除第一次访问设置的缓存
	 */
	public static void removeFirstRequest(HttpServletRequest request,
			HttpServletResponse response) {
		// 需要配置为进程内的域名cookie
		CookieUtil cookie = new CookieUtil(request, response);
		String domain = request.getServerName();
		// 设置的域名不能带http协议与端口
		cookie.setDomain(domain);

		cookie.setPath("/");
		cookie.setMaxAge(0);

		cookie.deleteCookie(SysopConstant.FIRST_REQUEST);
	}

	/**
	 * 获得用户名
	 *
	 * @return
	 */
	public String getUserName() {
		return cookieUtil.getString(SysopConstant.KEY_USER_NAME_FRONT);
	}

	/**
	 * 获得用户呢称
	 *
	 * @return
	 */
	public String getNickName() {
		return URLDecoder.decode(cookieUtil
				.getString(SysopConstant.KEY_NICK_NAME_FRONT));
	}

	/**
	 * 获得用户ID
	 *
	 * @return
	 */
	public int getUserId() {
		return cookieUtil.getInt(SysopConstant.KEY_USER_ID_FRONT);
	}

	/**
	 * 设置 cookie,浏览器进程有效
	 *
	 * @param name
	 *            - 名称
	 * @param value
	 *            - 值
	 */
	public void setCookie(String name, String value) {
		cookieUtil.setCookie(name, value);
	}
}




第三步  写一个 校验工具类

package com.gdiex.sts.util;

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

/**
 * 权限验证工具类
 * @author 
 *
 */
public class AuthencationHelper {

	/**
	 * 用于加密用户名的 key
	 */
	private static final String HASH_KEY = "$ILKLKOI*-UU&^%GKJ-2EOI-LKKP-JUJKJ9";
	
	/** 一年有多少秒 */
	public static final int YEAR_SECONDS = 365 * 24 * 3600;

	/**
	 * 保存用户名到 cookie
	 * @param response
	 * @param userName - 用户名
	 */
	public static void saveUserName(HttpServletResponse response, String userName, int userId) {
		if (userName == null) {
			throw new IllegalArgumentException("userName");
		}
		
		String code = getCode(userName, userId);
		CookieUtil cookieUtil = new CookieUtil(null, response);
		cookieUtil.setDomain(SysopConstant.SYSTEM_DOMAIN);
		cookieUtil.setPath("/");
		cookieUtil.setCookie(SysopConstant.KEY_USER_NAME, userName);
		cookieUtil.setCookie(SysopConstant.KEY_USER_ID, "" + userId);
		cookieUtil.setCookie(SysopConstant.KEY_IDENTIFYING_CODE, code);
		// 保存一个固定时间的 cookie
		cookieUtil.setCookie(SysopConstant.KEY_GLOBAL_USER_ID, "" + userId, AuthencationHelper.YEAR_SECONDS);

	}
	
	/**
	 * 是否为合法用户
	 * @param request
	 * @return true - 合法
	 */
	public static boolean isValidUser(HttpServletRequest request) {
		CookieUtil cookieUtil = new CookieUtil(request, null);
		cookieUtil.setDomain(SysopConstant.SYSTEM_DOMAIN);
		cookieUtil.setPath("/");
		String userName = cookieUtil.getString(SysopConstant.KEY_USER_NAME);
		if (userName == null) {
			return false;
		}
		
		int userId = cookieUtil.getInt(SysopConstant.KEY_USER_ID);
		
		String code = cookieUtil.getString(SysopConstant.KEY_IDENTIFYING_CODE);
		if (code == null) {
			return false;
		}
		String idCode = getCode(userName, userId);
		return (idCode.equals(code));
	}
	
	/**
	 * 获得用户名
	 * @param request
	 * @return
	 */
	public static String getUserName(HttpServletRequest request) {
		CookieUtil cookieUtil = new CookieUtil(request, null);
		cookieUtil.setDomain(SysopConstant.SYSTEM_DOMAIN);
		cookieUtil.setPath("/");
		return cookieUtil.getString(SysopConstant.KEY_USER_NAME);
	}
	
	/**
	 * 获得验证码
	 * @param request
	 * @return
	 */
	public static String getIdCode(HttpServletRequest request) {
		CookieUtil cookieUtil = new CookieUtil(request, null);
		cookieUtil.setDomain(SysopConstant.SYSTEM_DOMAIN);
		cookieUtil.setPath("/");
		return cookieUtil.getString(SysopConstant.KEY_IDENTIFYING_CODE);
	}
	
	/**
	 * 获得用户ID
	 * @param request
	 * @return
	 */
	public static int getUserId(HttpServletRequest request) {
		CookieUtil cookieUtil = new CookieUtil(request, null);
		cookieUtil.setDomain(SysopConstant.SYSTEM_DOMAIN);
		cookieUtil.setPath("/");
		return cookieUtil.getInt(SysopConstant.KEY_USER_ID);
	}
	
	/**
	 * 返回一个加密后的字符串
	 * @param userName
	 * @param userId
	 * @return
	 */
	public static String getCode(String userName, int userId) {
		return EncryptUtil.getSHA1(userName + "|" + userId + HASH_KEY);
	}
	
	/**
	 * 删除所有cookie
	 * @param request
	 */
	public static void clearAllCookie(HttpServletRequest request,HttpServletResponse response) {
		CookieUtil cookieUtil = new CookieUtil(request, response);
		cookieUtil.setDomain(SysopConstant.SYSTEM_DOMAIN);
		cookieUtil.setPath("/");
		cookieUtil.deleteCookie(SysopConstant.KEY_USER_NAME);
		cookieUtil.deleteCookie(SysopConstant.KEY_USER_ID);
		cookieUtil.deleteCookie(SysopConstant.KEY_IDENTIFYING_CODE);
		cookieUtil.deleteCookie(SysopConstant.FIRST_REQUEST);
	}
}



第四步  直接调用即可

FrontAuthencation auth = new FrontAuthencation(request, response);
// 保存用户信息到cookie
			auth.saveUserName(1, PropertyUtils.getProperty(bean, "object.body.userCode").toString(), "");

简单的思路就是  HttpServletRequest 把请求来的数据 放在指定的域名的cookie下面,以键值对的形式保存,下次需要使用的时候 根据键拿出来校验,通常写在拦截器里面,执行操作之前 先检查用户合法性。


java web系统 cookie 管理

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
使用JSP+servLet实现宠物管理系统,oraC1e11g作为后台数据厍,实现查看宠物和增加宠物 的功能由你实
1.什么是会话 会话,牛津词典对其的解释是进行某活动连续的一段时间。从不同的层面看待会话,它有着
之前项目采用spring4+security3做的权限管理,采用通用的 用户-角色,角色-资源来管理权限。但是太
近来,项目维护过程中,需频繁的上传文件,由于服务器端的OS账号密码被回收,无法快速适应ftp等工具
从MyEclipse工程里面看到还有之前做的一个简单的账单管理系统,也发上来吧,以后要是心血来潮说不定
使用 Jsp实现俱乐部会员信息管理功能,orac1e11g作为后台数据库,该系统包括 查看俱乐部会员信息列表
JRE本身提供了很好的管理工具,用于Web Start 及本机Java资源的管理 -- Java高速缓存查看器 打开
在实际的j2ee项目中,系统内部难免会出现一些异常,如果把异常放任不管直接打印到浏览器可能会让用
1:select标签.选择列表~ 让从数据库得到的科目名称全部放入一个ArrayList里,用for循环将其遍历。
记得我在很早之前,开始介绍我的Winform开发框架和我的WCF开发框架之初,我曾经给出下面的视图,介
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号