spring mvc 集成freemarker模板
主要使用到的jar 文件:spring mvc +freemarker.jar
第一步:spring mvc 集成 freemarker
- <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
- <property name="prefix" value="/backstage/jsp/" />
- <property name="suffix" value=".jsp" />
- <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
- <property name="order" value="1"/>
- </bean>
- <!-- 配置freeMarker视图解析器 -->
- <bean id="viewResolverFtl" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
- <property name="contentType" value="text/html; charset=UTF-8"/>
- <property name="exposeRequestAttributes" value="true" />
- <property name="exposeSessionAttributes" value="true" />
- <property name="exposeSpringMacroHelpers" value="true" />
- <property name="cache" value="true" />
- <property name="suffix" value=".ftl" />
- <property name="order" value="0"/>
- </bean>
- <!-- 配置freeMarker的模板路径 -->
- <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
- <property name="templateLoaderPath" value="/backstage/jsp/"/>
- <property name="freemarkerVariables">
- <map>
- <entry key="xml_escape" value-ref="fmXmlEscape" />
- </map>
- </property>
- <property name="defaultEncoding" value="UTF-8"/>
- <property name="freemarkerSettings">
- <props>
- <prop key="template_update_delay">3600</prop>
- <prop key="locale">zh_CN</prop>
- <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
- <prop key="date_format">yyyy-MM-dd</prop>
- <prop key="number_format">#.##</prop>
- </props>
- </property>
- </bean>
- <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
【重点:在JSP和Freemarker的配置项中都有一个order property,上面例子是把freemarker的order设置为0,jsp为1。意思是找view时,先找ftl文件,再找jsp文件做为视图。】
第二步:controller代码
- package com.wlsq.controller;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.servlet.ModelAndView;
- @Controller
- @RequestMapping(value="/ftl")
- public class FreemarkerTest {
- @RequestMapping(value="/index",method=RequestMethod.GET)
- public ModelAndView index() {
- ModelAndView view = new ModelAndView("TestFreemarker/index");
- view.addObject("message", "Say hi for Freemarker.");
- return view;
- }
- }
第三步:TestFreemarker/index.ftl
- <Html>
- <head>
- <title>${message}</title>
- </head>
- <body>
- <b>${message}</b>
- <body>
- </html>