报错信息
Nov 26, 2018 10:50:13 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value
at org.apache.tomcat.util.http.Rfc6265CookieProcessor.validateCookieValue(Rfc6265CookieProcessor.java:182)
at org.apache.tomcat.util.http.Rfc6265CookieProcessor.generateHeader(Rfc6265CookieProcessor.java:115)
at org.apache.catalina.connector.Response.generateCookieString(Response.java:1019)
at org.apache.catalina.connector.Response.addCookie(Response.java:967)
at org.apache.catalina.connector.ResponseFacade.addCookie(ResponseFacade.java:386)
这个错误是由于Tomcat 8.5 新版本中默认采用cookie标准 RFC 6265,在cookie值中不能使用分号(;)、逗号(,)、等号(=)以及空格等特殊符号,否则会出现异常
下面是解决方案
Spring Boot 1.x
@Bean
public EmbeddedServletContainerCustomizer customizer() {
return container -> {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
tomcat.addContextCustomizers(context -> context.setCookieProcessor(new LegacyCookieProcessor()));
}
};
}
Spring Boot 2.x
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
return (serverFactory) -> serverFactory.addContextCustomizers(
(context) -> context.setCookieProcessor(new LegacyCookieProcessor()));
}