Java HttpServletResponseWrapper中的getOutputStream被多次调用
我们使用servlet过滤器在返回响应之前将字符串注入响应。我们正在使用Java HttpServletResponseWrapper中的getOutputStream被多次调用,java,servlets,servlet-filters,outputstream,weblogic11g,Java,Servlets,Servlet Filters,Outputstream,Weblogic11g,我们使用servlet过滤器在返回响应之前将字符串注入响应。我们正在使用HttpServletResponseWrapper的一个实现来实现这一点。包装器类是从`doFilter()方法调用的: 我们的ResponseWrapper类中的代码snipppet是: @Override public ServletOutputStream getOutputStream() throws IOException { String theString = "someString"; // Get a
HttpServletResponseWrapper
的一个实现来实现这一点。包装器类是从`doFilter()方法调用的:
我们的ResponseWrapper
类中的代码snipppet是:
@Override
public ServletOutputStream getOutputStream()
throws IOException
{
String theString = "someString";
// Get a reference to the superclass's outputstream.
ServletOutputStream stream = super.getOutputStream();
// Create a new string with the proper encoding as defined
// in the server.
String s = new String(theString.getBytes(), 0, theString.length(), response.getCharacterEncoding());
// Inject the string
stream.write(s.getBytes());
return stream;
}
在某些服务器实例中,stream.write(s.getBytes())
方法导致多次调用getOutputStream()
方法。这会导致字符串在响应中被多次注入
当jsp显示最终输出时,该字符串在UI中出现多次
我们使用的是WebLogic Server 11g。所以您做错了。只要没有调用
getWriter()
,多次调用getOutputStream()
是完全可以的。您应该通过将输出流作为单例管理来注入字符串一次:
ServletOutputStream outputStream; // an instance member of your Wrapper
@Override
public synchronized ServletOutputStream getOutputStream()
throws IOException
{
if (outputStream == null)
{
outputStream = super.getOutputStream();
outputStream.write(/*your injected stuff*/);
}
return outputStream;
}
谢谢我们将尝试此解决方案
ServletOutputStream outputStream; // an instance member of your Wrapper
@Override
public synchronized ServletOutputStream getOutputStream()
throws IOException
{
if (outputStream == null)
{
outputStream = super.getOutputStream();
outputStream.write(/*your injected stuff*/);
}
return outputStream;
}