有没有办法从jsp文件中获取响应作为servlet内部的String。像
这样的东西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
答案 0 :(得分:18)
更好的解决方案可能是使用另一个模板引擎,如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>