public int request ( String path , HttpServletResponse response , boolean gzip ) throws IOException { Content content ; byte [ ] bytes ; try { content = doRequest ( path ) ; } catch ( IOException e ) { Servlet . LOG . error ( "request failed: " + e . getMessage ( ) , e ) ; response . setStatus ( 500 ) ; response . setContentType ( "text/html" ) ; try ( Writer writer = response . getWriter ( ) ) { writer . write ( "<html><body><h1>" + e . getMessage ( ) + "</h1>" ) ; writer . write ( "<details><br/>" ) ; printException ( e , writer ) ; writer . write ( "</body></html>" ) ; } return - 1 ; } if ( gzip ) { // see http://cs193h.stevesouders.com and "High Performance Websites", by Steve Souders response . setHeader ( "Content-Encoding" , "gzip" ) ; bytes = content . bytes ; } else { bytes = unzip ( content . bytes ) ; } response . addHeader ( "Vary" , "Accept-Encoding" ) ; response . setBufferSize ( 0 ) ; response . setContentType ( content . mimeType ) ; response . setCharacterEncoding ( ENCODING ) ; // TODO: inspect header - does this have an effect? if ( content . lastModified != - 1 ) { response . setDateHeader ( "Last-Modified" , content . lastModified ) ; } response . getOutputStream ( ) . write ( bytes ) ; return bytes . length ; }
Output is prepared in - memory before the response is written because a ) that s the common case where output is cached . If output is to big for this that whole caching doesn t work b ) I send sent proper error pages c ) I can return the number of bytes actually written