Spring mvc整合FreeMarker,使用的是Spring mvc 3.2 + FreeMarker 2.3.19,如下所示:
1、新建freemarker.properties,放到src目录下面:
01 |
#设置标签类型:square_bracket:[] auto_detect:[]<> |
02 |
tag_syntax=auto_detect |
04 |
template_update_delay=0 |
05 |
default_encoding=UTF-8 |
11 |
classic_compatible= true |
12 |
#auto_import="/WEB-INF/templates/index.ftl" as do |
2、在spring配置文件中,加入如下内容:
01 |
<? xml version = "1.0" encoding = "UTF-8" ?> |
02 |
< beans xmlns = "http://www.springframework.org/schema/beans" |
03 |
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" |
04 |
xmlns:context = "http://www.springframework.org/schema/context" |
05 |
xmlns:mvc = "http://www.springframework.org/schema/mvc" |
07 |
http://www.springframework.org/schema/beans |
08 |
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd |
09 |
http://www.springframework.org/schema/context |
10 |
http://www.springframework.org/schema/context/spring-context-3.2.xsd |
11 |
http://www.springframework.org/schema/mvc |
12 |
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> |
14 |
<!-- 设置freeMarker的配置文件路径 --> |
15 |
< bean id = "freemarkerConfiguration" class = "org.springframework.beans.factory.config.PropertiesFactoryBean" > |
16 |
< property name = "location" value = "classpath:freemarker.properties" /> |
19 |
<!-- 配置freeMarker的模板路径 --> |
20 |
< bean class = "org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" > |
21 |
< property name = "freemarkerSettings" ref = "freemarkerConfiguration" /> |
22 |
< property name = "templateLoaderPath" > |
23 |
< value >/WEB-INF/</ value > |
27 |
<!-- 配置freeMarker视图解析器 --> |
28 |
< bean id = "viewResolver" class = "org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" > |
29 |
< property name = "viewClass" value = "org.springframework.web.servlet.view.freemarker.FreeMarkerView" /> |
30 |
< property name = "contentType" value = "text/html; charset=utf-8" /> |
31 |
< property name = "cache" value = "true" /> |
3、创建IndexController类,进行测试:
01 |
import javax.servlet.http.HttpServletRequest; |
03 |
import org.springframework.beans.factory.annotation.Autowired; |
04 |
import org.springframework.stereotype.Controller; |
05 |
import org.springframework.ui.Model; |
06 |
import org.springframework.web.bind.annotation.RequestMapping; |
07 |
import org.springframework.web.bind.annotation.RequestMethod; |
10 |
public class IndexController { |
12 |
@RequestMapping (value= "/" , method=RequestMethod.GET) |
13 |
public String index(HttpServletRequest request, Model model){ |
14 |
model.addAttribute( "user" , "张三" ); |
15 |
model.addAttribute( "date" , new Date()); |
16 |
return "page/index.html" ; |
4、新建:/WEB-INF/page/index.html
view sourceprint?
来源:oschina
链接:https://my.oschina.net/u/1261699/blog/212340