Struts2 Freemarker 整合

在basePackage中添加  生产静态页面

 <result-types>
    <result-type name="freemarker2File" class="com.joy.web.utils.FreemarkerResult"/>  
 </result-types>

在自己使用的package中添加
    <package name="content" extends="basePackage" namespace="/admin/content" >
        <action name="contentAction_*" class="com.joy.web.action.ContentAction" method="{1}" >
<!--        <result name="specialList" ></result>-->
            <result type="freemarker2File" name="specialList"  >
                <param name="location">test/freemarkertest.ftl</param> 显示使用模版
                <param name="contentType">text/html</param>生成文件类型
                <param name="fileName">${fileName}</param>生成文件名
                <param name="staticTemplate">test/freemarkertest2.ftl</param>生成静态页面模版
                <param name="filePath">static</param>生成静态文件路径
            </result>
        </action>




package com.joy.web.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale; 
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.apache.struts2.views.util.ResourceUtil; 
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack; 
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException; 
/**
 * struts2 返回类型封装 用于生产静态页面
 * @author fh
 *
 */
public class FreemarkerResult extends StrutsResultSupport { 
	private static final long serialVersionUID = 1L;
	protected ActionInvocation invocation;
    protected Configuration configuration;
    protected ObjectWrapper wrapper;
    protected FreemarkerManager freemarkerManager;
    private Writer writer;
    protected String location; //显示使用Freemarker模板
    private String pContentType = "text/html"; 
    protected String fileName; // 要生成的静态页面名称
    protected String filePath; // 要生成的静态页面的路径
    protected String staticTemplate; // 用于生成静态页面Freemarker模板的路径 
    public FreemarkerResult() {
        super();
    } 
    public FreemarkerResult(String location) {
        super(location);
    } 
    @Inject
    public void setFreemarkerManager(FreemarkerManager mgr) {
        this.freemarkerManager = mgr;
    } 
    public void setContentType(String aContentType) {
        pContentType = aContentType;
    } 
    public String getContentType() {
        return pContentType;
    } 
    public void doExecute(String location, ActionInvocation invocation)
            throws IOException, TemplateException {
        this.location = location;
        this.invocation = invocation;
        this.configuration = getConfiguration();
        this.wrapper = getObjectWrapper(); 
        this.fileName = (String) conditionalParse(fileName, invocation);
        this.staticTemplate = (String) conditionalParse(staticTemplate, invocation);
        this.filePath = ((String) conditionalParse(filePath, invocation)) == null ? "" : ((String) conditionalParse(filePath, invocation)); 
        if (!location.startsWith("/")) {
            ActionContext ctx = invocation.getInvocationContext();
            HttpServletRequest req = (HttpServletRequest) ctx
                    .get(ServletActionContext.HTTP_REQUEST);
//            String base = ResourceUtil.getResourceBase(req);
//            location = base + "/" + location;
        } 
        //生成html页面的模板类
        Template template = configuration.getTemplate(location, deduceLocale());
        // 生成静态页面的的模板类
        Template staticTemplate = configuration.getTemplate(this.staticTemplate,
                deduceLocale()); 
        TemplateModel model = createModel();
        String path = ServletActionContext.getServletContext().getRealPath(filePath)+ File.separator;
        
        File f = new File(path);
        if (!f.exists()) {
			f.mkdirs();
		}
        
        Writer out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(path + fileName))); 
        if (preTemplateProcess(template, model)) {
            try {
                staticTemplate.process(model, out);
                template.process(model, getWriter());
            } finally {
                postTemplateProcess(template, model);
                postTemplateProcess(staticTemplate, model);
            }
        }
    } 
    protected Configuration getConfiguration() throws TemplateException {
        return freemarkerManager.getConfiguration(ServletActionContext
                .getServletContext());
    } 
    protected ObjectWrapper getObjectWrapper() {
        return configuration.getObjectWrapper();
    } 
    public void setWriter(Writer writer) {
        this.writer = writer;
    } 
    protected Writer getWriter() throws IOException {
        if (writer != null) {
            return writer;
        }
        return ServletActionContext.getResponse().getWriter();
    } 
    protected TemplateModel createModel() throws TemplateModelException {
        ServletContext servletContext = ServletActionContext
                .getServletContext();
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        ValueStack stack = ServletActionContext.getContext().getValueStack(); 
        Object action = null;
        if (invocation != null)
            action = invocation.getAction(); // Added for NullPointException
        return freemarkerManager.buildTemplateModel(stack, action,
                servletContext, request, response, wrapper);
    } 
    protected Locale deduceLocale() {
        if (invocation.getAction() instanceof LocaleProvider) {
            return ((LocaleProvider) invocation.getAction()).getLocale();
        } else {
            return configuration.getLocale();
        }
    } 
    protected void postTemplateProcess(Template template, TemplateModel data)
            throws IOException {
    } 
    protected boolean preTemplateProcess(Template template, TemplateModel model)
            throws IOException {
        Object attrContentType = template.getCustomAttribute("content_type"); 
        if (attrContentType != null) {
            ServletActionContext.getResponse().setContentType(
                    attrContentType.toString());
        } else {
            String contentType = getContentType(); 
            if (contentType == null) {
                contentType = "text/html";
            } 
            String encoding = template.getEncoding(); 
            if (encoding != null) {
                contentType = contentType + "; charset=" + encoding;
            } 
            ServletActionContext.getResponse().setContentType(contentType);
        } 
        return true;
    } 
    public String getFileName() {
        return fileName;
    } 
    public void setFileName(String fileName) {
        this.fileName = fileName;
    } 
    public String getFilePath() {
        return filePath;
    } 
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    } 
    public String getStaticTemplate() {
        return staticTemplate;
    } 
    public void setStaticTemplate(String staticTemplate) {
        this.staticTemplate = staticTemplate;
    }
}







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值