HttpServletResponseWrapper 中的 getOutputStream 被多次调用 [英] getOutputStream in HttpServletResponseWrapper getting called multiple times

查看:143
本文介绍了HttpServletResponseWrapper 中的 getOutputStream 被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用 servlet 过滤器在返回响应之前将字符串注入到响应中.我们正在使用 HttpServletResponseWrapper 的实现来做到这一点.从`doFilter() 方法调用包装类:

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

来自我们 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;
}

在某些服务器实例中,stream.write(s.getBytes()) 方法导致 getOutputStream() 方法被多次调用.这会导致在响应中多次注入字符串.

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.

jsp 显示最终输出时,该字符串在 UI 中出现多次.

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

我们使用的是 WebLogic Server 11g.

We are using WebLogic Server 11g.

推荐答案

所以你做错了.getOutputStream() 被多次调用是完全可以的,只要 getWriter() 没有被调用.您应该通过将输出流作为单例进行管理来注入字符串一次:

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

这篇关于HttpServletResponseWrapper 中的 getOutputStream 被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