Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Response filter - doFilter() never returns

J. Cartwright
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,

I'm trying to construct a servlet filter that will have access to the complete response content before sending back to the client. To this end I've created the Filter and ResponseWrapper classes listed below. However, something's still not right.

The request is passed by the filter to the destination servlet, but I don't see any evidence that the filter ever regains control after the doFilter() call.

Can anyone point out what I'm doing wrong?

Thanks so much!

-- john

package gov.noaa.gdsg.arcims;

import javax.servlet.*;
import gov.noaa.gdsg.CharResponseWrapper;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import java.util.*;

public class AXLtoJavaScriptFilter implements Filter {
private ServletContext ctx;
private FilterConfig cfg;
private final Logger log = Logger.getLogger(AXLtoJavaScriptFilter.class);

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;

log.debug("Request received from "+request.getRemoteHost());
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()) {
String paramName = (String)en.nextElement();
log.debug(paramName+" => "+request.getParameter(paramName));

PrintWriter out = response.getWriter();
CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse)response);
filterChain.doFilter(request, responseWrapper);
* ERROR the following statement never shows in log and
* no exceptions seem to be thrown
log.debug("responseLength: "+responseWrapper.toString());

StringReader sr = new StringReader(responseWrapper.toString());
StringBuffer result = new StringBuffer();
int c;
try {
while ((c = != -1) {

//@TODO transform servlet response response.setContentLength(result.toString().length());
} catch(Exception e) {
log.fatal("Error in filter",e);


public void destroy() {
ctx = null;
cfg = null;

public void init(FilterConfig cfg) throws ServletException {
this.cfg = cfg;
ctx = cfg.getServletContext();


package gov.noaa.gdsg;

import javax.servlet.http.*;

public class CharResponseWrapper extends HttpServletResponseWrapper {
private CharArrayWriter output;

public String toString() {
return output.toString();

public CharResponseWrapper(HttpServletResponse response){
output = new CharArrayWriter();

public PrintWriter getWriter(){
return new PrintWriter(output);
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!