freemarker依赖引入
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.21</version>
</dependency>
2.3.19不会报错
首先,在spring mvc框架中配置
<!-- FreeMarker -->
<bean
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"
p:templateLoaderPath="/WEB-INF/flt"
p:defaultEncoding="UTF-8">
<property name="freemarkerSettings">
<props>
<prop key="classic_compatible">true</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"
p:order="5"
p:suffix=".ftl"
p:contentType="text/html; charset=utf-8"/>
在/WEB-INF/下新建ftl文件. product.ftl
<#import "spring.ftl" as spring />
<html>
<head>
<title>产品列表</title>
</head>
<body>
产品列表
<table>
<#list productList as product>
<tr>
<td>
<a href="<@spring.url'/product/${product.logicId}.html'/>">${product.productName}</a>
</td>
<td>
${product.productValue}
</td>
</tr>
</#list>
</table>
</body>
</html>
接下来Controller中跳转到这个模板页
@RequestMapping("/showProductListByFlt.html")
public String showProductListByFlt(Product product,ModelMap model) throws Exception {
// 查询产品列表逻辑略
List<Product> productList = productService.findProList(product);
model.addAttribute("productList",productList);
return ("product");
}
由于xml配置了freemarker视图解析器的优先级, 所以会先跳转到product的ftl文件
接着条产品信息页面模板
@RequestMapping(value="/{logicId}")
public String showProduct(@PathVariable("logicId") String logicId,ModelMap model) throws Exception {
Product obj = new Product();
obj.setLogicId(logicId);
Product product = productService.getProductByLogicId(obj);
model.addAttribute("product",product);
return ("productDetail");
}