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

2024-03-16 08:08

本文主要是介绍记一次前后端分离联调 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;
    }}


这篇关于记一次前后端分离联调 setCookie出现的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/814839

相关文章

mybatis和mybatis-plus设置值为null不起作用问题及解决

《mybatis和mybatis-plus设置值为null不起作用问题及解决》Mybatis-Plus的FieldStrategy主要用于控制新增、更新和查询时对空值的处理策略,通过配置不同的策略类型... 目录MyBATis-plusFieldStrategy作用FieldStrategy类型每种策略的作

linux下多个硬盘划分到同一挂载点问题

《linux下多个硬盘划分到同一挂载点问题》在Linux系统中,将多个硬盘划分到同一挂载点需要通过逻辑卷管理(LVM)来实现,首先,需要将物理存储设备(如硬盘分区)创建为物理卷,然后,将这些物理卷组成... 目录linux下多个硬盘划分到同一挂载点需要明确的几个概念硬盘插上默认的是非lvm总结Linux下多

Python Jupyter Notebook导包报错问题及解决

《PythonJupyterNotebook导包报错问题及解决》在conda环境中安装包后,JupyterNotebook导入时出现ImportError,可能是由于包版本不对应或版本太高,解决方... 目录问题解决方法重新安装Jupyter NoteBook 更改Kernel总结问题在conda上安装了

pip install jupyterlab失败的原因问题及探索

《pipinstalljupyterlab失败的原因问题及探索》在学习Yolo模型时,尝试安装JupyterLab但遇到错误,错误提示缺少Rust和Cargo编译环境,因为pywinpty包需要它... 目录背景问题解决方案总结背景最近在学习Yolo模型,然后其中要下载jupyter(有点LSVmu像一个

解决jupyterLab打开后出现Config option `template_path`not recognized by `ExporterCollapsibleHeadings`问题

《解决jupyterLab打开后出现Configoption`template_path`notrecognizedby`ExporterCollapsibleHeadings`问题》在Ju... 目录jupyterLab打开后出现“templandroidate_path”相关问题这是 tensorflo

如何解决Pycharm编辑内容时有光标的问题

《如何解决Pycharm编辑内容时有光标的问题》文章介绍了如何在PyCharm中配置VimEmulator插件,包括检查插件是否已安装、下载插件以及安装IdeaVim插件的步骤... 目录Pycharm编辑内容时有光标1.如果Vim Emulator前面有对勾2.www.chinasem.cn如果tools工

springboot将lib和jar分离的操作方法

《springboot将lib和jar分离的操作方法》本文介绍了如何通过优化pom.xml配置来减小SpringBoot项目的jar包大小,主要通过使用spring-boot-maven-plugin... 遇到一个问题,就是每次maven package或者maven install后target中的ja

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

Java多线程父线程向子线程传值问题及解决

《Java多线程父线程向子线程传值问题及解决》文章总结了5种解决父子之间数据传递困扰的解决方案,包括ThreadLocal+TaskDecorator、UserUtils、CustomTaskDeco... 目录1 背景2 ThreadLocal+TaskDecorator3 RequestContextH

关于Spring @Bean 相同加载顺序不同结果不同的问题记录

《关于Spring@Bean相同加载顺序不同结果不同的问题记录》本文主要探讨了在Spring5.1.3.RELEASE版本下,当有两个全注解类定义相同类型的Bean时,由于加载顺序不同,最终生成的... 目录问题说明测试输出1测试输出2@Bean注解的BeanDefiChina编程nition加入时机总结问题说明