Spring MVC整合FreeMarker Spring MVC整合FreeMarker的示例
zsq_fengchen 人气:0什么是Freemarker?
FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。
目前企业中:主要用Freemarker做静态页面或是页面展示
一.工程结构
二.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 "> <!-- 自动扫描包 --> <context:component-scan base-package="com.bijian.study.controller"></context:component-scan> <!-- 默认注解映射支持 --> <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的配置项中都有一个order property,上面例子是把freemarker的order设置为0,jsp为1,意思是找view时,先找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>
九.运行效果
再输入http://localhost:8088/SpringMVC/greeting?name=zhangshan,JSP视图解析器运行依然正常。
至此,就结束完成整合了!
加载全部内容