tomcat 8 spring boot设置cookie问题

1.在spring boot项目中tomcat 8 以上需要设置cookie如下:

		Cookie cookie=new Cookie();
        cookie.setMaxAge(7* 24 * 60 * 60);
        cookie.setDomain(".test.com");
        cookie.setPath("/");
        response.addCookie(cookie);

默认情况下会报错
An invalid .test.com was present in the Cookie value
2.解决办法,在项目中增加CookieConfig配置

@Configuration
public class CookieConfig {
   /***
    * @return
    */
   @Bean
   public EmbeddedServletContainerCustomizer cookieProcessorCustomizer() {
       return new EmbeddedServletContainerCustomizer() {
           @Override
           public void customize(ConfigurableEmbeddedServletContainer container) {
               if (container instanceof TomcatEmbeddedServletContainerFactory) {
                   ((TomcatEmbeddedServletContainerFactory) container)
                           .addContextCustomizers(new TomcatContextCustomizer() {
                               @Override
                               public void customize(org.apache.catalina.Context context) {
                                   context.setCookieProcessor(myLegacyCookieProcesssor());

                               }
                           });
               }
           }

       };
   }

   @Bean
   public MyLegacyCookieProcesssor myLegacyCookieProcesssor() {
       MyLegacyCookieProcesssor legacyCookieProcessor = new MyLegacyCookieProcesssor();
       return legacyCookieProcessor;
   }

上面的MyLegacyCookieProcessor为了解决客户端使用中文设置了cookie(没有进行编码)错误完全复制了LegacyCookieProcessor代码并注释其中的校验代码,如果没有中文编码错误或者针对中文进行了Cookie cookie = new Cookie(“uname”, URLEncoder.encode(uname, “UTF-8”) )则直接使用LegacyCookieProcessor即可,复制LegacyCookieProcessor后注释了其中代码如下

     /**
     * Returns true if the byte is a separator as defined by V0 of the cookie
     * spec.
     */
    private static boolean isV0Separator(final char c) {
//        if (c < 0x20 || c >= 0x7f) {
//            if (c != 0x09) {
//                throw new IllegalArgumentException(
//                        "Control character in cookie value or attribute.");
//            }
//        }

        return V0_SEPARATOR_FLAGS.get(c);
    }
        private boolean isHttpSeparator(final char c) {
//        if (c < 0x20 || c >= 0x7f) {
//            if (c != 0x09) {
//                throw new IllegalArgumentException(
//                        "Control character in cookie value or attribute.");
//            }
//        }

        return httpSeparatorFlags.get(c);
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值