• Post Reply Bookmark Topic Watch Topic
  • New Topic

Response filter - doFilter() never returns  RSS feed

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

* AXLtoJavaScriptFilter.java
package gov.noaa.gdsg.arcims;

import javax.servlet.*;
import gov.noaa.gdsg.CharResponseWrapper;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import java.io.*;
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 = sr.read()) != -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();


* CharResponseWrapper.java
package gov.noaa.gdsg;

import java.io.*;
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);
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!