1. Create template objects through 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; /** * The simplest example of Freemarker* * @author leizhimin 11-11-17 10:32 am */ public class Test2 { public static void main(String[] args) throws Exception{ //Create a template object Template t = new Template(null, new StringReader("Username: ${user};URL: ${url};Name: ${name}"), null); //Create interpolated Map Map map = new HashMap(); map.put("user", "lavasoft"); map.put("url", "http://www.baidu.com/"); map.put("name", "Baidu"); //Execute interpolation and output to the specified output stream t.process(map, new OutputStreamWriter(System.out)); } } After execution, the console outputs the result:
Username: lavasoft;URL: http://www.baidu.com/;Name: Baidu Process finished with exit code 0
2. Create template objects through files 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; /** * The simplest example of Freemarker* * @author leizhimin 11-11-14 2:44 pm */ public class Test { private Configuration cfg; //template configuration object public void init() throws Exception { //Initialize FreeMarker configuration//Create a Configuration instance cfg = new Configuration(); //Set the template folder location of FreeMarker cfg.setDirectoryForTemplateLoading(new File("G://testprojects//freemarkertest//src")); } public void process() throws Exception { //Construct the Map Map map that fills the data Map map = new HashMap(); map.put("user", "lavasoft"); map.put("url", "http://www.baidu.com/"); map.put("name", "Baidu"); //Create the template object Template t = cfg.getTemplate("test.ftl"); //Perform interpolation operations on the template and output to the formulated output stream t.process(map, new OutputStreamWriter(System.out)); } public static void main(String[] args) throws Exception { Test hf = new Test(); hf.init(); hf.process(); } }
Create template file test.ftl
<html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome ${user}!</h1> <p>Our latest product: <a href="${url}">${name}</a>! </body> </html> Hello, dear user: Username: ${user}; URL: ${url}; Name: ${name}
After execution, the console output results are as follows:
<html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome lavasoft!</h1> <p>Our latest product: <a href="http://www.baidu.com/">Baidu</a>! </body> </html>
Hello, dear user:
Username: lavasoft; URL: http://www.baidu.com/; Name: Baidu Process finished with exit code 0
3. Annotation-based Spring+freemarker instance
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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <!-- Configure 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>-servlet.xml classpath method: <param-value>classpath:/spring-xml/*.xml</param-value> --> </init-param> <!-- Set startup order --> <load-on-startup>1</load-on-startup> </servlet> <!-- Configure the servlet that maps servlet-name and DispatcherServlet to the same servlet-name --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern><!-- Intercept to/all requests--> </servlet-mapping> <welcome-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="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"> <!-- Default annotation mapping support--> <mvc:annotation-driven/> <!-- Automatic scanning package--> <context:component-scan base-package="com.spring.freemarker" /> <!--<context:annotation-config /> Configure automatic scanning package configuration This configuration can be omitted--> <!--<bean Configure the automatic scan package Configure this configuration to omit/> -> <!-- Configure the template path of freeMarker --> <bean> <property name="templateLoaderPath" value="WEB-INF/ftl/" /> <property name="defaultEncoding" value="UTF-8" /> </bean> <!-- freemarker view parser--> <bean> <property name="suffix" value=".ftl" /> <property name="contentType" value="text/html;charset=UTF-8" /> <!-- This variable value is pageContext.request, How to use the page: rc.contextPath --> <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(); 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"> <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> Deploy to tomcat and run: http://localhost:8080/springmvc/home/index
Show results:
username : zhangsan password : 1234