将ServletOutputStream读取到String

时间:2012-03-11 15:35:11

标签: java concurrency freemarker

我正在尝试阅读FreemarkerView渲染的结果:

View view = viewResolver.resolveViewName(viewName, locale);
view.render(model, request, mockResponse);

为了读取结果,我创建了mockResponse,它封装了HttpServletResponse:

public class HttpServletResponseEx extends HttpServletResponseWrapper {

    ServletOutputStream outputStream;

    public HttpServletResponseEx(HttpServletResponse response) throws IOException {
        super(response);
        outputStream = new ServletOutputStreamEx();
    }

    @Override
    public ServletOutputStream getOutputStream() {
        return outputStream;
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"));
    }
}

还有我的ServletOutputStream,它使用StringBuilder构建String:

public class ServletOutputStreamEx extends ServletOutputStream {

    StringBuilder stringBuilder;

    public ServletOutputStreamEx() {
        this.stringBuilder = new StringBuilder();
    }

    @Override
    public void write(int b) throws IOException {
    } 

    @Override
    public void write(byte b[], int off, int len) throws IOException {
        stringBuilder.append(new String(b, "UTF-8"));
    }

    @Override
    public String toString() {
        return stringBuilder.toString();
    }
}

通过方法ServletOutputStreamEx.toString,我可以轻松阅读回复。

我的问题是没有按正确的顺序调用write方法,最终String 混合而且顺序不正确。这可能是由Freemarker中的并发引起的,但我不知道如何修复它。

1 个答案:

答案 0 :(得分:4)

感谢您的回复:write(int b)未实施,因为它从未被调用过。最后的问题是字节数​​组,它也包含前一个字符串。所以String需要创建为String(b, off, len, "UTF-8")