freemarker模板引擎的使用

时间:2022-12-12 22:46:57

  freemarker是一套前端模板引擎,在使用时,要先在web项目中添加freemarker.jar的依赖。

  我在这里主要演示spring-mvc整合freemarker模板引擎。项目案例的文件包结构示意图如下:

freemarker模板引擎的使用

  首先,在工程的web.xml文件中进行配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--配置前端控制器-->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!--配置编码格式为utf-8-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

  然后配置springmvc-config.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.itszt.controller"></context:component-scan> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="templateLoaderPath" value="/WEB-INF/templates/"></property>
</bean>
<!--spring-mvc整合freemarker-->
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property>
<property name="contentType" value="text/html;charset=UTF-8"></property>
<property name="suffix" value=".ftl"></property>
</bean>
</beans>

  网站首页如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="/testController/test1.html">test1</a>
<hr>
<a href="/testController/test2.html">test2</a>
<hr>
<a href="/testController/test3.html">test3</a>
<hr>
<a href="/testController/test4.html">test4</a>
<hr>
<a href="/testController/test5.html">test5</a>
<hr>
<a href="/testController/test6.html">test6</a>
<hr>
<a href="/testController/test7.html">test7</a>
<hr>
<a href="/testController/test8.html">test8</a>
<hr>
<a href="/testController/test9.html">test9</a>
</body>
</html>

  后台Java代码如下:

package com.itszt.domain;

import java.util.List;

/**
* 实体类
*/
public class User {
private String username,usersex;
private int userage;
private String nation,hometown;
private List<String> userhbs; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getUsersex() {
return usersex;
} public void setUsersex(String usersex) {
this.usersex = usersex;
} public int getUserage() {
return userage;
} public void setUserage(int userage) {
this.userage = userage;
} public String getNation() {
return nation;
} public void setNation(String nation) {
this.nation = nation;
} public String getHometown() {
return hometown;
} public void setHometown(String hometown) {
this.hometown = hometown;
} public List<String> getUserhbs() {
return userhbs;
} public void setUserhbs(List<String> userhbs) {
this.userhbs = userhbs;
}
}
-----------------------------------------------
package com.itszt.controller; import com.itszt.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*; /**
* 控制器
*/
@RequestMapping("testController")
@Controller
public class TestController {
@RequestMapping("test1")
public String test1(HttpServletRequest request, HttpSession session){
request.setAttribute("data1","dd");
request.setAttribute("data2","ff");
session.setAttribute("data3","vv");
return "hello";
} @RequestMapping("test2")
public String test2(Model model){
User user=new User();
user.setUsername("张三");
user.setUsersex("男");
user.setUserage(18);
user.setNation("汉族");
user.setHometown("中国北京市通州"); List<String> userhbs=new ArrayList<>();
userhbs.add("爬山");
userhbs.add("游泳");
userhbs.add("滑冰"); user.setUserhbs(userhbs); Date date=new Date(); model.addAttribute("data1",user);
model.addAttribute("data2",date); return "test2";
} @RequestMapping("test3")
public String test3(Model model){
List<String> list=new ArrayList<>();
list.add("爬山");
list.add("游泳");
list.add("打篮球");
model.addAttribute("data1",list); Map<String,String> map=new HashMap();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
model.addAttribute("data2",map); return "test3";
} @RequestMapping("test4")
public String test4(Model model){
User user1=new User();
user1.setUsername("Jim");
user1.setUsersex("male");
user1.setUserage(18); User user2=new User();
user2.setUsername("Tom");
user2.setUsersex("female");
user2.setUserage(19); User user3=new User();
user3.setUsername("Stone");
user3.setUsersex("male");
user3.setUserage(20); List<User> users=new ArrayList<>();
users.add(user1);
users.add(user2);
users.add(user3); model.addAttribute("users",users); return "test4";
} @RequestMapping("test5")
public String test5(Model model){
model.addAttribute("str1","ABCD");
model.addAttribute("str2","abcd");
model.addAttribute("intData1",159);
model.addAttribute("intData2",753);
return "test5";
} @RequestMapping("test6")
public String test6(Model model){
model.addAttribute("scoreMath",65);
model.addAttribute("scoreJava",90);
return "test6";
} @RequestMapping("test7")
public String test7(Model model){
model.addAttribute("htmlData","<h3 stype='color:red;font-weight:bold;'>你好,霍金先生,请一路走好!</h3>");
model.addAttribute("lowerData","ABCD");
model.addAttribute("upperData","abcd");
model.addAttribute("cfData","abcd");
model.addAttribute("intData",123.456);
return "test7";
} @RequestMapping("test8")
public String test8(Model model){
return "test8_1";
} @RequestMapping("test9")
public String test9(Model model){
model.addAttribute("data1","我是后台返回的一个数据");
return "test9";
} }

  WEB-INF/templates下的模板文件如下:

