Spring+Freemarker实现自定义方法

配置文件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-8
template.update_delay=3600
template.number_format=0.######
template.boolean_format=true,false
template.datetime_format=yyyy-MM-dd
template.date_format=yyyy-MM-dd
template.time_format=HH:mm:ss
template.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;
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	

	@Override
	public 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();
		}
		

	}


}




转载于:https://www.cnblogs.com/snowcity1231/p/6714708.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值