1. 程式人生 > >JS與Java中Cookie存取

JS與Java中Cookie存取

Js存cookie

function writeCookie (name, value, hours){
    var expire = "";
    if (hours != null)
    {
        expire = new Date ((new Date ()).getTime () + hours * 3600000);
        expire = "; expires=" + expire.toGMTString ();
    }
    document.cookie = name + "=" + escape (value) + expire;
}

layui.form.on('submit(pre)', function(data){
			//處理 	KindEditor 富文字取值問題
			var formDoms = data["form"];
			for(i=0,len=formDoms.length; i<len; i++){
				var idom = data["form"][i],
					idomName = data["form"][i].name,
					tagName = idom.tagName,
					idomId = data["form"][i].id,
					keditor = _self[idomName];
				if(idom.tagName == "TEXTAREA" && keditor){
					keditor.sync();
					data.field[idomName]=$('#'+idomId ).val();
				}
			}
			//如果有附件,上傳附件
			var uploadAttachmentIds = $("#uploadAttachmentIds").data("uploadAttachmentIds"),
				
			params = {};
			if(uploadAttachmentIds instanceof Array)
			{
                params.attachmentIds = uploadAttachmentIds.join(",");
			}
			else
			{
                params.attachmentIds = uploadAttachmentIds;
			}
			
			$.getData(CONTEXT_PATH + "/attach/updateEntityId", params);
			writeCookie("Imges", JSON.stringify(params), 1);
			
			writeCookie("adv", JSON.stringify(data.field), 1);
			
			layer.open({
				  type: 2,
			      title: "預覽",
			      maxmin: true,
				  shadeClose: true, //開啟遮罩關閉
				  area: ['100%','100%'],
			      content:CONTEXT_PATH+"/advice/preAdvice"
			});
		});

讀cookie

function readCookie (name)
{
    var cookieValue = "";
    var search = name + "=";
    if (document.cookie.length > 0)
    {
        offset = document.cookie.indexOf (search);
        if (offset != -1)
        {
            offset += search.length;
            end = document.cookie.indexOf (";", offset);
            if (end == -1)
                end = document.cookie.length;
            cookieValue = unescape (document.cookie.substring (offset, end))
        }
    }
    return cookieValue;
}


		layui.use(plugins,function(){
			_self.initEvent();
			_self.initLayuiPlugin();	//初始化layui元件		
			//渲染表單資料
			var params = {};
				params[_self.primaryKey] = _self.primaryValue;
			var imgs = JSON.parse(readCookie("Imges"));
			var data = JSON.parse(readCookie("adv"));
			var cardForm = $("#"+_self.filter+"Form"),
				formDoms = cardForm[0];
			cardForm.setValues(imgs);
			cardForm.setValues(data);
			//處理富文字賦值問題
			for(i=0,len=formDoms.length; i<len; i++){
				var idom = formDoms[i],
					idomName = idom.name,
					tagName = idom.tagName,
					idomId = idom.id,
					keditor = _self[idomName];
				if(idom.tagName == "TEXTAREA" && keditor){
					keditor.html(data[idomName]);
				}
			}	
			layui.form.render();
			if(afterRender){
				afterRender(data,_self);
			}
			
			
		});

Java Cookie工具類

import java.util.HashMap;
import java.util.Map;

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

public class CookieUtils {

	/**
     * 檢索所有Cookie封裝到Map集合
     * 
     * @param request
     * @return
     */
    public static Map<String, String> readCookieMap(HttpServletRequest request) 
    {
        Map<String, String> cookieMap = new HashMap<String, String>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie.getValue());
            }
        }
        return cookieMap;
    }
    
    /**
     * 通過Key獲取Value
     * 
     * @param request
     * @param name Key
     * @return Value
     */
    public static String getCookieValueByName(HttpServletRequest request, String name) 
    {
        Map<String, String> cookieMap = readCookieMap(request);
        if (cookieMap.containsKey(name)) {
            String cookieValue = (String) cookieMap.get(name);
            return cookieValue;
        } else {
            return null;
        }
    }
}

使用工具類獲取cookie中的值

	public String index(HttpServletRequest request,HttpServletResponse response, Model model,@RequestParam(value="userCode",required=false)String userCode,@RequestParam(value="userId",required=false)String userId) {
		logger.info("start enter index page");
		setUserCookie(request,response,userCode,userId,type);
		if(StringUtil.isEmpty(userCode))
		{
			userCode = CookieUtils.getCookieValueByName(request, "userId");
		}
		if(StringUtil.isEmpty(userId))
		{
			userId = CookieUtils.getCookieValueByName(request, "user");
		}

           Cookie writecookie=new Cookie("userId",userCode);//user的身份證號碼
			writecookie.setPath("/");
			response.addCookie(writecookie);
}


	public void setUserCookie(HttpServletRequest request, HttpServletResponse response, String userCode,
			String userId,int type) 
	{
		if(StringUtil.isNotEmpty(userCode))
		{
			Cookie writeCookie = new Cookie("userId", userCode);
			writeCookie.setPath("/");
			response.addCookie(writeCookie);
		}
		if(StringUtil.isNotEmpty(userId))
		{
			Cookie userCookie = new Cookie("user", userId);
			userCookie.setPath("/");
			response.addCookie(userCookie);
		}
		Cookie typeCookie = new Cookie("type",String.valueOf(type));
		typeCookie.setPath("/");
		response.addCookie(typeCookie);

	}