记一次前后端分离联调 setCookie出现的问题

我用的springboot 2.0.3 内置的tomcat是8.5.31



第一次出现问题  :java.lang.IllegalArgumentException: An invalid domain [] was specified for this cookie 

经过查询发现是 tomcat版本的问题,网上的答案是说tomcat8.5上cookie name的规则是用org.apache.tomcat.util.http.Rfc6265CookieProcessor

然后在tomcat8.0上使用的是org.apache.tomcat.util.http.LegacyCookieProcessor

解决方案有的是说有两种 一个是换掉tomcat的版本 微笑  另一个是修改tomcat的配置,让它接着用LegacyCookieProcessor这个。

然后这两个的差别好像是说不可以是 “.”还有一些字符开头,如果是这些字符开头 Rfc6265CookieProcessor就会报上面这个错误。

然后我抖了个机灵 ,没改版本 也没改配置  在我的Util里面  修改了下,我这个Util是之前在网上拉下来的,具体出处不是特别清楚了,然后我在util里面把这个"."去掉以后,上面的问题解决了  微笑

修改前的样子



修改后的样子:


ok  抖机灵解决问题  :)

然后碰到了最烦人的问题 我觉得烦人 是因为我对这方面了解的不多 ok描述业务与问题

业务:

首先 前段调用我后台的接口做登录  然后我给他set一个Cookie进去 他以后每次请求我都会在request里面取拿这个东西(需要前段加一个允许携带Cookie的设置好像,忘了叫啥,也忘了默认是true还是false了,反正肯定是有),去做验证这个token有没有被篡改,还是不是我之前放进去的那个token  

问题:

我后端setCookie不报错以后  前段的响应头里面看不到我set的Cookie  :)

我这边是成功了的 然后网页就是拿不到 ,也不报错 没有报错信息这个是最烦的  不怕你报错 就怕你啥都不显示,默默地不干人事儿  : )

 然后我在前端的电脑上绑定了一个我ip的host  然后再看NetWork里面信息


ok  发现有点点儿 坏味道   :)

看上去怪怪的 ...   Orign是localHost  然后request的是我的hello.com  

然后又在网上搜索到这篇文章



原文链接:    https://blog.csdn.net/czhphp/article/details/65628977

好的 是我放到了hello下面 然后他是localhost  所以他是看不到我放在响应头的东西的  :)  怎么办   跟上面的文章说的一样 配个子域名吧 :)  把他的localhost配成我的子域名  xxx.hello.com  

再试一次 



好了 响应头里面有东西了  完美 :)    

最后的解决方案就是  在前端的电脑上配两个host  一个我的 一个他的local  

然后当然这个问题 如果以后我们放到同一台服务器 ,或者用nginx  都不会出现。  但是联调出来了  总不能拉下他的代码来 或者他拉下我的代码来 

如果最后我set不进去 就准备采用b计划  我直接以参数的形式返回给他 他自己放 下次给我带上  :)

对了 把cookieUtil的工具类贴出来  

package com.ono.cio.common.utils;

import org.slf4j.Logger;

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) {
            throw new RuntimeException(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) {
            throw new RuntimeException(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 setCookieTwo(String domian, HttpServletResponse response, String cookieName,
                                 String cookieValue) {
        setCookieTwo(domian, 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 setCookieTwo(String domain, HttpServletResponse response, String cookieName,
            String cookieValue, int cookieMaxage) {
        setCookieTwo(domain, response, cookieName, cookieValue, cookieMaxage, false);
    }

    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数
     */
    public static void setCookieTwo(String  domain, HttpServletResponse response, String cookieName,
                                 String cookieValue, int cookieMaxage, boolean isEncode) {
        doSetCookieTwo(domain, response, cookieName, cookieValue, cookieMaxage, isEncode);
    }

    /**
     * 设置Cookie的值,并使其在指定时间内生效
     *
     * @param cookieMaxage cookie生效的最大秒数
     */
    private static final void doSetCookieTwo(String domain, 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);
            String domainName = getDomainNameByUrl(domain);
            if (!"localhost".equals(domainName)) {
                cookie.setDomain(domainName);
            }
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
        } catch (Exception e) {
//            logger.error("doSetCookie错误信息:{}",e);
            throw new RuntimeException(e);
//          e.printStackTrace();
        }
    }

    /**
     * 得到cookie的域名
     */
    public static final String getDomainNameByUrl(String domain) {
        String domainName = null;

        String serverName = domain;
        if (serverName == null || serverName.equals("")) {
            domainName = "";
        } else {
//            serverName = serverName.toLowerCase();
//            serverName = serverName.substring(7);
//            final int end = serverName.indexOf("/");
            serverName = domain;
            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;
    }

    /**
     * 设置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);
                if (!"localhost".equals(domainName)) {
                   cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
        } catch (Exception e) {
//            logger.error("doSetCookie错误信息:{}",e);
            throw new RuntimeException(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)) {
                   cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
//            logger.error("doSetCookie错误信息:{}",e);
            throw new RuntimeException(e);
//          e.printStackTrace();
        }
    }

    /**
     * 得到cookie的域名
     */
    public 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;
    }

}


猜你喜欢

转载自blog.csdn.net/tanshaonan888/article/details/81003421