hello.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
你好啊。。我是第一个FreeMarker
<hr>
动态数据展示1:${data1}
<hr>
动态数据展示2:${data2}
<hr>
动态数据展示2:${data3}
</body>
</html>
-----------------------------------------
test2.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
你好啊。。我来显示javabean和日期
<hr>
动态数据展示1:${data1.username}--${data1.usersex}--${data1.userage}--${data1.nation}--${data1.hometown}
<hr>
动态数据展示2:${data2?string("yyyy-MM-dd HH:mm:ss")} </body>
</html>
----------------------------------------------
test3.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
你好啊。。我来显示javabean和日期
<hr>
动态数据展示1:
该集合中元素的个数:${data1?size} 个
<#list data1 as hb>
<h3>
${hb_index}.${hb}
</h3>
</#list>
<hr>
动态数据展示2:
该集合中元素的个数:${data2?size} 个
<#list data2?keys as mapKey>
<h3>
${mapKey}--${data2[mapKey]}
</h3>
</#list>
</body>
</html>
---------------------------------------------
test4.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
你好啊。。我来显示date和javabean的FreeMarker
<hr>
动态数据展示:
该集合*有 : ${users?size} 个
<#list users as user >
<h4>${user_index+1}. ${user.username} ${user.usersex} ${user.userage}</h4>
</#list>
</body>
</html>
---------------------------------------------------
test5.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
你好啊。。我来显示date和javabean的FreeMarker
<hr>
<h3>演示字符串拼接</h3>
${"前面的东西${str1}"}
<br>
${"${str2}后面的东西"}
<br>
${intData1}
</body>
</html>
-------------------------------------------------
test6.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
你好啊。。我来显示date和javabean的FreeMarker
<hr>
<#if scoreMath gt 90>
数学优秀
<#elseif scoreMath gte 60>
数学一般
<#else>
数学不及格
</#if>
<hr>
<#if (scoreMath+scoreJava) gt 160>
优秀学生
<#elseif (scoreMath+scoreJava) gte 120>
一般学生
<#else >
不及格学生
</#if>
</body>
</html>
------------------------------------------------
test7.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
你好啊。。我来显示date和javabean的FreeMarker
<hr>
${htmlData}
<hr>
${htmlData?html}
<hr>
${upperData?upper_case}
<hr>
${lowerData?lower_case}
<hr>
${cfData?cap_first}
<hr>
${intData?int}
</body>
</html>
----------------------------------------
test8_1.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
<hr>
我是8-1的东西。。。。嘻嘻哈哈
<#include "test8_2.ftl">
</body>
</html>
---------------------------------------
test8_2.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
<hr>
我是8-2的东西。。。。
</body>
</html>
------------------------------------------
test9.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
<hr>
演示macro自定义标签:
<#import "test10.ftl" as xgk />
1
<#--<@xgk.tag1 data="${data1}">xxxxxxxxx</@xgk.tag1>--> <@xgk.tag1 data="${data1}">xxxxxxxxx</@xgk.tag1> <hr><hr>
</body>
</html>
-----------------------------------------
test10.ftl
<html>
<head>
<title>$Title$</title>
</head>
<body>
<hr>
<#--<#macro tag1 data>
<hr>
<hr>
<h3 style="color: red">我是一个自定义的标签的效果,展示后台传来的数据:</h3>
<h5>${data} <#nested /></h5>
<hr>
<hr>
</#macro>--> <#macro tag1 data>
<hr>
<hr>
<h3 style="color: red;">
我是test10.ftl
</h3>
<h5>
${data} <#nested />
</h5>
<hr>
<hr>
</#macro>
</body>
</html>

  总的来说,在在.ftl的页面里,可以这样操作传递过来的数据:

	直接显示数据或数据的hashcode	${dataName}
显示自定义类型对象的属性 ${dataName.username}
显示日期型数据 ${dateData?String("yyyy-MM-dd HH:mm:ss")}
显示List型数据 ${listData?size}
<#list listData? as hb>
${hb_index} ${hb}
</#list>
显示Map型数据 ${mapData?size}
<#list mapData?keys as mapKey>
${mapKey} ${mapData[mapKey]}
</#list>
显示自定义类型对象的list集合:
<#list users as user>
${user_index} ${user.username}
</#list>
字符串拼接 ${"前面的东西${strData}"}
if判断 <#if scoreMath gt 90>
数学优秀
<#elseif scoreMath gte 60>
数学一般
<#else>
数学不及格
</#if>
其他函数 ${htmlData?html}
${upperData?upper_case}
${lowerData?lower_case}
${cfData?cap_first}
${intData?int}
引入其他.ftl页面 在test1.ftl中写入
<#include "test2.ftl">
macro自定义标签 test2.ftl页面中写:
<#macro tag1 data>
${data} <#nested />
</#macro>
test1.ftl页面中写:
<#import "test2.ftl" as xgk />
<@xgk.tag1 data="${dataParam}">haha</xgk.tag1>