Java對象詳解之cookie使用(初級)

因項目須要,最近改用了cookie進行登陸。下面詳細解說一下,具體的使用。javascript

咱們都知道,cookie最重要的,一個是鍵值集合,一個是生命週期。它的特色在於前端和後臺均可以輕鬆對其進行操做,固然這也致使了存在必定的安全隱患,因此,大多數主流網站,在用戶體驗上,好比說記住用戶賬號和密碼,會對用戶進行安全提醒。前端

這裏咱們經過示例,講cookie的基本操做方法,安全問題的補救方法後續再聊。分兩部分,一是前端操做,二是後臺操做。java

1、前端代碼:瀏覽器

 1.定義cookie工具類,用於封裝對cookie的操做。安全

function CookieUtil(){
	
}

CookieUtil.prototype={
		support:function(){
		 
			var cookieEnable = (navigator.cookieEnable)?true:false;
			if(typeof navigator.cookieEnable == "undefined" && !cookieEnable)
			{
				document.cookie="mycookie";
				cookieEnable=(document.cookie.indexOf("mycookie")>-1)?true:false;
				document.cookie="";
			}
			return cookieEnable;
		},
		set:function(key,value,time)
		{
			if(!this.support())
			{
				alert("當前瀏覽器設置不支持cookie,請啓用cookie支持!");
				return;
			}
			if(time==null)
			{
				time=1;
			}
			var edate= new Date();
		    edate.setDate(edate.getDate()+time);
			document.cookie=key+"="+escape(value)+";expires="+edate;
		},
		get:function(key)
		{
			 
			if(!this.support())
			{
				alert("當前瀏覽器設置不支持cookie,請啓用cookie支持!");
				return;
			}
			
			if(document.cookie.length>0)
			{ 
				var reg=new RegExp("(^| )"+key+"=([^;]*)(;|$)");
				var arr= document.cookie.match(reg); 
				if(arr!=null&&arr.length>2)
				{
					return arr[2];
				}
				return null;
			}
			else
			{
				alert("讀取cookie失敗!")
			}
		}
}

 2.在頁面中調用工具類方法,來讀取和設置cookiecookie

function readCookies(){
					var cookie = new CookieUtil(); 
					
					var r =cookie.get("remember");
					var u =cookie.get("username");
					var p =cookie.get("password"); 
				   
					//記住密碼設置
					if(r=="on")
					{
						if(u!=null)
						{
							$("#username").val(u);
						}
						
						if(p!=null)
						{
							$("#password").val(p);
						}
						
						$("#remember").attr("checked","true");
					}
			}

設置的話,能夠用下面的代碼:app

var cookie = new CookieUtil(); 
cookie.set("username","test")
或者
cookie.set("username","test",1)

2、後臺代碼工具

1.一樣是定義操做工具類,這裏用到了反射,經過反射來自動映射cookie網站

package com.yeegee.test;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

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

public class CookieUtil {

	private static CookieUtil instance;

	private CookieUtil() {
		// TODO Auto-generated constructor stub
	}

	public static CookieUtil getInstance() {
		if (instance == null)
			instance = new CookieUtil();
		return instance;
	}

	public void AddCookie(HttpServletResponse response, String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		if (maxAge > 0)
			cookie.setMaxAge(maxAge);

		response.addCookie(cookie);
	}

	public Cookie GetCookie(HttpServletRequest request, String name) {
		Cookie[] cookie = request.getCookies();
		for (Cookie c : cookie) {
			if (c.getName().equals(name)) {
				return c;
			}
		}
		return null;
	}

	public Object CookieToObject(HttpServletRequest request, Class clazz) {
		Object o = null;
		try {
			Field[] fields = clazz.getDeclaredFields();
			
			o = clazz.newInstance();
			
			for (Field field : fields) {
				 
				Cookie c = this.GetCookie(request, field.getName());
				if (c != null) {
					field.setAccessible(true);
					field.set(o, c.getValue());
				}
			}
			
		 

		} catch (Exception e) {
			 
		}
		return o;
	}

	public void ObjectToCookie(HttpServletResponse response, Object o) {
		try {
			Field[] fields = o.getClass().getDeclaredFields();
		 
			for (Field field : fields) {
			 
				PropertyDescriptor pd = new PropertyDescriptor(field.getName(), o.getClass());
				Method m = pd.getReadMethod();
				if (m != null&&m.invoke(o)!=null) {
					String val = m.invoke(o).toString();
					if (val != null) {
						this.AddCookie(response, field.getName(), val, (12*60*60)); 
					}
				}

			}

		} catch (Exception e) {
				e.printStackTrace();
		}
	} 

}

2.調用時,以登陸爲例,先將object轉成cookie存儲在客戶端,當登陸以後,再獲取信息,則從cookie轉成objectthis

//登陸
CookieUtil cookie = CookieUtil.getInstance();
@RequestMapping("/checklogin")
@ResponseBody
public String CheckLogin(LoginUserEntity user) throws IOException
{
     //TODO (省略邏輯代碼)
     
     cookie.ObjectToCookie(this.response, user); 
}

//登陸後 
Object o=cookie.CookieToObject(req, LoginUserEntity.class);
//Object轉成目標對象
LoginUserEntity user = (o==null?null:(LoginUserEntity)o);

到此,cookie的操做基本上介紹完了。我的認爲,實踐是最好的老師。但願各位新手朋友能本身動手,去理解其中的奧妙。

相關文章
相關標籤/搜索