简单环境搭建之第三部分,加入freemaker
一.pom.xml加入
<span style="white-space:pre"> </span><dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
二.spring-servlet.xml文件加入
<!-- 针对freemarker的视图配置 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="false" />
<property name="contentType" value="text/html;charset=UTF-8"></property>
<property name="requestContextAttribute" value="request" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
</bean>
<!-- freemaker配置 -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/viewsftl/" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="number_format">0.##########</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="classic_compatible">true</prop>
<prop key="template_exception_handler">ignore</prop>
</props>
</property>
</bean>
这里需要注意的问题:
三. 测试ftl是否能正常显示
controller代码:
package com.template.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
public class TemplateController {
@RequestMapping(value="/index",method=RequestMethod.GET)
public ModelAndView getFirstPage() {
ModelAndView mv = new ModelAndView();
mv.setViewName("template.ftl");
mv.addObject("name", "王大锤");
return mv;
}
}
ftl代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>模板页标题</title>
</head>
<body>
名字: ${name}
</body>
</html>
注意:这里有几个地方设置了UTF-8编码
1:首先项目新建的时候就会设置属性编码,你要保证每个文件的编码格式统一,可以右键文件查看下
2:在web.xml文件里设置了encoding filter
3:freemaker配置文件里设置了contentType属性
4:网页文件里也加了charset