更好的解决方案可能是使用另一个模板引擎,例如freemarker或velocity,它们独立于servlet api,更适合于基于文本的电子邮件。
但是,这可以通过包装
HttpServletResponse和覆盖
getWriter方法来实现。以下代码对我适用于glassfish。
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>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)