Getting template text from FreeMarker in Struts2 app

百般思念 提交于 2019-12-02 10:51:05

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