这可能有点令人困惑,但我遇到了一些麻烦。我的目标是获取输入的 HTML 文档,然后处理该文档并使用 HTML 数据输出图像文档。例如,用户将请求一个 URL,在查询字符串中包含一些 action=png,然后将为 URL 调用过滤器并输出图像文档。
我已经尝试了一切,但在我的环境(Websphere)中,我只能输出一种类型。如果输入类型是 text/html 那么我只能输出一个文本文档,我似乎不能输出一个二进制文档。为什么?因为我每次都得到一个非法的状态异常。
[1/29/09 17:59:57:576 EST] 00000020 SystemErr R java.lang.IllegalStateException: SRVE0209E: Writer 已经获得 [1/29/09 17:59:57:576 EST] 00000020 SystemErr R at com。 ibm.ws.webcontainer.srt.SRTServletResponse.getOutputStream(SRTServletResponse.java:505)
我使用伪代码不显示我的所有代码:
<filter>
<filter-name>TestFilter</filter-name>
<filter-class>
com.util.TestFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>TestFilter</filter-name>
<url-pattern>/index_test2.html</url-pattern>
</filter-mapping>
Wrapper 类的代码本质上是这样的:
public class ContentCaptureServletResponse extends HttpServletResponseWrapper {
private ByteArrayOutputStream contentBuffer;
private PrintWriter writer;
public PrintWriter getWriter() throws IOException {
if (writer == null) {
contentBuffer = new ByteArrayOutputStream();
writer = new PrintWriter(contentBuffer);
}
return writer;
}
public String getContent(){
try {
writer = getWriter();
} catch (IOException e) {
e.printStackTrace();
}
writer.flush();
String xhtmlContent = new String(contentBuffer.toByteArray());
System.out.println(xhtmlContent);
return xhtmlContent;
}
}
过滤器代码是这样的:
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
final String renderType = request.getParameter("R");
final String renderClassName = request.getParameter("C");
if ((renderType != null) && (renderClassName != null)) {
try {
this.setFilterChain(filterChain);
response.setContentType("image/png");
PrintWriter out = response.getWriter();
// I call getWriter but not BOTH!
//response.getOutputStream();
response.getWriter();
// Build up the HTML document into a string.
CaptureResponse capContent = new CaptureResponse(response);
this.mainFilterChain.doFilter(req, );
String myString = capHtmlContent.getContent();
// What I really want to do here is output an output stream
// so I can write a binary image
processStr(myString);
response.getOutputStream();
response.write(binaryimage)
} catch (Exception e) {
e.printStackTrace();
}
// No data will be output to the user.
} else {
filterChain.doFilter(request, response);
} // End of if-else
} // End of the method.
如果我想获取一些输入的 html 文本文档,则该代码有效。我假设是因为打开了 printwriter 流。但是我在使用不同的格式时遇到了麻烦。基本上,因为我不能调用 response.getOutputStream()