升级到 Tomcat 8 后 Cookie 可能出现的问题
servlet:
@WebServlet(urlPatterns = "/AddCookie")
public class AddCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//利用response下发一个cookie到浏览器
//1、创建一个cookie(不限个数)
Cookie cookie = new Cookie("message", "hello world");
//2、下发cookie
response.addCookie(cookie);
response.setContentType("text/html; charset=UTF-8");
response.getWriter().println("ok");
}
}
- 问题原因
Tomcat 8 更换默认的 CookieProcessor 实现为 Rfc6265CookieProcessor ,之前的实现为 LegacyCookieProcessor 。前者是基于 RFC6265 ,而后者基于 RFC6265、RFC2109、RFC2616 。 - 解决方式(报cookie的错都可以试试)
独立的 Tomcat修改配置文件 context.xml ,指定 CookieProcessor 为 org.apache.tomcat.util.http.LegacyCookieProcessor,具体配置如下:
<Context>
<CookieProcessor className="org.apache.tomcat.util.http.LegacyCookieProcessor" />
</Context>
- SpringBoot 内嵌 Tomcat 的解决方式
在 springboot 启动类中增加内嵌 Tomcat 的配置 Bean,如下代码:
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
// Tomcat Cookie 处理配置 Bean
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
return (factory) -> factory.addContextCustomizers(
(context) -> context.setCookieProcessor(new LegacyCookieProcessor()));
}
}