Spring MVC Integration Freemarker Detailed

Source: Internet
Author: User
Tags arithmetic arithmetic operators logical operators ord

1. What is Freemarker

Freemarker is a template engine, a generic tool that generates text output based on a template, written in plain Java
Freemarker is designed to generate HTML Web pages, especially for applications based on MVC patterns
Although Freemarker has some programming capabilities, it is common for Java programs to prepare the data to be displayed, generate pages from Freemarker, and display prepared data through templates (such as)

2.FreeMarker Features

Ability to generate various types of text: HTML, XML, RTF, Java source code, etc.
Easy to embed into your product: lightweight; no servlet environment required
Plug-in Template loader: Templates can be loaded from any source, such as local files, databases, and so on
You can generate text as you want: save to a local file, send it as an email, send it back to the Web browser from the Web application

3. SPRINGMVC integration Freemarker1. Add a Jar Package

Add Freemarker jar and add Spring-content-support jar package, otherwise you will get an error.

2. Then add the configuration to the Freemarker in the spring configuration file
<!--Configure the Freemarker template path--<Beanclass="Org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" ><PropertyName="Templateloaderpath"Value="Web-inf/ftl/"/><PropertyName="Defaultencoding"Value="UTF-8"/></Bean><!--freemarker View Resolver--<Beanclass="Org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" ><property name=  "suffix" value= ". html"/> <property name=  "ContentType" value= "text/html; Charset=utf-8 "/> <!--This variable value is pagecontext.request, page usage: rc.contextpath--<property name=  "Requestcontextattribute" value= "RC"/> </bean>      
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
3. Write a user class:
package Com.my.springmvc.bean; 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;}}        
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
4. A class of Freemarkercontroller:
@Controller@RequestMapping ( "home") public class freemarkercontroller { @RequestMapping (  "/index") public modelandview add (HttpServletRequest request, HttpServletResponse response) {User user = new User (); User.setusername (" SG "); User.setpassword ( "1234"); list<user> users = new arraylist<user> (); Users.add (User); Modelandview mv = new Modelandview (); Mv.setviewname ( "index"); Mv.addobject ( "users", users); return mv;}            
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
5. Then create a index.html file in the WEB-INF/FTL directory:

##

<! DOCTYPE html><Html><Head><meta charset= "UTF-8" ><title>another</ title></head> <body> <  #list users as user> Username: ${user.username}<br/> Password: ${user.password} </ #list >  </body> </HTML>   
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
Results:

4.freemarker Syntax Introduction: 1. Freemarker template file consists of the following 4 parts

Text: Part of the direct output
Note the:<#–...–> format section, which does not output
Interpolation: The portion of the format that ${...} or #{...} will use partial substitution output from the data model
directive: Freemarker specified, similar to HTML tags, name before the # to differentiate, not output

<Html><Head><title>welcome!</Title></Head><Body><#--comment section-<#--use interpolation below-<H1>welcome ${username}!</H1><p>we have these animals:</p> <u1>  <!--using FTL instruction--< #list  Animals as animal> <li>${animal.name} for ${animal.price} euros</ li> </ #list > </u1></ body></html    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
2. Control statements
< #if condition>  ... <# ElseIf condition2>  #elseif condition3>  #else >< #switch value > < #case refvalue1>  ... <  #break > < #case refvalue2>  < #break > < #case refvaluen>  < #break > <  #default >  </ #switch                 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
3 determining whether a variable exists
<#if readonly??></#if>
    • 1
4. Prevent NULL pointer error

Variable name after use! Add default value: ${foo! " Default "}, if Foo is null then output Default

5. Common variables

This is the simplest case, directly< Span id= "mathjax-span-5" class= "Texatom" > change volume name said as variable name, such as {name}

It is important to note that there are variables that need to be escaped, such as double quotes

6. Traverse the list collection
<#list ["克里斯埃文斯", "斯嘉丽约翰逊", "小罗伯特唐尼"]  as x>  ${x} </#list> 
    • 1
    • 2
    • 3
    • 4

In addition, when iterating over a collection object, it also contains two special loop variables:
Item_index: Index value of the current variable
Item_has_next: Whether the next object exists
You can also use the < #break > command to jump out of an iteration

7. Operators

Arithmetic operations are fully supported in freemarker expressions, and arithmetic operators supported by Freemarker include: +,-, *,/,%
Comparison operators

The comparison operators supported in an expression include the following:
1,= or = =: Determines whether two values are equal.
2,!=: Determine whether two values are unequal.
3,> or GT: Determine if the left value is greater than the right value
4,>= or GTE: Determine if the left value is greater than or equal to the right value
5,< or LT: Determine if the left value is less than the right value
6,<= or LTE: Determine if the left value is less than or equal to the right value

Note: = and! = can be used for strings, numbers and dates to compare equality, but = and! = must be the same type of value on either side, otherwise an error is generated, and Freemarker is an exact comparison, "X", "X", "X" are unequal. Other operators can be used for numbers and dates, But not for strings, most of the time, the use of the GT and other letter operators instead of > will have a better effect, because Freemarker will interpret > as the end character of the FTL tag, and of course, you can also use parentheses to avoid this situation, such as:< #if (x>y) >

logical operators

Like normal programs, Freemarker also has &&,| | ,! Three kinds

8. Declaration of variables

< #assign num=0/>

9.include instruction

The include directive acts like a JSP containing directive that contains the specified page. The syntax format for the include directive is as follows:
< #include filename [options]>
In the syntax format above, the two parameters are interpreted as follows:
FileName: This parameter specifies the template file to be included
Options: This parameter can be omitted, specifying the options that are included, including encoding and parse two options, where encoding specifies the decoding set to be used when the page is contained, and parse specifies whether the included file is parsed as an FTL file, and if the parse option value is omitted, This option is true by default.

10.import instruction

The directive is used to import all the variables in the Freemarker template and place the variable in the specified Map object, with the following syntax for the import directive:
< #import "/LIB/COMMON.FTL" as com>
The above code will import all the variables in the/LIB/COMMON.FTL template file and place them in a map object named COM.

The use of one macro

This can be used to implement custom directives, which are commonly used to make public components, such as paging strips
Finally, the list contains a map of the traversal, which can be used in the point syntax or square brackets syntax. If you have the following data model:
Map root = new HashMap ();
Book book = new book ();
Author Author = new Author ();
Author.setname ("Annlee");
Author.setaddress ("GZ");
Book.setname ("Struts2");
Book.setauthor (author);
Root.put ("info", "struts");
Root.put ("book", book);

To access the name of the author of a book named Struts2 in the data model, you can use the following syntax:
Book.author.name//all use point syntax
book["Author"].name
book.author["name"]//mixed use point syntax and square brackets syntax
book["Author" ["Name"]//all use square brackets syntax

Reference:
http://blog.csdn.net/walkcode/article/details/26393211
http://blog.csdn.net/win_man/article/details/51317957
http://rongjih.blog.163.com/blog/static/3357446120127632757911/
Http://qtdebug.com/spring-web/11.%20Freemarker%20%E8%AF%AD%E6%B3%95%E7%AE%80%E4%BB%8B.html
http://blog.csdn.net/walkcode/article/details/26393211
http://blog.csdn.net/shimiso/article/details/8778793

Spring MVC Integration Freemarker Detailed

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.