Reading ServletOutputStream to String

99封情书 提交于 2019-12-22 06:27:45

问题


I am trying to read the result of FreemarkerView rendering:

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

To read the result, I have created mockResponse, which encapsulates the 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"));
    }
}

And also my ServletOutputStream, which builds the String using StringBuilder:

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

With those I am able to easily read the response with method ServletOutputStreamEx.toString.

My problem is that the write method is not called in correct order and in the end the final String is mixed and not in correct order. This is probably caused by concurrency in Freemarker, but I have no idea how to fix it.


回答1:


Thanks for the responses: the write(int b) was not implemented, because it is never called. The problem in the end is the byte array, which also contains the previous String. So the String needs to be created as String(b, off, len, "UTF-8").



来源:https://stackoverflow.com/questions/9656295/reading-servletoutputstream-to-string

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