有没有办法从js内的String中获取来自jsp文件的响应。就像是
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String section1 = getResponseFromJSP(); // do something else ... sendMailToUser(section1); }
我正在使用Servlet API 2.4和Java 1.4
更好的解决方案可能是使用另一个模板引擎,例如freemarker或velocity,它们独立于servlet api,更适合于基于文本的电子邮件。
但是,这可以通过包装HttpServletResponse和覆盖getWriter方法来实现。以下代码对我适用于glassfish。
HttpServletResponse
getWriter
Servlet:
public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response) { private final StringWriter sw = new StringWriter(); @Override public PrintWriter getWriter() throws IOException { return new PrintWriter(sw); } @Override public String toString() { return sw.toString(); } }; request.getRequestDispatcher("test.jsp").include(request, responseWrapper); String content = responseWrapper.toString(); System.out.println("Output : " + content); response.getWriter().write(content); } }
JSP:
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Hello world</title> </head> <body> <h1><%= "Hello world from a JSP!" %></h1> </body> </html>