基於Java的Spring架構來操作FreeMarker模板的樣本_java

來源:互聯網
上載者:User

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項目圖

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.