gpt4 book ai didi

java - 如何替换 HttpServletResponse 输出流?

转载 作者:行者123 更新时间:2023-11-28 22:41:32 25 4
gpt4 key购买 nike

我需要使用 JSP 生成 HTML 报告。我做了一个例子,但是目前它在 Tomcat6 中不起作用。

public class SubstitutionServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/report.jsp");
final ByteArrayOutputStream buf = new ByteArrayOutputStream();
ServletResponseWrapper wrapper = new HttpServletResponseWrapper(response){
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(buf);
}
};
dispatcher.forward(request, wrapper);
String html = buf.toString("UTF-8"); // "" is returned
System.out.println(html);
response.getOutputStream().print("Completed");
}
}

当我尝试运行这个示例时,结果是一个空字符串。我犯了什么错误?

最佳答案

问题是您为方法 getWriter 的每次调用都创建了新的 PrintWriter。相反,您应该拥有一个并重复使用它。

public class SubstitutionServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/report.jsp");
final ByteArrayOutputStream buf = new ByteArrayOutputStream();
final PrintWriter out = new PrintWriter(buf); //CREATE ONLY ONE WRITER
ServletResponseWrapper wrapper = new HttpServletResponseWrapper(response) {
@Override
public PrintWriter getWriter() throws IOException {
return out; // REUSE WRITER
}
};
dispatcher.forward(request, wrapper);
String html = buf.toString("UTF-8"); // "" is returned
System.out.println(html);
response.getOutputStream().print("Completed");
}
}

关于java - 如何替换 HttpServletResponse 输出流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32198656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com