Spring MVC整合FreeMarker的示例
什么是Freemarker?
FreeMarker是一個(gè)用Java語(yǔ)言編寫的模板引擎,它基于模板來(lái)生成文本輸出。FreeMarker與Web容器無(wú)關(guān),即在Web運(yùn)行時(shí),它并不知道Servlet或HTTP。它不僅可以用作表現(xiàn)層的實(shí)現(xiàn)技術(shù),而且還可以用于生成XML,JSP或Java 等。
目前企業(yè)中:主要用Freemarker做靜態(tài)頁(yè)面或是頁(yè)面展示
一.工程結(jié)構(gòu)

二.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SpringMVC</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springMVC-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
三.springMVC-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!-- 自動(dòng)掃描包 -->
<context:component-scan base-package="com.bijian.study.controller"></context:component-scan>
<!-- 默認(rèn)注解映射支持 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!--JSP視圖解析器-->
<bean id="viewResolverJsp" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<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="/WEB-INF/ftl/"/>
<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"/>
</beans>
在JSP和Freemarker的配置項(xiàng)中都有一個(gè)order property,上面例子是把freemarker的order設(shè)置為0,jsp為1,意思是找view時(shí),先找ftl文件,再找jsp文件做為視圖。這樣Freemarker視圖解析器就能與JSP視圖解析器并存。
四.FreeMarkerController.java
package com.bijian.study.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.bijian.study.utils.JsonUtil;
import com.bijian.study.vo.User;
@Controller
public class FreeMarkerController {
@RequestMapping("/get/usersInfo")
public ModelAndView Add(HttpServletRequest request, HttpServletResponse response) {
User user = new User();
user.setUsername("zhangsan");
user.setPassword("1234");
User user2 = new User();
user2.setUsername("lisi");
user2.setPassword("123");
List<User> users = new ArrayList<User>();
users.add(user);
users.add(user2);
return new ModelAndView("usersInfo", "users", users);
}
@RequestMapping("/get/allUsers")
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
List<User> users = new ArrayList<User>();
User u1 = new User();
u1.setUsername("王五");
u1.setPassword("123");
users.add(u1);
User u2 = new User();
u2.setUsername("張三");
u2.setPassword("2345");
users.add(u2);
User u3 = new User();
u3.setPassword("fgh");
u3.setUsername("李四");
users.add(u3);
Map<String, Object> rootMap = new HashMap<String, Object>();
rootMap.put("userList", users);
Map<String, String> product = new HashMap<String, String>();
rootMap.put("lastProduct", product);
product.put("url", "http://www.baidu.com");
product.put("name", "green hose");
String result = JSON.toJSONString(rootMap);
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap = JsonUtil.getMapFromJson(result);
return new ModelAndView("allUsers", "resultMap", resultMap);
}
}
五.JsonUtil.java
package com.bijian.study.utils;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class JsonUtil {
public static Map<String, Object> getMapFromJson(String jsonString) {
if (checkStringIsEmpty(jsonString)) {
return null;
}
return JSON.parseObject(jsonString);
}
/**
* 檢查字符串是否為空
* @param str
* @return
*/
private static boolean checkStringIsEmpty(String str) {
if (str == null || str.trim().equals("") || str.equalsIgnoreCase("null")) {
return true;
}
return false;
}
}
六.User.java
ackage com.bijian.study.vo;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
七.usersInfo.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>usersInfo</title>
</head>
<body>
<#list users as user>
<div>
username : ${user.username},
password : ${user.password}
</div>
</#list>
</body>
</html>
八.allUsers.ftl
<html>
<head>
<title>allUsers</title>
</head>
<body>
<#list resultMap.userList as user>
Welcome ${user.username}! id:${user.password}<br/>
</#list>
<p>Our latest product:
<a href="${resultMap.lastProduct.url}" rel="external nofollow" >${resultMap.lastProduct.name} </a>!
</body>
</html>
九.運(yùn)行效果


再輸入http://localhost:8088/SpringMVC/greeting?name=zhangshan,JSP視圖解析器運(yùn)行依然正常。

至此,就結(jié)束完成整合了!
以上就是Spring MVC整合FreeMarker的示例的詳細(xì)內(nèi)容,更多關(guān)于Spring MVC整合FreeMarker的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Spring MVC整合 freemarker及使用方法
- springmvc整合freemarker配置的詳細(xì)步驟
- spring mvc整合freemarker基于注解方式
- Springboot整合Freemarker的實(shí)現(xiàn)詳細(xì)過(guò)程
- spring boot加載freemarker模板路徑的方法
- Springboot整合freemarker 404問(wèn)題解決方案
- 基于Freemarker和xml實(shí)現(xiàn)Java導(dǎo)出word
- SpringBoot2.2.X用Freemarker出現(xiàn)404的解決
- 后臺(tái)使用freeMarker和前端使用vue的方法及遇到的問(wèn)題
- 構(gòu)建SpringBoot+MyBatis+Freemarker的項(xiàng)目詳解
相關(guān)文章
Java 獲取當(dāng)前時(shí)間及實(shí)現(xiàn)時(shí)間倒計(jì)時(shí)功能【推薦】
這篇文章主要介紹了Java 獲取當(dāng)前時(shí)間及實(shí)現(xiàn)時(shí)間倒計(jì)時(shí)功能 ,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
Java利用序列化實(shí)現(xiàn)對(duì)象深度clone的方法
這篇文章主要介紹了Java利用序列化實(shí)現(xiàn)對(duì)象深度clone的方法,實(shí)例分析了java序列化及對(duì)象克隆的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
SpringBoot對(duì)Filter過(guò)濾器中的異常進(jìn)行全局處理方案詳解
這篇文章主要介紹了SpringBoot對(duì)Filter過(guò)濾器中的異常進(jìn)行全局處理,在SpringBoot中我們通過(guò) @ControllerAdvice 注解和 @ExceptionHandler注解注冊(cè)了全局異常處理器,需要的朋友可以參考下2023-09-09
mybatis中的擴(kuò)展實(shí)現(xiàn)源碼解析
這篇文章主要介給大家紹了關(guān)于mybatis中擴(kuò)展實(shí)現(xiàn)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
解決FontConfiguration.getVersion報(bào)空指針異常的問(wèn)題
這篇文章主要介紹了解決FontConfiguration.getVersion報(bào)空指針異常的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Spring AOP如何自定義注解實(shí)現(xiàn)審計(jì)或日志記錄(完整代碼)
這篇文章主要介紹了Spring AOP如何自定義注解實(shí)現(xiàn)審計(jì)或日志記錄(完整代碼),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
springboot中請(qǐng)求地址轉(zhuǎn)發(fā)的兩種方案
在開發(fā)過(guò)程中,我們經(jīng)常需要將請(qǐng)求從一個(gè)服務(wù)轉(zhuǎn)發(fā)到另一個(gè)服務(wù),以實(shí)現(xiàn)不同服務(wù)之間的協(xié)作,本文主要介紹了springboot中請(qǐng)求地址轉(zhuǎn)發(fā)的兩種方案,感興趣的可以了解一下2023-11-11
SpringBoot開發(fā)技巧之使用AOP記錄日志示例解析
這篇文章主要為大家介紹了SpringBoot開發(fā)技巧之如何利用AOP記錄日志的示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10
java中map與實(shí)體類的相互轉(zhuǎn)換操作
這篇文章主要介紹了java中map與實(shí)體類的相互轉(zhuǎn)換操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07

