小编典典

以字符串形式在servlet中获取jsp响应

jsp

有没有办法从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


阅读 309

收藏
2020-06-08

共1个答案

小编典典

更好的解决方案可能是使用另一个模板引擎,例如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>
2020-06-08