404 Not Found


nginx/1.24.0
404 Not Found

404 Not Found


nginx/1.24.0
首页 > 介绍 > 技术

FreeMarker自定义指令封装

2015-10-21 10:55:56 阅读:loading...

BaseDirective自定义指令基类,编写自定义指令时需要集成此类

package com.sanluan.common.base;
 
import java.io.IOException;
import java.util.Map;
 
import com.sanluan.common.handler.DirectiveHandler;
 
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
 
public abstract class BaseDirective implements TemplateDirectiveModel {
 
    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment environment, @SuppressWarnings("rawtypes") Map parameters, TemplateModel[] loopVars,
            TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        execute(new DirectiveHandler(environment, parameters,loopVars, templateDirectiveBody));
    }
 
    public abstract void execute(DirectiveHandler handler) throws TemplateException, IOException;
}

DirectiveHandler操作封装类,这个类主要封装了指令参数的获取,数据模型的填充与回收,简化指令逻辑操作

package com.sanluan.common.handler;
 
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
import org.apache.commons.lang3.StringUtils;
 
import freemarker.core.Environment;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateDateModel;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateHashModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;
import freemarker.template.TemplateScalarModel;
 
public class DirectiveHandler {
    public static final DateFormat FULL_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final int FULL_DATE_LENGTH = 19;
 
    public static final DateFormat SHORT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    public static final int SHORT_DATE_LENGTH = 10;
    private Environment environment;
    private Map<String, TemplateModel> parameters;
    private TemplateModel[] loopVars;
    private TemplateDirectiveBody templateDirectiveBody;
    private Map<String, Object> map = new HashMap<String, Object>();
 
    /**
     * @param environment
     * @param parameters
     * @param templateDirectiveBody
     */
    public DirectiveHandler(Environment environment, Map<String, TemplateModel> parameters, TemplateModel[] loopVars,
            TemplateDirectiveBody templateDirectiveBody) {
        this.environment = environment;
        this.loopVars = loopVars;
        this.parameters = parameters;
        this.templateDirectiveBody = templateDirectiveBody;
    }
 
    /**
     * 渲染
     * 
     * @param templateDirectiveBody
     * @throws IOException
     * @throws TemplateException
     */
    public void render() throws IOException, TemplateException {
        Map<String, TemplateModel> reduceMap = reduce();
        if (null != templateDirectiveBody)
            templateDirectiveBody.render(environment.getOut());
        reduce(reduceMap);
    }
 
    /**
     * 控制变量不为空时,导出所有变量
     * 
     * @param map
     * @param notEmptyObject
     * @throws IOException
     * @throws TemplateException
     */
    public void renderIfNotNull(Object notEmptyObject) throws IOException, TemplateException {
        if (null != notEmptyObject) {
            render();
        }
    }
 
    /**
     * 打印变量
     * 
     * @param str
     * @throws IOException
     * @throws TemplateException
     */
    public void print(String str) throws IOException, TemplateException {
        environment.getOut().append(str);
    }
 
    /**
     * @param key
     * @param value
     * @return
     */
    public DirectiveHandler put(String key, Object value) {
        map.put(key, value);
        return this;
    }
 
    /**
     * @return
     * @throws TemplateModelException
     */
    private Map<String, TemplateModel> reduce() throws TemplateModelException {
        Map<String, TemplateModel> reduceMap = new HashMap<String, TemplateModel>();
        for (String key : map.keySet()) {
            TemplateModel value = environment.getVariable(key);
            if (null != value)
                reduceMap.put(key, environment.getVariable(key));
            environment.setVariable(key, environment.getObjectWrapper().wrap(map.get(key)));
        }
        return reduceMap;
    }
 
    /**
     * @param map
     * @throws TemplateModelException
     */
    private void reduce(Map<String, TemplateModel> map) throws TemplateModelException {
        for (String key : map.keySet()) {
            environment.setVariable(key, map.get(key));
        }
    }
 
