Kazu's Log

Jul 25, 2016

Who is writing response headers on Tomcat?

org.apache.coyote.http11.AbstractHttp11Processor#prepareResponse() is writing HTTP headers. This method knows a lot about HTTP, such as which status codes have a response body.

        int statusCode = response.getStatus();
        if (statusCode < 200 || statusCode == 204 || statusCode == 205 ||
                statusCode == 304) {
            // No entity body
            getOutputBuffer().addActiveFilter
                (outputFilters[Constants.VOID_FILTER]);
            entityBody = false;
            contentDelimitation = true;
        }

Then the method adds/removes some of the headers based on the knowledge.

A Tale of Two Responses

response here is org.apache.coyote.Response which is declared in org.apache.coyote.AbstractProcessor. But the class doesn’t implement HttpServletResponse. Instead Tomcat has org.apache.catalina.connector.Response which implements the interface and prepares org.apache.coyote.Response inside.

Both org.apache.coyote.Response#setHeader() org.apache.catalina.connector.Response#setHeader() have checkSpecialHeader(). The special headers such as Content-Length and Content-Type are treated differently.