博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javaweb项目前后端cookie工具
阅读量:6528 次
发布时间:2019-06-24

本文共 8175 字,大约阅读时间需要 27 分钟。

后端设置cookie的工具类 :

前端获取后端的cookie值

通过EL表达式${cookie.key.value}

package com.gmsp.util.cookie;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 工具类 * */public final class CookieUtils {    /**     * 得到Cookie的值, 不编码     *      * @param request     * @param cookieName     * @return     */    public static String getCookieValue(HttpServletRequest request, String cookieName) {        return getCookieValue(request, cookieName, false);    }    /**     * 得到Cookie的值,     *      * @param request     * @param cookieName     * @return     */    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {        Cookie[] cookieList = request.getCookies();        if (cookieList == null || cookieName == null) {            return null;        }        String retValue = null;        try {            for (int i = 0; i < cookieList.length; i++) {                if (cookieList[i].getName().equals(cookieName)) {                    if (isDecoder) {                        retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");                    } else {                        retValue = cookieList[i].getValue();                    }                    break;                }            }        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return retValue;    }    /**     * 得到Cookie的值 (自定义编码格式),     *      * @param request     * @param cookieName     * @return     */    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {        Cookie[] cookieList = request.getCookies();        if (cookieList == null || cookieName == null) {            return null;        }        String retValue = null;        try {            for (int i = 0; i < cookieList.length; i++) {                if (cookieList[i].getName().equals(cookieName)) {                    retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);                    break;                }            }        } catch (UnsupportedEncodingException e) {             e.printStackTrace();        }        return retValue;    }    /**     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue) {        setCookie(request, response, cookieName, cookieValue, -1);    }    /**     * 设置Cookie的值 在指定时间内生效,但不编码     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue, int cookieMaxage) {        setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);    }    /**     * 设置Cookie的值 不设置生效时间,但编码     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue, boolean isEncode) {        setCookie(request, response, cookieName, cookieValue, -1, isEncode);    }    /**     * 设置Cookie的值 在指定时间内生效, 编码参数     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue, int cookieMaxage, boolean isEncode) {        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);    }    /**     * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)     */    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,            String cookieValue, int cookieMaxage, String encodeString) {        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);    }    /**     * 删除Cookie带cookie域名     */    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,            String cookieName) {        doSetCookie(request, response, cookieName, "", -1, false);    }    /**     * 设置Cookie的值,并使其在指定时间内生效     *      * @param cookieMaxage cookie生效的最大秒数     */    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,            String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {        try {            if (cookieValue == null) {                cookieValue = "";            } else if (isEncode) {                cookieValue = URLEncoder.encode(cookieValue, "utf-8");            }            Cookie cookie = new Cookie(cookieName, cookieValue);            if (cookieMaxage > 0)                cookie.setMaxAge(cookieMaxage);            if (null != request) {
// 设置域名的cookie String domainName = getDomainName(request); System.out.println(domainName); if (!"localhost".equals(domainName)&&"127.0.0.1".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } /** * 设置Cookie的值,并使其在指定时间内生效 * * @param cookieMaxage cookie生效的最大秒数 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { try { if (cookieValue == null) { cookieValue = ""; } else { cookieValue = URLEncoder.encode(cookieValue, encodeString); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) cookie.setMaxAge(cookieMaxage); if (null != request) {
// 设置域名的cookie String domainName = getDomainName(request); System.out.println(domainName); if (!"localhost".equals(domainName)&&"127.0.0.1".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } /** * 得到cookie的域名 */ private static final String getDomainName(HttpServletRequest request) { String domainName = null; String serverName = request.getRequestURL().toString(); if (serverName == null || serverName.equals("")) { domainName = ""; } else { serverName = serverName.toLowerCase(); serverName = serverName.substring(7); final int end = serverName.indexOf("/"); serverName = serverName.substring(0, end); final String[] domains = serverName.split("\\."); int len = domains.length; if (len > 3) { // www.xxx.com.cn domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1]; } else if (len <= 3 && len > 1) { // xxx.com or xxx.cn domainName = "." + domains[len - 2] + "." + domains[len - 1]; } else { domainName = serverName; } } if (domainName != null && domainName.indexOf(":") > 0) { String[] ary = domainName.split("\\:"); domainName = ary[0]; } return domainName; }}

前端JS设置cookie:

设置和加入cookie的方法

cookie.set(key,value);

cookie.get(key);

var cookie = {    set:function(key,val,time){
//设置cookie方法 var date=new Date(); //获取当前时间 var expiresDays=time; //将date设置为n天以后的时间 date.setTime(date.getTime()+expiresDays*24*3600*1000); //格式化为cookie识别的时间 document.cookie=key + "=" + escape(val) +";expires="+date.toGMTString(); //设置cookie }, get:function(key){
//获取cookie方法 /*获取cookie参数*/ var getCookie = document.cookie.replace(/[ ]/g,""); //获取cookie,并且将获得的cookie格式化,去掉空格字符 var arrCookie = getCookie.split(";") //将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中 var tips; //声明变量tips for(var i=0;i

 

转载于:https://www.cnblogs.com/fangweilin/p/8507568.html

你可能感兴趣的文章
sort,uniq命令
查看>>
am335x 电容屏驱动添加。
查看>>
JavaScript Unicode字符操作
查看>>
rhel-server-7.2-x86_64无法联网(VMware环境)
查看>>
Nginx配置中的log_format用法梳理(设置详细的日志格式)
查看>>
Atitit 软件工程概览attilax总结
查看>>
优化LibreOffice如此简单
查看>>
【Oracle 数据迁移】环境oracle 11gR2,exp无法导出空表的表结构【转载】
查看>>
秒杀系统设计方案
查看>>
3D印花芭蕾舞鞋为舞者科学地保护双脚
查看>>
冲浪科技获Ventech China数百万美元天使轮融资,发力自动驾驶行业
查看>>
通过ActionTrail监控AccessKey的使用
查看>>
从 JavaScript 到 TypeScript
查看>>
一个mysql复制中断的案例
查看>>
【最佳实践】OSS开源工具ossutil-大文件断点续传
查看>>
Linux常用的服务器构建
查看>>
深入了解 Weex
查看>>
Android第三方开源FloatingActionButton(com.getbase.floatingactionbutton)【1】
查看>>
【75位联合作者Nature重磅】AI药神:机器学习模型有望提前五年预测白血病!
查看>>
精通SpringBoot——第二篇:视图解析器,静态资源和区域配置
查看>>