getOutputStream in HttpServletResponseWrapper getting called multiple times

这一生的挚爱 提交于 2021-02-08 10:21:05

问题


We are using a servlet filter to inject a string into the response before returning it. We are using an implementation of HttpServletResponseWrapper to do this. The wrapper class is called from the `doFilter() method:

chain.doFilter(request, responseWrapper);

The code snipppet from our ResponseWrapper class is:

@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;
}

In some server instances the stream.write(s.getBytes()) method causes the getOutputStream() method getting called multiple times. This causes the string getting injected multiple times in the response.

When the final output is displayed by the jsp, the string appears multiple times in the UI.

We are using WebLogic Server 11g.


回答1:


So you're doing it wrong. It is perfectly OK for getOutputStream() to be called multiple times, as long as getWriter() hasn't been called. You should inject the string once, by managing your output stream as a singleton:

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;
}


来源:https://stackoverflow.com/questions/29713767/getoutputstream-in-httpservletresponsewrapper-getting-called-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!