1. Créer des objets de modèle via une chaîne et effectuer un traitement d'interpolation
Importer Freemarker.Template.Template; import java.io.outputStreamWriter; import java.io.stringReader; import java.util.hashmap; importation java.util.map; / ** * L'exemple le plus simple de Freemarker * * @author Leizhimin 11-11-17 10:32 AM * / Classe publique Test2 {public static void main (String [] args) lève une exception {// Créer un modèle d'objet de modèle t = nouveau modèle (null, new StringReader ("username: $ {user}; url: $ {url}: username: $ {user}; url: $ {url}: $ {name} "), null); // Créer une carte de carte interpolé MAP = new HashMap (); map.put ("utilisateur", "lavasoft"); map.put ("url", "http://www.baidu.com/"); map.put ("name", "baidu"); // Exécuter l'interpolation et la sortie vers le flux de sortie spécifié T.Process (map, new OutputStreamWriter (System.out)); }} Après l'exécution, la console sortira le résultat:
Nom d'utilisateur: lavasoft; URL: http://www.baidu.com/ ;name: processus Baidu terminé avec le code de sortie 0
2. Créez des objets de modèle via des fichiers et effectuez des opérations d'interpolation
Importer Freemarker.Template.configuration; Importer Freemarker.Template.Template; Importer java.io.file; import java.io.outputStreamWriter; import java.util.hashmap; importation java.util.map; / ** * l'exemple le plus simple de Freemarker * * @author Leizhimin 11-11-14 2:44 PM * / Public Class Test {Configuration privée CFG; // Template Configuration Object public void init () lève une exception {// initialiser Freemarker Configuration // Créer une instance de configuration cfg = new Configuration (); // Définissez l'emplacement du dossier du modèle de freariker cfg.setDirectoryFortEmplateLoading (nouveau fichier ("g: // testProjects // freemarkerTest // src")); } public void process () lève une exception {// construire la carte de carte de la carte qui remplit la carte des données map = new HashMap (); map.put ("utilisateur", "lavasoft"); map.put ("url", "http://www.baidu.com/"); map.put ("name", "baidu"); // Créez le modèle d'objet de modèle t = cfg.getTemplate ("test.ftl"); // Effectuez des opérations d'interpolation sur le modèle et la sortie du flux de sortie formulé T.Process (Map, New outputStreamWriter (System.out)); } public static void main (string [] args) lève une exception {test hf = new test (); hf.init (); hf.process (); }}
Créer un modèle de fichier test.ftl
<html> <éad- head> <itle> bienvenue! </title> </ head> <body> <h1> Bienvenue $ {user}! </h1> <p> Notre dernier produit: <a href = "$ {url}"> $ {name} </a>! </ body> </html> Bonjour, cher utilisateur: nom d'utilisateur: $ {utilisateur}; Url: $ {url}; Nom: $ {nom}
Après l'exécution, les résultats de sortie de la console sont les suivants:
<Html> <A-Head> <Title> Bienvenue! </Title> </ Head> <Body> <H1> Bienvenue Lavasoft! </h1> <p> Notre dernier produit: <a href = "http://www.baidu.com/"> baidu </a>! </ body> </html>
Bonjour, cher utilisateur:
Nom d'utilisateur: Lavasoft; URL: http://www.baidu.com/; Nom: processus Baidu terminé avec le code de sortie 0
3. Instance printemps + freemarker basée sur l'annotation
Schéma de projet Web
fichier 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/xmlSchea "//www.w3.org/2001/xmlSche" XSI: ScheMalocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <! - Configurer Dispatcherservlet -> <Servlet-Name> Springmvc </ Servlet-Name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- Specify the spring mvc configuration file location without specifying the default usage--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springmvc-servlet.xml</param-value> <! - Default: / web-inf / <servlet-name> -serservlet.xml ClassPath Méthode: <Amam-Value> ClassPath: / Spring-xml / *. Dispatterservlet au même servlet-name -> <servlet-mapping> <servlet-name> springmvc </ serplet-name> <url-potern> / </url-potern> <! - Intercept to / all demandes -> </vretlet-mapping> <leen weenge-file> </low-web-App>
Fichier 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. 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/Contex Prise en charge -> <MVC: Annotation-Driven /> <! - Automatic Scanning Package -> <context: Component-Scan Base-Package = "com.spring.freMarker" /> <! - <Context: Annotation-Config /> Configurer la configuration automatique du package de numérisation Cette configuration peut être omise -> <! Template Chemin de FreeMarker -> <an Bean> <Property Name = "TemplateLoaderPath" Value = "web-Inf / Ftl /" /> <propriété name = "DefateNcoding" Value = "utf-8" /> </ bean> <! - FreeMarker View PARSER -> <Eban> <propriété Name = "SUPIX" Value = ". FTL" /> <prewet name = "Contesttype" value = "text / html; charset = utf-8" /> <! - Cette valeur de variable est pageConText.Request, comment utiliser la page: rc.ContextPath -> <propriété name = "requestContextAttribute" value = "rc" /> </ bean> </ beans>
Classe FreemarkerController
package com.spring.freMarker; import java.util.arraylist; Importer java.util.list; Importer javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; import org.springframework.sterreotype.Controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.servlet.modelandView; import com.spring.vo.user; @Controller @RequestMapping ("/ home") classe publique FreemarkerController {@RequestMapping ("/ index") public ModelandView add (httpservletRequest request, httpservletResponse réponse) {user user = new user (); user.setUsername ("Zhangsan"); user.setpassword ("1234"); List <ser utilisateur> users = new ArrayList <Serser> (); users.add (utilisateur); return new ModelandView ("index", "utilisateurs", utilisateurs); }}Classe d'utilisateurs
package com.spring.vo; Nom d'utilisateur de chaîne privée de classe publique; mot de passe de chaîne privé; public String getUserName () {return username; } public void setUsername (String username) {this.userName = username; } public String getPassword () {return mot de passe; } public void setPassword (String Motword) {this.password = mot de passe; }}
fichier index.ftl
<! Doctype html public "- // w3c // dtd html 4.01 transitional // en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <read> <metml <Title> Insérez le titre ici </ title> </ head> <body> <#List Users en tant qu'utilisateur> Nom d'utilisateur: $ {user.username} <br/> Mot de passe: $ {user.password} </ # list> </body> </html> Déployer sur Tomcat et courir: http: // localhost: 8080 / springmvc / home / index
Afficher les résultats:
Nom d'utilisateur: Mot de passe Zhangsan: 1234