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.
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