Spring MVC整合FreeMarker的示例

什麼是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視圖解析器運行依然正常。

至此,就結束完成整合瞭!

以上就是Spring MVC整合FreeMarker的示例的詳細內容,更多關於Spring MVC整合FreeMarker的資料請關註WalkonNet其它相關文章!

推薦閱讀: