简体   繁体   English

Servlet过滤器坚持没有响应文本

[英]Servlet filter insists that there's no response text

My filter is supposed to edit the HTML of a response. 我的过滤器应该用于编辑响应的HTML。 But when I navigate to a page it does nothing because 但是,当我导航到页面时,它什么都不做,因为

newResponse.toString();

returns null . 返回null

Further debugging shows that within that toString method, writer is null 进一步的调试显示,在该toString方法中, writernull

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). 据我所知,servlet过滤器链到达目的地之前 (例如-servlet)在HTTP请求上被调用。 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. 当您使用筛选器获取由请求目标点生成的内容时,您将获得null因为它仅在将来存在。 But there is an adequate solution, mentioned in docs ( http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/Filter.html ). 但是有一个适当的解决方案,在文档( 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. 进行适当的设置,以便您的响应包装器装饰对HttpServletResponse内容的访问。 For example - override the default writer with your custom, which will detect the letters and uppercase them at his write() method. 例如-用您的自定义覆盖默认的writer,它将检测字母并在他的write()方法中将它们大写。

The page I was trying to filter was index.html . 我试图过滤的页面是index.html

It seems that the filter can only edit the response for a page ending in .jsp . 看来过滤器只能编辑以.jsp结尾的页面的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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