欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring MVC整合FreeMarker的示例

 更新時(shí)間:2020年12月30日 10:46:38   作者:zsq_fengchen  
這篇文章主要介紹了Spring MVC整合FreeMarker的示例,幫助大家更好的理解和使用Spring MVC,感興趣的朋友可以了解下

什么是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)文章!

相關(guān)文章

  • Spring Boot之@Async異步線程池示例詳解

    Spring Boot之@Async異步線程池示例詳解

    在Spring Boot中,我們只需要通過(guò)使用@Async注解就能簡(jiǎn)單的將原來(lái)的同步函數(shù)變?yōu)楫惒胶瘮?shù),下面這篇文章主要給大家介紹了關(guān)于Spring Boot之@Async異步線程池的相關(guān)資料,需要的朋友可以參考下
    2021-09-09
  • SpringBoot加載多個(gè)配置文件實(shí)現(xiàn)dev、product多環(huá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)度

    使用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)與使用

    四個(gè)實(shí)例超詳細(xì)講解Java?貪心和枚舉的特點(diǎn)與使用

    貪心算法是指,在對(duì)問題求解時(shí),總是做出在當(dāng)前看來(lái)是最好的選擇。也就是說(shuō),不從整體最優(yōu)上加以考慮,他所做出的是在某種意義上的局部最優(yōu)解,枚舉法的本質(zhì)就是從所有候選答案中去搜索正確的解,枚舉算法簡(jiǎn)單粗暴,他暴力的枚舉所有可能,盡可能地嘗試所有的方法
    2022-04-04
  • java設(shè)計(jì)模式之觀察者模式學(xué)習(xí)

    java設(shè)計(jì)模式之觀察者模式學(xué)習(xí)

    這篇文章主要為大家詳細(xì)介紹了java設(shè)計(jì)模式之觀察者模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-01-01
  • Spring的IOC代碼解析

    Spring的IOC代碼解析

    這篇文章主要介紹了Spring的IOC代碼解析,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • Java靜態(tài)方法不能調(diào)用非靜態(tài)成員的原因分析

    Java靜態(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-10
  • springboot 返回json格式數(shù)據(jù)時(shí)間格式配置方式

    springboot 返回json格式數(shù)據(jù)時(shí)間格式配置方式

    這篇文章主要介紹了springboot 返回json格式數(shù)據(jù)時(shí)間格式配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • SpringCloud Netflix Ribbon源碼解析(推薦)

    SpringCloud Netflix Ribbon源碼解析(推薦)

    這篇文章主要介紹了SpringCloud Netflix Ribbon源碼解析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • @Query注解的原生用法和native用法解析

    @Query注解的原生用法和native用法解析

    這篇文章主要介紹了@Query注解的原生用法和native用法解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-08-08

最新評(píng)論