Index: java/org/apache/catalina/connector/Request.java =================================================================== --- java/org/apache/catalina/connector/Request.java (revision 929332) +++ java/org/apache/catalina/connector/Request.java (working copy) @@ -2280,10 +2280,11 @@ SessionTrackingMode.COOKIE)) return; - if (response != null) { + if (response != null && !response.isCommitted()) { Cookie newCookie = ApplicationSessionCookieConfig.createSessionCookie(context, newSessionId, secure); + response.removeCookieInternal(newCookie.getName()); response.addCookieInternal(newCookie); } } Index: java/org/apache/catalina/connector/Response.java =================================================================== --- java/org/apache/catalina/connector/Response.java (revision 929332) +++ java/org/apache/catalina/connector/Response.java (working copy) @@ -31,6 +31,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; +import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.TimeZone; @@ -1014,6 +1015,49 @@ /** + * Removes all cookies with the given name from the response. + * + * @param cookieName + */ + protected void removeCookieInternal(String cookieName) { + + if (isCommitted()) + return; + + boolean headersToRemove = false; + + // Remove any cookies from the cookies array + Iterator cookieIter = cookies.iterator(); + while (cookieIter.hasNext()) { + Cookie cookie = cookieIter.next(); + if (cookieName.equals(cookie.getName())) { + cookieIter.remove(); + headersToRemove = true; + } + } + + // Only scan the headers if we have to + if (headersToRemove) { + String match = cookieName + "="; + MimeHeaders headers = coyoteResponse.getMimeHeaders(); + int i = 0; + while (i > -1) { + i = headers.findHeader("Set-Cookie", i); + if (i > -1) { + if (headers.getValue(i).startsWith(match)) { + // Remove this header. + // Continue search at same position + headers.removeHeader(i); + } else { + // Continue search at next header + i++; + } + } + } + } + } + + /** * Add the specified date header to the specified value. * * @param name Name of the header to set Index: java/org/apache/tomcat/util/http/MimeHeaders.java =================================================================== --- java/org/apache/tomcat/util/http/MimeHeaders.java (revision 929332) +++ java/org/apache/tomcat/util/http/MimeHeaders.java (working copy) @@ -341,7 +341,7 @@ * reset and swap with last header * @param idx the index of the header to remove. */ - private void removeHeader(int idx) { + public void removeHeader(int idx) { MimeHeaderField mh = headers[idx]; mh.recycle();