Spring+Freemarker实现自定义方法

来源:互联网 发布:apm2.8飞控源码 编辑:程序博客网 时间:2024/05/16 00:44

配置文件test.properties中添加Freemarker相关配置信息

locale=zh_TW  url_escaping_charset=UTF-8  message.cache_seconds=3600  message.common_path=/WEB-INF/language/message #------------ Template ------------template.encoding=UTF-8template.update_delay=3600template.number_format=0.######template.boolean_format=true,falsetemplate.datetime_format=yyyy-MM-ddtemplate.date_format=yyyy-MM-ddtemplate.time_format=HH:mm:sstemplate.loader_path=/WEB-INF/template,classpath:/template.suffix=.ftl

在spring中进行freemarker相关配置

<!-- freemarker配置 -->    <bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">        <property name="templateLoaderPaths" value="${template.loader_path}" />        <property name="freemarkerSettings">            <props>                <prop key="defaultEncoding">${template.encoding}</prop>                <prop key="url_escaping_charset">${url_escaping_charset}</prop>                <prop key="locale">${locale}</prop>                <prop key="template_update_delay">${template.update_delay}</prop>                <prop key="tag_syntax">auto_detect</prop>                <prop key="whitespace_stripping">true</prop>                <prop key="classic_compatible">true</prop>                <prop key="number_format">${template.number_format}</prop>                <prop key="boolean_format">${template.boolean_format}</prop>                <prop key="datetime_format">${template.datetime_format}</prop>                <prop key="date_format">${template.date_format}</prop>                <prop key="time_format">${template.time_format}</prop>                <prop key="object_wrapper">freemarker.ext.beans.BeansWrapper</prop>            </props>        </property>        <property name="freemarkerVariables">            <map>                <entry key="message" value-ref="messageMethod" />            </map>        </property>    </bean>

模板实现国际化的方法,具体SpringUtils任何实现国际化在http://blog.csdn.net/snowcity1231/article/details/44152099

@Component("messageMethod")public class MessageMethod implements TemplateMethodModel {    @SuppressWarnings("rawtypes")    public Object exec(List arguments) throws TemplateModelException {        if (arguments != null && !arguments.isEmpty() && arguments.get(0) != null && StringUtils.isNotEmpty(arguments.get(0).toString())) {            String message = null;            String code = arguments.get(0).toString();            if (arguments.size() > 1) {                Object[] args = arguments.subList(1, arguments.size()).toArray();                message = SpringUtils.getMessage(code, args);            } else {                message = SpringUtils.getMessage(code);            }            return new SimpleScalar(message);        }        return null;    }}

编写模板文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Welcome!</title></head><body><h1>Welcome ${user}!</h1><p>Our latest product:<a href="${latestProduct.url}">${latestProduct.name}</a>!<p>${message("demo.test")}</p></body></html>



以下,将模板静态化成html界面即可

@Service("staticService")public class StaticServiceImpl implements IStaticService, ServletContextAware {private ServletContext servletContext;@Resource(name="freeMarkerConfigurer")private FreeMarkerConfig freeMarkerConfig;@Overridepublic void setServletContext(ServletContext servletContext) {this.servletContext = servletContext;}@Overridepublic void build() {                /* 创建数据模型 */                Map<String, Object> root = new HashMap<String, Object>();                root.put("user", "Big Joe");                Map<String, String> latest = new HashMap<String, String>();                root.put("latestProduct", latest);                latest.put("url", "products/greenmouse.html");                latest.put("name", "green mouse");FileOutputStream fileOutputStream = null;OutputStreamWriter outputStreamWriter = null;Writer writer = null;try {String staticPath = "/static/test.html";String templateFileName = "test.ftl";//String templateDir = "/WEB-INF/template";String templatePath = "/test.ftl";File originalFile = new File(servletContext.getRealPath(staticPath));if (originalFile.exists()) {originalFile.delete();}Template template = freeMarkerConfig.getConfiguration().getTemplate(templatePath);/*Configuration cfg = new Configuration();cfg.setDirectoryForTemplateLoading(new File(servletContext.getRealPath(templateDir)));cfg.setObjectWrapper(new DefaultObjectWrapper());Template template = cfg.getTemplate(templateFileName);*/File staticFile = new File(servletContext.getRealPath(staticPath));fileOutputStream = new FileOutputStream(staticFile);outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");writer = new BufferedWriter(outputStreamWriter);template.process(map, writer);writer.flush();System.out.println("-----静态化成功------:"+staticFile);} catch (Exception e) {e.printStackTrace();}}}




0 0