近日使用tomcat调试的时候,使用response写入一个cookie,发现cookie的值带上了双引号,百思不得其解,查找源码发现tomcat在写入cookie值有"/" 的时候,为避免错误,tomcat做了以下处理:
org.apache.tomcat.util.http.servercookie

<span> private static void maybequote (stringbuffer buf, string value) {
if (value==null || value.length()==0) {
buf.append("\"\"");
} else if (cookiesupport.alreadyquoted(value)) {
buf.append('"');
buf.append(escapedoublequotes(value,1,value.length()-1));
} <span style="color: #ff0000;">else if (cookiesupport.ishttptoken(value) &&
!cookiesupport.allow_http_separators_in_v0 ||
cookiesupport.isv0token(value) &&
cookiesupport.allow_http_separators_in_v0)</span> {
buf.append(escapedoublequotes(value,0,value.length()));
} else {
buf.append(value);
}
}
</span>
查询tomcat文档,解释如下:
org.apache.catalina. strict_servlet_compliance
if this is <code>true</code> the following actions will occur:
any wrapped request or response object passed to an application dispatcher will be checked to ensure that it has wrapped the original request or response. (srv.8.2 / srv.14.2.5.1)
a call to <code>response.getwriter()</code> if no character encoding has been specified will result in subsequent calls to <code>response.getcharacterencoding()</code> returning<code>iso-8859-1</code> and the <code>content-type</code> response header will include a <code>charset=iso-8859-1</code> component. (srv.15.2.22.1)
every request that is associated with a session will cause the session's last accessed time to be updated regardless of whether or not the request explicitly accesses the session. (srv.7.6)
cookies will be parsed strictly, by default v0 cookies will not work with any invalid characters.
if set to <code>false</code>, any v0 cookie with invalid character will be switched to a v1 cookie and the value will be quoted.
the path in <code>servletcontext.getresource</code> / <code>getresourceasstream</code> calls must start with a "/".
if set to <code>false</code>, code like <code>getresource("myfolder/myresource.txt")</code> will work.
if this is <code>true</code> the default value will be changed for:
<code>org.apache.catalina.connector.request. allow_empty_query_string</code> property
if not specified, the default value of <code>false</code> will be used.
解决办法:
在catalina.properties里边增加一行:
org.apache.catalina.strict_servlet_compliance=true
或者自行修改源码
影响版本:暂时确认有tomcat 6、7