Example of the Java-based spring framework for manipulating Freemarker templates _java

Source: Internet
Author: User
Tags aop

1. Create template objects by string, and perform interpolation processing

Import freemarker.template.Template; 

Import Java.io.OutputStreamWriter; 
Import Java.io.StringReader; 
Import Java.util.HashMap; 
Import Java.util.Map; 

/** 
* Freemarker The simplest example 
* * 
@author leizhimin 11-11-17 Morning 10:32 * * Public 
class Test2 { 
    public static void Main (string[] args) throws exception{ 
        //Create a Template object 
        Template t = new Template (NULL, new Stringre Ader ("User name: ${user}; URL:  ${url}; Name: ${name} "), null); 
        Create the interpolated map map 
        = new HashMap (); 
        Map.put ("User", "Lavasoft"); 
        Map.put ("url", "http://www.baidu.com/"); 
        Map.put ("name", "Baidu"); 
        Executes the interpolation and outputs to the specified output stream 
        t.process (map, new OutputStreamWriter (System.out)); 
    } 

 

After execution, the console outputs the results:

User name: Lavasoft;

URL:  http://www.baidu.com/;

Name: Baidu 
Process finished with exit code 0



2, through the file to create template objects, and perform interpolation operations

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 Simplest example * * @author leizhimin 11-11-14 pm 2:44 * * Public class Test {private Configuration cfg; 
        Template Configuration Object public void init () throws Exception {//Initialize Freemarker configuration//Create an instance of configuration 
        CFG = new Configuration (); 
    Sets the template folder location cfg.setdirectoryfortemplateloading (new File ("G:\\testprojects\\freemarkertest\\src") freemarker); 
        The public void process () throws Exception {//constructs the map map map of the populated data = new HashMap (); 
        Map.put ("User", "Lavasoft"); 
        Map.put ("url", "http://www.baidu.com/"); 
        Map.put ("name", "Baidu"); 
        Create a Template object Template t = cfg.gettemplate ("TEST.FTL"); 
    Performs an interpolation operation on the stencil and outputs the t.process (map, new OutputStreamWriter (System.out)) to the established output stream; 

    }public static void Main (string[] args) throws Exception {Test HF = new test (); 
        Hf.init (); 
    Hf.process ();

 } 
}


Create a template file Test.ftl

 
 
Dear User hello: 
user name: ${user}; 
URL:  ${url}; 
Name: ${name}


After execution, the console outputs the following results:

 
 

Dear User Hello:

User name: Lavasoft; 
URL:  http://www.baidu.com/; 
Name: Baidu 
Process finished with exit code 0


3. Spring+freemarker examples based on annotations
Web Project diagram

Web.xml file

<?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/ Java http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "> <servlet> <!--configuration Dispatcherservlet--> <s Ervlet-name>springmvc</servlet-name> <servlet-class> 
   Org.springframework.web.servlet.dispatcherservlet</servlet-class> <!--Specifies that the spring MVC configuration file location does not specify a default condition--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/web-inf/ Springmvc-servlet.xml</param-value> <!--default:/web-inf/<servlet-name>-servlet.xml classpath mode: &LT;PA Ram-value>classpath:/spring-xml/*.xml</param-value>--> </init-param> <!--set boot order- -> <load-on-startup>1</load-on-startup> </servlet> <!--configuration mappingServlet-name and Dispatcherservlet servlet consistent--> <servlet-mapping> <servlet-name>springmvc</ Servlet-name> <url-pattern>/</url-pattern><!--intercept with/all requests--> </servlet-mapping> <welco 
 me-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>

 
Springmvc-servlet.xml file

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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://WW W.springframework.org/schema/mvc/spring-mvc-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP HTTP://WWW.SPRINGF Ramework.org/schema/aop/spring-aop-3.0.xsd Http://www.springframework.org/schema/context Http://www.springframew Ork.org/schema/context/spring-context.xsd "> <!--default annotation mapping support--> <mvc:annotation-driven/> <! --Automatic scanning package--> <context:component-scan base-Package= "Com.spring.freemarker"/> <!--<context:annotation-config/> Configure automatic Scan package configuration This configuration can omit--> < !--<bean class= "Org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" Configure automatic Scan package configuration This configuration can omit/>--> <!--configuration freemarker template path--> <bean class= "org.springframework.web.servlet.view.f Reemarker. Freemarkerconfigurer "> <property name=" Templateloaderpath "value=" web-inf/ftl/"/> <property-name=" D Efaultencoding "value=" UTF-8 "/> </bean> <!--freemarker View parser--> <bean class=" Org.springfra Mework.web.servlet.view.freemarker.FreeMarkerViewResolver "> <property name=" suffix "value=" FTL "/>" ;p roperty name= "ContentType" value= "Text/html;charset=utf-8"/> <!--this variable value is pagecontext.request, page usage: rc.conte 
 Xtpath--> <property name= "Requestcontextattribute" value= "RC"/> </bean> </beans>


Freemarkercontroller class

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 (); C15/>user.setusername ("Zhangsan"); 
    User.setpassword ("1234"); 
    list<user> users = new arraylist<user> (); 
    Users.add (user); 
    return new Modelandview ("Index", "Users", users); 
  } 
 
 

User class

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 file

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 
 
 

Deploy to Tomcat, run: Http://localhost:8080/springmvc/home/index
Show Results:

 Username:zhangsan
 password:1234

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.