目錄
Welcome ${user}!
Welcome lavasoft!
首頁 Java java教程 基於Java的Spring框架來操作FreeMarker模板的範例

基於Java的Spring框架來操作FreeMarker模板的範例

Jan 05, 2017 pm 01:43 PM

1、通过String来创建模版对象,并执行插值处理

import freemarker.template.Template; 
 
import java.io.OutputStreamWriter; 
import java.io.StringReader; 
import java.util.HashMap; 
import java.util.Map; 
 
/** 
* Freemarker最简单的例子 
* 
* @author leizhimin 11-11-17 上午10:32 
*/
public class Test2 { 
    public static void main(String[] args) throws Exception{ 
        //创建一个模版对象 
        Template t = new Template(null, new StringReader("用户名:${user};URL:  ${url};姓名:  ${name}"), null); 
        //创建插值的Map 
        Map map = new HashMap(); 
        map.put("user", "lavasoft"); 
        map.put("url", "http://www.baidu.com/"); 
        map.put("name", "百度"); 
        //执行插值,并输出到指定的输出流中 
        t.process(map, new OutputStreamWriter(System.out)); 
    } 
}
登入後複製

执行后,控制台输出结果:

用户名:lavasoft;
 
URL:  http://www.baidu.com/;
 
姓名:  百度 
Process finished with exit code 0
登入後複製

2、通过文件来创建模版对象,并执行插值操作

import freemarker.template.Configuration; 
import freemarker.template.Template; 
 
import java.io.File; 
import java.io.OutputStreamWriter; 
import java.util.HashMap; 
import java.util.Map; 
 
/** 
* Freemarker最简单的例子 
* 
* @author leizhimin 11-11-14 下午2:44 
*/
public class Test { 
    private Configuration cfg;      //模版配置对象 
 
    public void init() throws Exception { 
        //初始化FreeMarker配置 
        //创建一个Configuration实例 
        cfg = new Configuration(); 
        //设置FreeMarker的模版文件夹位置 
        cfg.setDirectoryForTemplateLoading(new File("G:\\testprojects\\freemarkertest\\src")); 
    } 
 
    public void process() throws Exception { 
        //构造填充数据的Map 
        Map map = new HashMap(); 
        map.put("user", "lavasoft"); 
        map.put("url", "http://www.baidu.com/"); 
        map.put("name", "百度"); 
        //创建模版对象 
        Template t = cfg.getTemplate("test.ftl"); 
        //在模版上执行插值操作,并输出到制定的输出流中 
        t.process(map, new OutputStreamWriter(System.out)); 
    } 
 
    public static void main(String[] args) throws Exception { 
        Test hf = new Test(); 
        hf.init(); 
        hf.process(); 
    } 
}
登入後複製

创建模版文件test.ftl

<html> 
<head> 
  <title>Welcome!</title> 
</head> 
<body> 
  <h1 id="Welcome-nbsp-user">Welcome ${user}!</h1> 
  <p>Our latest product: 
  <a href="${url}">${name}</a>! 
</body> 
</html>
登入後複製
尊敬的用户你好: 
用户名:${user}; 
URL:  ${url}; 
姓名:  ${name}
登入後複製

执行后,控制台输出结果如下:

<html> 
<head> 
  <title>Welcome!</title> 
</head> 
<body> 
  <h1 id="Welcome-nbsp-lavasoft">Welcome lavasoft!</h1> 
  <p>Our latest product: 
  <a href="http://www.baidu.com/">百度</a>! 
</body> 
</html>
登入後複製

尊敬的用户你好:

用户名:lavasoft; 
URL:  http://www.baidu.com/; 
姓名:  百度 
Process finished with exit code 0
登入後複製

3.基于注解的Spring+freemarker实例
web项目图

基於Java的Spring框架來操作FreeMarker模板的範例

web.xml文件

