Getting template text from FreeMarker in Struts2 app

亡梦爱人 提交于 2019-12-31 05:33:07

问题


I would like to generate email inside a Struts2 application, using Freemarker. As I am also using Freemarker for my view, I would like to "reuse" the same config.

There is already a similar question for doing the same thing with Spring. Getting template text from FreeMarker in Spring app

I am not sure where to start.

I am looking at the code of org.apache.struts2.components.template.FreemarkerTemplateEngine. Should I replicate it ? or simply call it ? I am unclear on how to get back the rendered text.


回答1:


Something like this should do,

import com.opensymphony.xwork2.ActionSupport;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.StringWriter;

import javax.servlet.ServletContext;

import org.apache.struts2.util.ServletContextAware;
import org.apache.struts2.views.freemarker.FreemarkerManager;

public class DummyAction extends ActionSupport implements ServletContextAware
{
    private static final long serialVersionUID = 1L;
    private ServletContext context;

    public String execute()
    {
        try
        {
            //retrive freemarker config used by struts2 for freemarker results
            FreemarkerManager manager = new FreemarkerManager();
            Configuration cfg = manager.getConfiguration(context);
            Template template = cfg.getTemplate("your-template");

            //your data model
            Object root = new Object();

            //process template
            StringWriter out = new StringWriter();
            template.process(new Object(), out);

            String renderedText= out.toString();

            System.out.println(renderedText);

        } catch (Exception e)
        {
            e.printStackTrace();
        }

        //do work



        return "success?";
    }

    public void setServletContext(ServletContext context)
    {
        this.context = context;
    }
}


来源:https://stackoverflow.com/questions/3985373/getting-template-text-from-freemarker-in-struts2-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!