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);
}