欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于Java的Spring框架来操作FreeMarker模板的示例

程序员文章站 2024-03-09 14:58:37
1、通过string来创建模版对象,并执行插值处理   import freemarker.template.template; impo...

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>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>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