近日使用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