记一次前后端分离联调 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

相关文章

MySQL主从同步延迟问题的全面解决方案

《MySQL主从同步延迟问题的全面解决方案》MySQL主从同步延迟是分布式数据库系统中的常见问题,会导致从库读取到过期数据,影响业务一致性,下面我将深入分析延迟原因并提供多层次的解决方案,需要的朋友可... 目录一、同步延迟原因深度分析1.1 主从复制原理回顾1.2 延迟产生的关键环节二、实时监控与诊断方案

SQLyog中DELIMITER执行存储过程时出现前置缩进问题的解决方法

《SQLyog中DELIMITER执行存储过程时出现前置缩进问题的解决方法》在SQLyog中执行存储过程时出现的前置缩进问题,实际上反映了SQLyog对SQL语句解析的一个特殊行为,本文给大家介绍了详... 目录问题根源正确写法示例永久解决方案为什么命令行不受影响?最佳实践建议问题根源SQLyog的语句分

解决IDEA报错:编码GBK的不可映射字符问题

《解决IDEA报错:编码GBK的不可映射字符问题》:本文主要介绍解决IDEA报错:编码GBK的不可映射字符问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录IDEA报错:编码GBK的不可映射字符终端软件问题描述原因分析解决方案方法1:将命令改为方法2:右下jav

MyBatis模糊查询报错:ParserException: not supported.pos 问题解决

《MyBatis模糊查询报错:ParserException:notsupported.pos问题解决》本文主要介绍了MyBatis模糊查询报错:ParserException:notsuppo... 目录问题描述问题根源错误SQL解析逻辑深层原因分析三种解决方案方案一:使用CONCAT函数(推荐)方案二:

Redis 热 key 和大 key 问题小结

《Redis热key和大key问题小结》:本文主要介绍Redis热key和大key问题小结,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、什么是 Redis 热 key?热 key(Hot Key)定义: 热 key 常见表现:热 key 的风险:二、

IntelliJ IDEA 中配置 Spring MVC 环境的详细步骤及问题解决

《IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决》:本文主要介绍IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决,本文分步骤结合实例给大... 目录步骤 1:创建 Maven Web 项目步骤 2:添加 Spring MVC 依赖1、保存后执行2、将新的依赖

Spring 中的循环引用问题解决方法

《Spring中的循环引用问题解决方法》:本文主要介绍Spring中的循环引用问题解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录什么是循环引用?循环依赖三级缓存解决循环依赖二级缓存三级缓存本章来聊聊Spring 中的循环引用问题该如何解决。这里聊

Spring Boot中JSON数值溢出问题从报错到优雅解决办法

《SpringBoot中JSON数值溢出问题从报错到优雅解决办法》:本文主要介绍SpringBoot中JSON数值溢出问题从报错到优雅的解决办法,通过修改字段类型为Long、添加全局异常处理和... 目录一、问题背景:为什么我的接口突然报错了?二、为什么会发生这个错误?1. Java 数据类型的“容量”限制

关于MongoDB图片URL存储异常问题以及解决

《关于MongoDB图片URL存储异常问题以及解决》:本文主要介绍关于MongoDB图片URL存储异常问题以及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录MongoDB图片URL存储异常问题项目场景问题描述原因分析解决方案预防措施js总结MongoDB图

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring