简体   繁体   中英

Servlet filter insists that there's no response text

My filter is supposed to edit the HTML of a response. But when I navigate to a page it does nothing because

newResponse.toString();

returns null .

Further debugging shows that within that toString method, writer is null

Here is the section that seems to be the problem:

public ServletOutputStream getOutputStream() throws IOException {
    if (getWriterCalled) {
      throw new IllegalStateException("getWriter already called");
    }

    getOutputStreamCalled = true;
    return super.getOutputStream();
  }

  public PrintWriter getWriter() throws IOException {
    if (writer != null) {
      return writer;
    }
    if (getOutputStreamCalled) {
      throw new IllegalStateException("getOutputStream already called");
    }
    getWriterCalled = true;
    writer = new PrintWriter(charWriter);
    return writer;
  }

  public String toString() {
    String s = null;

    if (writer != null) {
      s = charWriter.toString();
    }
    return s;
  }
}

The full code is here:

Filter that uses a response wrapper to convert all output to uppercase

As far as i know, servlet filter chain is invoked on HTTP request before it reaches the destination (for example - servlet). As you use Filter to get the content which is produced by a request destination point, you get null because it will exist only in future. But there is an adequate solution, mentioned in docs ( http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/Filter.html ). Just make so that your response wrapper decorated the access to the HttpServletResponse's content. For example - override the default writer with your custom, which will detect the letters and uppercase them at his write() method.

The page I was trying to filter was index.html .

It seems that the filter can only edit the response for a page ending in .jsp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM