下面是springmvc整合freemarker配置的详细步骤:
1.添加maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
2.配置springmvc
在springmvc配置文件中添加如下配置:
<!-- 开启注解支持 -->
<mvc:annotation-driven/>
<!-- 视图解析器 -->
<bean id="freeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".ftl"/>
</bean>
<!-- 模板配置 -->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/views/"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="url_escaping_charset">UTF-8</prop>
<prop key="tag_syntax">auto_detect</prop>
<prop key="whitespace_stripping">true</prop>
<prop key="classic_compatible">true</prop>
</props>
</property>
</bean>
3.创建Controller
创建一个Controller类,添加如下注解:
@Controller
public class MainController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home() {
ModelAndView mav = new ModelAndView();
mav.setViewName("index");
mav.addObject("greeting", "Hello World");
return mav;
}
}
4.编写FreeMarker模板
在/WEB-INF/views/目录下创建index.ftl文件,添加如下内容:
<!DOCTYPE html>
<html>
<head>
<title>SpringMVC and FreeMarker Integration</title>
</head>
<body>
<h2>${greeting}</h2>
</body>
</html>
5.运行应用程序
现在,我们已经完成了整合,可以运行应用程序并在浏览器中输入URL http://localhost:8080/,即可看到输出的“Hello World”消息。
下面给出另外一种示例,其中使用了Freemarker的一些高级特性:
6.Freemarker模板继承
base.ftl:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>${page.title}</title>
<link rel="stylesheet" href="${page.css}">
<script src="${page.js}"></script>
</head>
<body>
<header>
<h1>My Site</h1>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<article>
<!-- 子模板在这里添加内容 -->
<#nested/>
</article>
<footer>
© 2021 My Site
</footer>
</body>
</html>
index.ftl:
<#import "base.ftl" as layout>
<#macro pageTitle>
Home
</#macro>
<#macro content>
<h2>Welcome to My Site</h2>
<p>This is the home page of my site.</p>
</#macro>
<@layout.page>
<@layout.content/>
</@layout.page>
使用Freemarker标签:
<#if accountList?size gt 0>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<#list accountList as account>
<tr>
<td>${account.id}</td>
<td>${account.name}</td>
<td>${account.balance}</td>
</tr>
</#list>
</tbody>
</table>
<#else>
<p>No accounts found.</p>
</#if>
这是使用Freemarker标签的示例,其中<#if>和<#list>标签用于条件判断和迭代列表等操作。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:springmvc整合freemarker配置的详细步骤 - Python技术站