    /**
     * @param name
     * @return
     * @throws TemplateModelException
     */
    public TemplateHashModel getMap(String name) throws TemplateModelException {
        TemplateModel model = parameters.get(name);
        if (null == model) {
            return null;
        }
        if (model instanceof TemplateHashModelEx) {
            return (TemplateHashModelEx) model;
        } else if (model instanceof TemplateHashModel) {
            return (TemplateHashModel) model;
        } else {
            return null;
        }
    }
 
    /**
     * @param name
     * @param defaultValue
     * @return
     * @throws TemplateException
     */
    public String getString(String name, String defaultValue) throws TemplateException {
        String result = getString(name);
        if (null == result)
            return defaultValue;
        else
            return result;
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public String getString(String name) throws TemplateException {
        TemplateModel model = parameters.get(name);
        if (null == model) {
            return null;
        }
        if (model instanceof TemplateScalarModel) {
            return ((TemplateScalarModel) model).getAsString();
        } else if ((model instanceof TemplateNumberModel)) {
            return ((TemplateNumberModel) model).getAsNumber().toString();
        } else {
            return null;
        }
    }
 
    /**
     * @param name
     * @param defaultValue
     * @return
     * @throws TemplateException
     */
    public Integer getInteger(String name, int defaultValue) throws TemplateException {
        Integer result = getInteger(name);
        if (null == result)
            return defaultValue;
        else
            return result;
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public Integer getInteger(String name) throws TemplateException {
        TemplateModel model = parameters.get(name);
        if (null == model) {
            return null;
        }
        if (model instanceof TemplateNumberModel) {
            return ((TemplateNumberModel) model).getAsNumber().intValue();
        } else if (model instanceof TemplateScalarModel) {
            String s = ((TemplateScalarModel) model).getAsString();
            if (StringUtils.isBlank(s)) {
                return null;
            }
            try {
                return Integer.parseInt(s);
            } catch (NumberFormatException e) {
                return null;
            }
        } else {
            return null;
        }
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public Short getShort(String name) throws TemplateException {
        TemplateModel model = parameters.get(name);
        if (null == model) {
            return null;
        }
        if (model instanceof TemplateNumberModel) {
            return ((TemplateNumberModel) model).getAsNumber().shortValue();
        } else if (model instanceof TemplateScalarModel) {
            String s = ((TemplateScalarModel) model).getAsString();
            if (StringUtils.isBlank(s)) {
                return null;
            }
            try {
                return Short.parseShort(s);
            } catch (NumberFormatException e) {
                return null;
            }
        } else {
            return null;
        }
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public Long getLong(String name) throws TemplateException {
        TemplateModel model = parameters.get(name);
        if (null == model) {
            return null;
        }
        if (model instanceof TemplateNumberModel) {
            return ((TemplateNumberModel) model).getAsNumber().longValue();
        } else if (model instanceof TemplateScalarModel) {
            String s = ((TemplateScalarModel) model).getAsString();
            if (StringUtils.isBlank(s)) {
                return null;
            }
            try {
                return Long.parseLong(s);
            } catch (NumberFormatException e) {
                return null;
            }
        } else {
            return null;
        }
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public Double getDouble(String name) throws TemplateException {
        TemplateModel model = parameters.get(name);
        if (null == model) {
            return null;
        }
        if (model instanceof TemplateNumberModel) {
            return ((TemplateNumberModel) model).getAsNumber().doubleValue();
        } else if (model instanceof TemplateScalarModel) {
            String s = ((TemplateScalarModel) model).getAsString();
            if (StringUtils.isBlank(s)) {
                return null;
            }
            try {
                return Double.parseDouble(s);
            } catch (NumberFormatException e) {
                return null;
            }
        } else {
            return null;
        }
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public Integer[] getIntegerArray(String name) throws TemplateException {
        String[] arr = getStringArray(name);
        if (null != arr) {
            Integer[] ids = new Integer[arr.length];
            int i = 0;
            try {
                for (String s : arr) {
                    ids[i++] = Integer.valueOf(s);
                }
                return ids;
            } catch (NumberFormatException e) {
                return null;
            }
        } else
            return null;
 
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public Long[] getLongArray(String name) throws TemplateException {
        String[] arr = getStringArray(name);
        if (null != arr) {
            Long[] ids = new Long[arr.length];
            int i = 0;
            try {
                for (String s : arr) {
                    ids[i++] = Long.valueOf(s);
                }
                return ids;
            } catch (NumberFormatException e) {
                return null;
            }
        } else
            return null;
 
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public String[] getStringArray(String name) throws TemplateException {
        String str = getString(name);
        if (StringUtils.isBlank(str)) {
            return null;
        }
        return StringUtils.split(str, ',');
    }
 
    /**
     * @param name
     * @param defaultValue
     * @return
     * @throws TemplateException
     */
    public Boolean getBoolean(String name, Boolean defaultValue) throws TemplateException {
        Boolean result = getBoolean(name);
        if (null == result)
            return defaultValue;
        else
            return result;
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public Boolean getBoolean(String name) throws TemplateException {
        TemplateModel model = parameters.get(name);
        if (null == model) {
            return null;
        }
        if (model instanceof TemplateBooleanModel) {
            return ((TemplateBooleanModel) model).getAsBoolean();
        } else if (model instanceof TemplateNumberModel) {
            return !(0 == ((TemplateNumberModel) model).getAsNumber().intValue());
        } else if (model instanceof TemplateScalarModel) {
            String s = ((TemplateScalarModel) model).getAsString();
            if (StringUtils.isNotBlank(s)) {
                return !("0".equals(s) || "false".equalsIgnoreCase(s));
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
 
    /**
     * @param name
     * 
     * @return
     * @throws TemplateException
     */
    public Date getDate(String name) throws TemplateException {
        TemplateModel model = parameters.get(name);
        if (null == model) {
            return null;
        }
        if (model instanceof TemplateDateModel) {
            return ((TemplateDateModel) model).getAsDate();
        } else if (model instanceof TemplateScalarModel) {
            String temp = StringUtils.trimToEmpty(((TemplateScalarModel) model).getAsString());
            try {
                if (FULL_DATE_LENGTH == temp.length()) {
                    return FULL_DATE_FORMAT.parse(temp);
                } else if (SHORT_DATE_LENGTH == temp.length()) {
                    return SHORT_DATE_FORMAT.parse(temp);
                } else {
                    return null;
                }
            } catch (ParseException e) {
                return null;
            }
        } else {
            return null;
        }
    }
 
    /**
     * @return the parameters
     */
    public Map<String, TemplateModel> getParameters() {
        return parameters;
    }
 
    /**
     * @return the environment
     */
    public Environment getEnvironment() {
        return environment;
    }
 
    /**
     * @return the templateDirectiveBody
     */
    public TemplateDirectiveBody getTemplateDirectiveBody() {
        return templateDirectiveBody;
    }
 
    public TemplateModel[] getLoopVars() {
        return loopVars;
    }
 
    public void setLoopVars(TemplateModel[] loopVars) {
        this.loopVars = loopVars;
    }
}

CmsCategoryListDirective示例

package com.publiccms.views.directive.cms;
 
// Generated 2015-5-10 17:54:56 by SourceMaker
 
import java.io.IOException;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import com.publiccms.logic.service.cms.CmsCategoryService;
import com.sanluan.common.base.BaseDirective;
import com.sanluan.common.handler.PageHandler;
import com.sanluan.common.handler.DirectiveHandler;
import freemarker.template.TemplateException;
 
@Component
public class CmsCategoryListDirective extends BaseDirective {
 
    @Override
    public void execute(DirectiveHandler handler) throws TemplateException, IOException {
        PageHandler page = service.getPage(handler.getInteger("parentId"), handler.getString("extend1"),
                handler.getString("name"), handler.getBoolean("disabled", false), handler.getInteger("pageIndex", 1),
                handler.getInteger("count", 30));
        handler.put("page", page).render();
    }
 
    @Autowired
    private CmsCategoryService service;
 
}


标签:PublicCMS
上一页 1 下一页
404 Not Found

404 Not Found


nginx/1.24.0