我试图阅读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中的并发引起的,但我不知道如何修复它.
最佳答案
原文链接:https://www.f2er.com/java/438039.html