刚在自己的项目中添加了freemarker支持
1、为了支持freemarker,添加了两个jar包 spring-context-support-3.2.0.M1.jar (http://www.findjar.cn/showjar.x?id=697) com.springsource.freemarker-2.3.18.jar (http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.freemarker&version=2.3.18)
2、添加freemarker.properties
tag_syntax=auto_detect
template_update_delay=2
default_encoding=UTF-8
output_encoding=UTF-8
locale=zh_CN
date_format=yyyy-MM-dd
time_format=HH:mm:ss
datetime_format=yyyy-MM-dd HH:mm:ss
3、配置springmvc-servlet.xml 加入如下配置,必须加在jsp解析器之前
<!-- ***********************freemarker 配置 start ********************** --> <!-- 设置freeMarker的配置文件路径 --> <bean id="freemarkerConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:freemarker.properties"/> </bean> <!-- 配置freeMarker的模板路径 --> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath"> <value>/WEB-INF/ftl/</value> </property> <property name="freemarkerVariables"> <map> <entry key="xml_escape" value-ref="fmXmlEscape" /> </map> </property> </bean> <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/> <!-- 配置freeMarker视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="cache" value="true"/> <property name="prefix" value="/"/> <property name="suffix" value=".ftl"/> <property name="contentType" value="text/html; charset=UTF-8"/> </bean> <!-- ***********************freemarker 配置 end ********************** -->
4、添加一个控制器类
package com.frame.application.admin.modules.demo; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; /** * FreeMarker示例控制器 * @author Tandaly * @date 2013-3-7 上午9:29:57 */ @Controller @RequestMapping("/freeMarker") public class FreeMarkerController { @RequestMapping("/hello") public String sayHello(ModelMap map) { System.out.println("say Hello ……"); map.addAttribute("name", " World!"); return "hello"; } @RequestMapping("/hi") public String sayHi(ModelMap map) { System.out.println("say hi ……"); map.put("name", "jojo"); return "hi"; } @RequestMapping("/jsp") public String jspRequest(ModelMap map) { System.out.println("jspRequest ……"); map.put("name", "jsp"); return "system/login"; } }
5、在WEB-INF下新建一个用于存放ftl文件的目录并增加两个测试文件
hello.ftl
<html>
<body>
<h1>say hello ${name}</h1><br/>
${(1 == 1)?string("yes", "no")}
</body>
</html>
hi.ftl
<html> <body> <h1>say hello ${name}</h1><br/> ${(1 != 1)?string("yes", "no")} </body> </html>