1.Cookie跨域

  Cookie不能跨顶级域名访问,但是二级域名可以共享Cookie,所以要实现跨域,有一定的局限性。

2.代码

  

package com.DingYu.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
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)) {
//如果true 使用UTF-8 进行解码
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域名,删除原理,把原来的cookie的Value用""
*/
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) {
//使用UTF-8进行编码
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0)
//设置Cookie的生存时间
cookie.setMaxAge(cookieMaxage);
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
System.out.println(domainName);
if (!"localhost".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);
if (!"localhost".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();
//从第七个开始截取,过滤掉http://
serverName = serverName.substring(7);
//到后面的参数为止 比如 www.taobao.com/name=xxx
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;
} }

Java Cookie工具类的更多相关文章

  1. Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie

    Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie >>>>>>>>>>>>& ...

  2. java cookie 工具类

    package com.xxx.xxx.xxx.xxx; import java.net.URLDecoder; import java.net.URLEncoder; import javax.se ...

  3. Cookie工具类 - CookieUtil.java

    Cookie工具类,提供Cookie的创建.获取.删除方法. 源码如下:(点击下载 -CookieUtil.java ) import javax.servlet.http.Cookie; impor ...

  4. Cookie工具类

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

  5. 180425、cookie工具类

    package com.thinkgem.jeesite.common.utils; import java.io.UnsupportedEncodingException; import java. ...

  6. Cookie 工具类

    一.导入 jar 包 <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet ...

  7. Cookie工具类(获取cookie,设置cookie)

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

  8. Java开发工具类集合

    Java开发工具类集合 01.MD5加密工具类 import java.security.MessageDigest; import java.security.NoSuchAlgorithmExce ...

  9. cookie工具类,解决servlet3.0以前不能添加httpOnly属性的问题

    最近在解决XSS注入的问题,由于使用的servlet版本是2.5,不支持httpOnly的属性,故做了个工具类来实现cookie的httpOnly的功能.全类如下: /** * cookie工具类,解 ...

随机推荐

  1. php安全编程&python测试实例编写

    前言 本文首发i春秋论坛. 本篇文章主要分享一个python暴破脚本,该脚本采用optparse模块,支持自定义字典位置:用了多线程(虽然我感觉和单线程速度差不多..是我的错觉还是线程写的不对..求表 ...

  2. 使用Java面向对象单词必备

    第一章 class   班级,用声明类 object     目标,整个程序集对大 static  静态的 final  不可更改的,用声明常量 private  私有的,用访问权限 public  ...

  3. SpringBoot集成Thymeleaf模板引擎

    简单介绍 目前在JavaEE领域有几中比较常用的模板引擎,分别是Jsp.Velocity.Freemarker.Thymeleaf,对Freemark语法不是特别熟悉,不过对于前端页面渲染效率来说,j ...

  4. Xamarin.Android 使用 SimpleAdapter 打造 ListView 万能适配器

    第一步:创建 layout1.axml 来展示列表详细内容 <?xml version="1.0" encoding="utf-8"?> <L ...

  5. Execution failed for task ':app:processDebugResources'

    经常会遇到突然AndroidStudio编译不了程序,报错误: Execution failed for task ':app:processDebugResources'. > Failed ...

  6. Mybatis 源码简述

    转载请注明来自:http://www.cnblogs.com/xmzJava/p/8578399.html 日常开发中,mybatis如果报错了调错起来会比较麻烦,因为一层套着一层,如果没有对myba ...

  7. ZOJ Problem Set - 3708 Density of Power Network

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3708 #include <stdio.h> #include ...

  8. TCP/IP 笔记 - TCP拥塞控制

    拥塞控制是TCP通信的每一方需要执行的一系列行为,这些行为有特定算法规定,用于防止网络因为大规模的通信负载而瘫痪.其基本方法是当有理由认为网络即将进入拥塞状态(或已由于拥塞而出现路由丢包情况)时减缓T ...

  9. Nginx安装echo模块

    echo-nginx-module 模块可以在Nginx中用来输出一些信息,可以用来实现简单接口或者排错. 项目地址:https://github.com/openresty/echo-nginx-m ...

  10. [NewLife.XCode]数据初始化

    NewLife.XCode是一个有10多年历史的开源数据中间件,支持nfx/netstandard,由新生命团队(2002~2019)开发完成并维护至今,以下简称XCode. 整个系列教程会大量结合示 ...