<?xml version="1.0" encoding="UTF-8"?> 
<web-app id="WebApp_ID" 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"> 
 <servlet> 
  <!-- 配置DispatcherServlet -->
  <servlet-name>springmvc</servlet-name> 
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
  <!-- 指定spring mvc配置文件位置 不指定使用默认情况 -->
   <init-param>   
    <param-name>contextConfigLocation</param-name>   
    <param-value>/WEB-INF/springmvc-servlet.xml</param-value> 
    <!--默认:/WEB-INF/<servlet-name>-servlet.xml 
    classpath方式:<param-value>classpath:/spring-xml/*.xml</param-value>   
     -->  
    </init-param> 
  <!-- 设置启动顺序 -->
  <load-on-startup>1</load-on-startup> 
 </servlet> 
 <!-- 配置映射 servlet-name和DispatcherServlet的servlet一致 -->
 <servlet-mapping> 
  <servlet-name>springmvc</servlet-name> 
  <url-pattern>/</url-pattern><!-- 拦截以/所有请求 -->
 </servlet-mapping> 
 <welcome-file-list> 
  <welcome-file>index.jsp</welcome-file> 
 </welcome-file-list> 
</web-app>
登入後複製

springmvc-servlet.xml文件

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans.xsd 
   http://www.springframework.org/schema/mvc  
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
   http://www.springframework.org/schema/aop  
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
   http://www.springframework.org/schema/context  
   http://www.springframework.org/schema/context/spring-context.xsd"> 
  
   <!-- 默认注解映射支持 -->
   <mvc:annotation-driven/>  
   <!-- 自动扫描包 --> 
   <context:component-scan base-package="com.spring.freemarker" /> 
     
   <!--<context:annotation-config /> 配置自动扫描包配置此配置可省略-->  
   <!--<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" 配置自动扫描包配置此配置可省略/>-->
   <!-- 配置freeMarker的模板路径 -->
   <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> 
    <property name="templateLoaderPath" value="WEB-INF/ftl/" /> 
    <property name="defaultEncoding" value="UTF-8" /> 
   </bean> 
   <!-- freemarker视图解析器 -->
   <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> 
    <property name="suffix" value=".ftl" /> 
    <property name="contentType" value="text/html;charset=UTF-8" /> 
    <!-- 此变量值为pageContext.request, 页面使用方法:rc.contextPath -->
    <property name="requestContextAttribute" value="rc" /> 
   </bean> 
</beans>
登入後複製

FreeMarkerController类

package com.spring.freemarker; 
  
import java.util.ArrayList; 
import java.util.List; 
  
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.spring.vo.User; 
  
@Controller
@RequestMapping("/home") 
public class FreeMarkerController { 
  
  @RequestMapping("/index") 
  public ModelAndView Add(HttpServletRequest request, HttpServletResponse response) { 
  
    User user = new User(); 
    user.setUsername("zhangsan"); 
    user.setPassword("1234"); 
    List<User> users = new ArrayList<User>(); 
    users.add(user); 
    return new ModelAndView("index", "users", users); 
  } 
  
}
登入後複製

User类

package com.spring.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; 
  } 
  
}
登入後複製

index.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>Insert title here</title> 
</head> 
<body> 
<#list users as user> 
username : ${user.username}<br/> 
password : ${user.password} 
</#list> 
</body> 
</html>
登入後複製

部署到tomcat,运行:http://localhost:8080/springmvc/home/index
显示结果:

username : zhangsan
password : 1234
登入後複製

更多基於Java的Spring框架來操作FreeMarker模板的範例相关文章请关注PHP中文网!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

公司安全軟件導致應用無法運行?如何排查和解決? 公司安全軟件導致應用無法運行?如何排查和解決? Apr 19, 2025 pm 04:51 PM

公司安全軟件導致部分應用無法正常運行的排查與解決方法許多公司為了保障內部網絡安全,會部署安全軟件。 ...

如何使用MapStruct簡化系統對接中的字段映射問題? 如何使用MapStruct簡化系統對接中的字段映射問題? Apr 19, 2025 pm 06:21 PM

系統對接中的字段映射處理在進行系統對接時,常常會遇到一個棘手的問題:如何將A系統的接口字段有效地映�...

如何優雅地獲取實體類變量名構建數據庫查詢條件? 如何優雅地獲取實體類變量名構建數據庫查詢條件? Apr 19, 2025 pm 11:42 PM

在使用MyBatis-Plus或其他ORM框架進行數據庫操作時,經常需要根據實體類的屬性名構造查詢條件。如果每次都手動...

如何將姓名轉換為數字以實現排序並保持群組中的一致性? 如何將姓名轉換為數字以實現排序並保持群組中的一致性? Apr 19, 2025 pm 11:30 PM

將姓名轉換為數字以實現排序的解決方案在許多應用場景中,用戶可能需要在群組中進行排序,尤其是在一個用...

IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? Apr 19, 2025 pm 11:45 PM

在使用IntelliJIDEAUltimate版本啟動Spring...

Java對像如何安全地轉換為數組? Java對像如何安全地轉換為數組? Apr 19, 2025 pm 11:33 PM

Java對象與數組的轉換:深入探討強制類型轉換的風險與正確方法很多Java初學者會遇到將一個對象轉換成數組的�...

使用TKMyBatis進行數據庫查詢時,如何優雅地獲取實體類變量名構建查詢條件? 使用TKMyBatis進行數據庫查詢時,如何優雅地獲取實體類變量名構建查詢條件? Apr 19, 2025 pm 09:51 PM

在使用TKMyBatis進行數據庫查詢時,如何優雅地獲取實體類變量名以構建查詢條件,是一個常見的難題。本文將針...

電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? 電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? Apr 19, 2025 pm 11:27 PM

電商平台SKU和SPU表設計詳解本文將探討電商平台中SKU和SPU的數據庫設計問題,特別是如何處理用戶自定義銷售屬...

See all articles