1.1. What is Freemarker
Freemarker is a template engine written in the Java language that generates text output based on a template. Freemarker is not related to the Web container, that is, it does not know the servlet or HTTP while the Web is running. It can be used not only as an implementation technique for the presentation layer, but also for generating xml,jsp or Java.
Currently in the enterprise: mainly use Freemarker to do static pages or page display
1.2. How to use Freemarker
Add the Freemarker jar package to the project.
Maven Project Add Dependency
<dependency>
<groupId>org.freemarker</groupId>
<artifactid>freemarker</ artifactid>
<version>2.3.23</version>
</dependency>
Principle:
Steps to use:
The first step: Create a Configuration object that is directly new to an object. The parameter of the constructor method is the version number of the Freemarker.
Step Two: Set the path where the template files are located.
Step three: Set the character set used by the template file. is generally utf-8.
Fourth step: Load a template and create a template object.
Fifth step: Create a data set used by a template, either Pojo or map. is generally a map.
Sixth step: Create a Writer object that typically creates a FileWriter object that specifies the generated file name.
Seventh Step: Call the Template object's Process method output file.
Eighth step: Close the stream.
@Test public void Genfile () throws Exception {//First step: Create a Configuration object that is directly new to an object.
The parameter of the constructor method is the version number of the Freemarker.
Configuration configuration = new configuration (configuration.getversion ());
Step Two: Set the path where the template files are located. Configuration.setdirectoryfortemplateloading (The New File ("d:/workspaces-itcast/term197/taotao-item-web/src/main/
WEBAPP/WEB-INF/FTL ")); Step three: Set the character set used by the template file.
is generally utf-8.
Configuration.setdefaultencoding ("Utf-8");
Fourth step: Load a template and create a template object.
Template template = Configuration.gettemplate ("HELLO.FTL"); Fifth step: Create a data set used by a template, either Pojo or map.
is generally a map.
Map Datamodel = new hashmap<> ();
Add data Datamodel.put to the dataset ("Hello", "This is my first freemarker test.");
Sixth step: Create a Writer object that typically creates a FileWriter object that specifies the generated file name.
Writer out = new FileWriter (New File ("d:/temp/term197/out/hello.html"));
Seventh Step: Call the Template object's Process method output file.
Template.process (Datamodel, out); EighthStep: Close the stream.
Out.close (); }
1.3. The syntax of the template is 1.3.1. Access key in Map
${key}
1.3.2. Accessing Properties in Pojo
The student object. School number, name, age
${key.property}
1.3.3. Fetching data from a collection
< #list studentlist asstudent>
${student.id}/${studnet.name}
</#list >
Looping using formats:
< #list data to be recycled as a loop after data >
</#list >
1.3.4. Taking the subscript in the loop
< #list studentlist as student>
${student_index}
</#list >
1.3.5. Judging
< #if student_index% 2 = = 0>
< #else >
</#if >
1.3.6. Date type formatting
Direct value: ${date} (date is property name) if a date data is coming, it will be an error.
${date?date} 2016-9-13
${date?time} 17:53:55
${date?datetime} 2016-9-13 17:53:55
1.3.7. Handling of NULL values
An exception is reported if a non-existent value is directly taken (a value of NULL)
${AAA}
Processing: ${aaa! " Default Value "} or ${aaa!} Represents an empty string
1.3.8. Include tags
< #include "template name" >
(equivalent to included in Jstl)
1.4. Freemarker Integration Spring
To introduce a jar package:
Freemarker's jar Package
1.4.1. Creating a configuration file that consolidates spring
<?xmlversion= "1.0" encoding= "UTF-8"?> <beansxmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:dubbo= "Http://code.alibabatech.com/schema/dubbo" Xmlns:mvc = "Http://www.springframework.org/schema/mvc" 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-4.2.xsd Http://code.alibabatech.com/schema/dubbo/HTTP Code.alibabatech.com/schema/dubbo/dubbo.xsd Http://www.springframework.org/schema/context/HTTP Www.springframework.org/schema/context/spring-context.xsd "> <beanid=" freemarkerconfig "class=" org.sp Ringframework.web.servlet.view.freemarker.FreeMarkerConfigurer "> <proPertyname= "Templateloaderpath" value= "/web-inf/ftl/"/> <propertyname= "defaultencoding" value= "UTF-8"/> </bean> </beans>
Need to write a controller to test
1.4.2. Controller
Url:/genhtml of the request
Parameters: None
return value: OK (String, need to use @responsebody)
Business logic:
1. Obtain the Freemarkerconfigurer object from the Spring container.
2. Get the configuration object from the Freemarkerconfigurer object.
3. Use the configuration object to get the template object.
4. Create a data set
5. Create the writer object for the output file.
6. Call the Template object's process method to generate the file.
7. Close the stream.
To load a configuration file:
@Controller
publicclass htmlgencontroller {
@Autowired
private Freemarkerconfigurerfreemarkerconfigurer;
@RequestMapping ("/genhtml")
@ResponseBody public
String genhtml () throws Exception {
//1, Gets the Freemarkerconfigurer object from the Spring container.
///2, get the configuration object from the Freemarkerconfigurer object.
Configuration Configuration = Freemarkerconfigurer.getconfiguration ();
3. Use the configuration object to get the template object.
Template template = Configuration.gettemplate ("HELLO.FTL");
4. Create DataSet
Map Datamodel = new hashmap<> ();
Datamodel.put ("Hello", "n");
5. Create the writer object for the output file.
Writer out = new FileWriter (New File ("d:/temp/term197/out/spring-freemarker.html"));
6. Call the Template object's process method to generate the file.
template.process (Datamodel, out);
7. Close the stream.
out.close ();
return "OK";
}
}