Spring MVC整合FreeMarker

2019-08-16 11:35:11来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Spring MVC整合FreeMarker

什么是Freemarker?
    FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。
    目前企业中:主要用Freemarker做静态页面或是页面展示

一.工程结构

二.web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>  
 2 <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee      
 5    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
 6      
 7     <display-name>SpringMVC</display-name>  
 8       
 9     <context-param>  
10         <param-name>contextConfigLocation</param-name>  
11         <param-value>/WEB-INF/springMVC-servlet.xml</param-value>  
12     </context-param>  
13       
14     <listener>  
15         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
16     </listener>  
17       
18     <filter>  
19         <filter-name>encodingFilter</filter-name>  
20         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
21         <init-param>  
22             <param-name>encoding</param-name>  
23             <param-value>UTF-8</param-value>  
24         </init-param>  
25         <init-param>  
26             <param-name>forceEncoding</param-name>  
27             <param-value>true</param-value>  
28         </init-param>  
29     </filter>  
30     <filter-mapping>  
31         <filter-name>encodingFilter</filter-name>  
32         <url-pattern>/*</url-pattern>  
33     </filter-mapping>  
34   
35     <servlet>  
36         <servlet-name>springMVC</servlet-name>  
37         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
38         <load-on-startup>1</load-on-startup>  
39     </servlet>  
40     <servlet-mapping>  
41         <servlet-name>springMVC</servlet-name>  
42         <url-pattern>/</url-pattern>  
43     </servlet-mapping>  
44 </web-app>   

 

三.springMVC-servlet.xml

 1 <?xml version="1.0" encoding="UTF-8"?>  
 2 <beans xmlns="http://www.springframework.org/schema/beans"  
 3     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"  
 4     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans   
 6                     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
 7                     http://www.springframework.org/schema/context  
 8                     http://www.springframework.org/schema/context/spring-context-3.0.xsd  
 9                     http://www.springframework.org/schema/mvc  
10                     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
11                     ">  
12     <!-- 自动扫描包 -->   
13     <context:component-scan base-package="com.bijian.study.controller"></context:component-scan>     
14       
15     <!-- 默认注解映射支持 -->   
16     <mvc:annotation-driven></mvc:annotation-driven>  
17       
18     <!--JSP视图解析器-->  
19     <bean id="viewResolverJsp" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
20         <property name="prefix" value="/WEB-INF/views/"/>  
21         <property name="suffix" value=".jsp"/>  
22         <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>  
23         <property name="order" value="1"/>  
24     </bean>  
25       
26     <!-- 配置freeMarker视图解析器 -->  
27     <bean id="viewResolverFtl" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
28         <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>  
29         <property name="contentType" value="text/html; charset=UTF-8"/>  
30         <property name="exposeRequestAttributes" value="true" />  
31         <property name="exposeSessionAttributes" value="true" />  
32         <property name="exposeSpringMacroHelpers" value="true" />  
33         <property name="cache" value="true" />  
34         <property name="suffix" value=".ftl" />  
35         <property name="order" value="0"/>  
36     </bean>  
37   
38     <!-- 配置freeMarker的模板路径 -->  
39     <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
40         <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>  
41         <property name="freemarkerVariables">  
42             <map>  
43                 <entry key="xml_escape" value-ref="fmXmlEscape" />  
44             </map>  
45         </property>  
46         <property name="defaultEncoding" value="UTF-8"/>  
47         <property name="freemarkerSettings">  
48             <props>  
49                 <prop key="template_update_delay">3600</prop>  
50                 <prop key="locale">zh_CN</prop>  
51                 <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>  
52                 <prop key="date_format">yyyy-MM-dd</prop>  
53                 <prop key="number_format">#.##</prop>  
54             </props>  
55         </property>  
56     </bean>  
57   
58     <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>  
59 </beans>  

      在JSP和Freemarker的配置项中都有一个order property,上面例子是把freemarker的order设置为0,jsp为1,意思是找view时,先找ftl文件,再找jsp文件做为视图。这样Freemarker视图解析器就能与JSP视图解析器并存。

   

四.FreeMarkerController.java

 1 package com.bijian.study.controller;  
 2   
 3 import java.util.ArrayList;  
 4 import java.util.HashMap;  
 5 import java.util.List;  
 6 import java.util.Map;  
 7   
 8 import javax.servlet.http.HttpServletRequest;  
 9 import javax.servlet.http.HttpServletResponse;  
10   
11 import org.springframework.stereotype.Controller;  
12 import org.springframework.web.bind.annotation.RequestMapping;  
13 import org.springframework.web.servlet.ModelAndView;  
14   
15 import com.alibaba.fastjson.JSON;  
16 import com.bijian.study.utils.JsonUtil;  
17 import com.bijian.study.vo.User;  
18     
19 @Controller   
20 public class FreeMarkerController {     
21     
22     @RequestMapping("/get/usersInfo")     
23     public ModelAndView Add(HttpServletRequest request, HttpServletResponse response) {     
24     
25         User user = new User();     
26         user.setUsername("zhangsan");     
27         user.setPassword("1234");  
28           
29         User user2 = new User();     
30         user2.setUsername("lisi");     
31         user2.setPassword("123");   
32           
33         List<User> users = new ArrayList<User>();     
34         users.add(user);  
35         users.add(user2);  
36         return new ModelAndView("usersInfo", "users", users);     
37     }  
38       
39     @RequestMapping("/get/allUsers")     
40     public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {  
41           
42         List<User> users = new ArrayList<User>();     
43         User u1 = new User();     
44         u1.setUsername("王五");  
45         u1.setPassword("123");  
46         users.add(u1);  
47           
48         User u2 = new User();     
49         u2.setUsername("张三");  
50         u2.setPassword("2345");  
51         users.add(u2);  
52           
53         User u3 = new User();     
54         u3.setPassword("fgh");     
55         u3.setUsername("李四");  
56         users.add(u3);     
57           
58         Map<String, Object> rootMap = new HashMap<String, Object>();  
59         rootMap.put("userList", users);  
60         Map<String, String> product = new HashMap<String, String>();  
61         rootMap.put("lastProduct", product);  
62         product.put("url", "http://www.baidu.com");     
63         product.put("name", "green hose");  
64           
65         String result = JSON.toJSONString(rootMap);  
66           
67         Map<String, Object> resultMap = new HashMap<String, Object>();  
68         resultMap = JsonUtil.getMapFromJson(result);  
69           
70         return new ModelAndView("allUsers", "resultMap", resultMap);     
71     }  
72 }  

 

五.JsonUtil.java

 1 package com.bijian.study.utils;  
 2   
 3 import java.util.Map;  
 4   
 5 import com.alibaba.fastjson.JSON;  
 6   
 7 public class JsonUtil {  
 8   
 9     public static Map<String, Object> getMapFromJson(String jsonString) {  
10         if (checkStringIsEmpty(jsonString)) {  
11             return null;  
12         }  
13         return JSON.parseObject(jsonString);  
14     }  
15       
16     /** 
17      * 检查字符串是否为空 
18      * @param str 
19      * @return 
20      */  
21     private static boolean checkStringIsEmpty(String str) {  
22         if (str == null || str.trim().equals("") || str.equalsIgnoreCase("null")) {  
23             return true;  
24         }  
25         return false;  
26     }  
27 }  

 

 六.User.java

 1 ackage com.bijian.study.vo;  
 2   
 3 public class User {  
 4   
 5     private String username;  
 6     private String password;  
 7   
 8     public String getUsername() {  
 9         return username;  
10     }  
11   
12     public void setUsername(String username) {  
13         this.username = username;  
14     }  
15   
16     public String getPassword() {  
17         return password;  
18     }  
19   
20     public void setPassword(String password) {  
21         this.password = password;  
22     }  
23 }  

 

七.usersInfo.ftl

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">     
 2 <html>     
 3 <head>     
 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">     
 5 <title>usersInfo</title>     
 6 </head>     
 7 <body>     
 8 <#list users as user>  
 9     <div>  
10         username : ${user.username},   
11         password : ${user.password}  
12     </div>  
13 </#list>     
14 </body>     
15 </html>  

 

八.allUsers.ftl

 1 <html>     
 2  <head>     
 3    <title>allUsers</title>     
 4  </head>     
 5  <body>     
 6    <#list resultMap.userList as user>     
 7        Welcome ${user.username}!&nbsp;&nbsp;id:${user.password}<br/>     
 8    </#list>     
 9    <p>Our latest product:     
10     <a href="${resultMap.lastProduct.url}">${resultMap.lastProduct.name}  </a>!     
11   </body>     
12 </html>  

 

九.运行效果

 

 再输入http://localhost:8088/SpringMVC/greeting?name=zhangshan,JSP视图解析器运行依然正常。

至此,就结束完成整合了!


原文链接:https://www.cnblogs.com/zhaosq/p/11252028.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Redisson基本用法

下一篇:基于Morphia实现MongoDB按小时、按天聚合操作