您当前的位置: 首页 > 

梁云亮

暂无认证

  • 1浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

基于Cookie的Session跨域

梁云亮 发布时间:2020-01-25 12:00:35 ,浏览量:1

一个完整的、有独立访问路径的功能集合称为一个域。 域信息,有时也称为多级域名。 域以IP、端口、域名、主机名为标准实现划分。 例如百度下的若干个域:搜索引擎(www.baidu.com),百度贴吧(tie.baidu.com),百度知道(zhidao.baidu.com),百度地图(map.baidu.com)等。

跨域

客户端请求的时候,请求服务器的IP、端口、域名、主机名只要有一个相同,都称为跨域。

session跨域

默认情况下session是不能跨域的。 Session跨域就是摒弃了系统(Tomcat)提供的Session,而使用自定义的类似Session的机制来保存客户端数据的一种解决方案。

实现方法的原理

通过设置cookie的domain来实现cookie的跨域传递。在cookie中传递一个自定义的session_id。这个session_id是客户端的唯一标记。将这个标记作为key,将客户端需要保存的数据作为value,在服务端进行保存(数据库保存或NoSQL保存)。这种机制就是Session的跨域解决。

set-cookie虽然在响应头中存在,但是在跨域的时候出于安全考虑,该头会被浏览器忽略,并不会产生真实的cookie。而Cookie 的domain属性设置域之后,那么子域可以访问父域的cookie,而父域不可以访问子域的cookie。可以说cookie的domain访问权限是向下继承的,当然其它域名跨域名访问也是不可以的。

domain设置为b.e.f.com.cn或.b.e.f.com.cn没有区别。 跨域设计的思想也是子域可以访问父域。

session是保存在内存中的,由Session ID取值。session共享是通过cookie.setPath("/")设置。可在同一应用服务器内共享方法,可以在webapp文件夹下的所有应用共享cookie

示例 第一步:新建Maven项目

    junit
    junit
    4.12
    test




    javax.servlet
    javax.servlet-api
    4.0.1




    javax.servlet.jsp
    jsp-api
    2.2




    javax.servlet
    jstl
    1.2




    org.springframework
    spring-context
    5.2.1.RELEASE



    org.springframework
    spring-web
    5.2.1.RELEASE


    org.springframework
    spring-webmvc
    5.2.1.RELEASE





    com.fasterxml.jackson.core
    jackson-core
    2.10.1


    com.fasterxml.jackson.core
    jackson-databind
    2.10.1


    com.fasterxml.jackson.core
    jackson-annotations
    2.10.1

第二步:配置文件 spring.xml



    
    


springmvc.xml


    
    

    
    

    
    
        
        
    

app.xml



    

    


web.xml



    
    
        SpringMVC
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:app.xml
        
        1
    
    
        SpringMVC
        /
    


第三步:工具类
public class CookieUtils {
    /**
     * 获取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  0) {
                cookie.setMaxAge(cookieMaxage);
            }
            if (null != request) {// 设置域名的cookie
                String domainName = getDomainName(request);
                System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                    cookie.setDomain(domainName); //为cookie设定有效域范围
                }
            }
            cookie.setPath("/");//为cookie设定有效的URI范围
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到cookie的域名
     */
    private static final String getDomainName(HttpServletRequest request) {
        String domainName = null;
        //获取完整的请求URL地址
        String serverName = request.getRequestURL().toString();
        if (null == serverName || "".equals(serverName)) {
            domainName = "";
        } else {
            serverName = serverName.toLowerCase();
            if (serverName.startsWith("http://")) {
                serverName = serverName.substring(7);
            } else if (serverName.startsWith("https://")) {
                serverName = serverName.substring(8);
            }
            int end = serverName.indexOf("/");
            if (end == -1) {
                end = serverName.length() - 1;
            }
            //www.baidu.com  www.xxx.com.cn
            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  1) { // xxx.com or xxx.cn
                domainName = domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }
        //domain与端口无关 去掉端口号
        if (domainName != null && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        return domainName;
    }

}
第四步:Controller
@Controller
public class TestController {

    @RequestMapping("/fun1")
    public String fun1(HttpServletRequest request, HttpServletResponse response){
        String cookieName = "global_session_id";
        String encodeString = "UTF-8";
        String cookieValue = CookieUtils.getCookieValue(request,cookieName,encodeString);
        if(null == cookieValue || "".equals(cookieValue.trim())){
            System.out.println("cookie不存在,重新生成新的cookie");
            cookieValue = UUID.randomUUID().toString();
        }
        //根据cookieValue访问数据存储,获取客户端数据
        CookieUtils.setCookie(request,response,cookieName,cookieValue,0,encodeString);
        return "index.jsp";
    }

}
第五步,运行项目到tomcat9 打开Windows的hosts文件,在其中添加如下内容:
127.0.0.1 blog.hc.com
127.0.0.1 test.hc.com
127.0.0.1 resume.hc.com
依次在浏览器中打开如下三个网页:
  • http://test.hc.com/ssd/fun1 在这里插入图片描述

  • http://resume.hc.com/ssd/fun1 在这里插入图片描述

  • http://blog.hc.com/ssd/fun1 在这里插入图片描述

关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0424s