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問題解決方案
- 基于Freemarker和xml實(shí)現(xiàn)Java導(dǎo)出word
- SpringBoot2.2.X用Freemarker出現(xiàn)404的解決
- 后臺(tái)使用freeMarker和前端使用vue的方法及遇到的問題
- 構(gòu)建SpringBoot+MyBatis+Freemarker的項(xiàng)目詳解
相關(guān)文章
SpringBoot加載多個(gè)配置文件實(shí)現(xiàn)dev、product多環(huán)境切換的方法
這篇文章主要介紹了SpringBoot加載多個(gè)配置文件實(shí)現(xiàn)dev、product多環(huán)境切換,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03使用java.util.Timer實(shí)現(xiàn)任務(wù)調(diào)度
這篇文章主要為大家詳細(xì)介紹了使用java.util.Timer實(shí)現(xiàn)任務(wù)調(diào)度,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03四個(gè)實(shí)例超詳細(xì)講解Java?貪心和枚舉的特點(diǎn)與使用
貪心算法是指,在對(duì)問題求解時(shí),總是做出在當(dāng)前看來(lái)是最好的選擇。也就是說(shuō),不從整體最優(yōu)上加以考慮,他所做出的是在某種意義上的局部最優(yōu)解,枚舉法的本質(zhì)就是從所有候選答案中去搜索正確的解,枚舉算法簡(jiǎn)單粗暴,他暴力的枚舉所有可能,盡可能地嘗試所有的方法2022-04-04java設(shè)計(jì)模式之觀察者模式學(xué)習(xí)
這篇文章主要為大家詳細(xì)介紹了java設(shè)計(jì)模式之觀察者模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01Java靜態(tài)方法不能調(diào)用非靜態(tài)成員的原因分析
在Java中,靜態(tài)方法是屬于類的方法,而不是屬于對(duì)象的方法,它可以通過(guò)類名直接調(diào)用,無(wú)需創(chuàng)建對(duì)象實(shí)例,非靜態(tài)成員指的是類的實(shí)例變量和實(shí)例方法,它們需要通過(guò)對(duì)象實(shí)例才能訪問和調(diào)用,本文小編將和大家一起探討Java靜態(tài)方法為什么不能調(diào)用非靜態(tài)成員2023-10-10springboot 返回json格式數(shù)據(jù)時(shí)間格式配置方式
這篇文章主要介紹了springboot 返回json格式數(shù)據(jù)時(shí)間格式配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11SpringCloud Netflix Ribbon源碼解析(推薦)
這篇文章主要介紹了SpringCloud Netflix Ribbon源碼解析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03