【问题标题】:Struts2 - How can I get the result of a JSP page as a string in an action class (for emails)Struts2 - 如何将 JSP 页面的结果作为操作类中的字符串获取(用于电子邮件)
【发布时间】:2014-11-14 04:39:42
【问题描述】:

我想同时实现这两件事。

我在 Struts2 中有一个常规的 jsp 页面。 xx/yy/zz/email.jsp

<html>
<head>
</head>
<body>
    <s:property value="email"/>
</body>
</html>

这个页面的url可以是xx/yy/zz/myEmail.action,而一些action类会处理它...

public class MyEmailAction {
    private String email;
    public String execute(){
        this.email = 'abc@xyz.com''
    }
    //setter and getter for 'email'
    ......
}

现在,我想做另一个动作,将 xx/yy/zz/myEmail.action 页面的结果作为电子邮件发送。

public class MyEmailAction {
    private String email;
    public String execute(){
        this.email = 'abc@xyz.com''
    }

    public String send() {
        this.email = 'abc@xyz.com''
        Map mapping;
        //put this.email into the mapping
        String result = getResultOfJSP('../../../xx/yy/zz/email.jsp', mapping);
        Email.send('me@me.com', 'you@you.com', 'My Subject', result);
    }
    //setter and getter for 'email'
    ......
}

所以问题是:如何将渲染的 JSP 的结果作为字符串获取?

我想要这个的原因显然是我想在一个地方管理这个模板(email.jsp)。

我知道我可以使用另一个速度 (vm) 页面,它与 jsp 具有完全相同的 html,但使用速度标记。但是每当我需要对这个模板进行更改时,我都必须在两个地方都这样做。

我想我也可以使用 URL 来获取结果,但我不喜欢使用这种方式,因为它是对服务器的另一个请求。

谢谢

【问题讨论】:

    标签: java html jsp struts2 velocity


    【解决方案1】:

    我在使用邮件 servlet 时遇到了这个问题,使用它来获取 jsp 的结果作为字符串:

    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("email.jsp").include(request,
        responseWrapper);
    String result = responseWrapper.toString();
    

    设置邮箱给html内容:

    Email.send('me@me.com', 'you@you.com', 'My Subject', result);
    

    【讨论】:

      【解决方案2】:

      这不是您问题的答案,但我建议您考虑使用模板引擎来撰写您的电子邮件,例如 Velocity 或 Jelly

      http://velocity.apache.org/

      http://commons.apache.org/proper/commons-jelly/

      通过这种方式,您可以将模板组合为 HTML 或 XML,并在其中注入您的逻辑可能检索到的任何相关数据(甚至某些逻辑集成在它们自己的模板语言中,例如 if-then-else 或 while-loop 结构) .

      在渲染完整 JSP 完全必要的最坏情况下,您可以破解一些东西

      RequestDispatcher::include

      你可以从你的 MyEmailAction 中执行这个方法,但是传递一个被黑的 ServletResponse。这将是您实现 ServletResponse 编写的某个类...但将结果写入一些 ByteArrayOutputStream。页面呈现后(在您的假 ServletResponse 上),您可以从那里检索它(实际上使用 servlet 容器作为您自己的模板引擎)

      【讨论】:

      • 实际上 izzipod5 的回答看起来是实现我所说的完美方式:)
      猜你喜欢
      • 1970-01-01
      • 2013-08-11
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多