场景:为解决多个tomcat分布式,session共享问题中,创建自定义的CookieUtil类,实现读,写,删除cookie的操作,部分代码如下
private final static String COOKIE_DOMAIN = ".nginxtomcat.com"; private final static String COOKIE_NAME = "shop_login_token"; public static String readLoginToken(HttpServletRequest request){ Cookie[] cks = request.getCookies(); if(cks != null){ for(Cookie ck : cks){ log.info("read cookieName:{},cookieValue:{}",ck.getName(),ck.getValue()); if(StringUtils.equals(ck.getName(),COOKIE_NAME)){ log.info("return cookieName:{},cookieValue:{}",ck.getName(),ck.getValue()); return ck.getValue(); } } } return null; }
如上代码,设置的COOKIE_DOMAIN的值为“.nginxtomcat.com”,在一级域名前加有一个点
但是,代码执行过程中,却有异常,经过debug调试,调用try catch捕捉了其部分异常如下
java.lang.IllegalArgumentException: An invalid domain [.nginxtomcat.com] was specified for this cookie at org.apache.tomcat.util.http.Rfc6265CookieProcessor.validateDomain(Rfc6265CookieProcessor.java:203) ~[tomcat-coyote.jar:8.5.20] at org.apache.tomcat.util.http.Rfc6265CookieProcessor.generateHeader(Rfc6265CookieProcessor.java:145) ~[tomcat
关键异常处: An invalid domain [.nginxtomcat.com] was specified for this cookie
解决方案:
问题就是tomcat版本问题,因为在tomcat8.5以后对cookie的处理变了,在tomcat8.5之前,domain定义时是需要在域名之前加一个“.”(加一个点,就像如上代码)
而在8.5之后,是不能加点的,就是将".xxxx.com" 换成"xxx.com"(此为设置一级域名)
SpringBoot方案
如果使用SpringBoot,其中使用的是内嵌的Tomcat,可以增加如下策略解决
@Configuration public class CookieConfig { /** * 解决问题: * There was an unexpected error (type=Internal Server Error, status=500). * An invalid domain [.localhost.com] was specified for this cookie * * @return */ @Bean public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() { return (factory) -> factory.addContextCustomizers( (context) -> context.setCookieProcessor(new LegacyCookieProcessor())); } }
参考文章:https://blog.csdn.net/doctor_who2004/article/details/81750713
未经允许请勿转载:程序喵 » 问题解决:An invalid domain [.xxx.com] was specified for this cookie