Freemarker's Application Instances in struts2.0, Java, and Web

Source: Internet
Author: User
Tags tld

 

Freemarker Overview
  • Freemarker is a template engine and a common tool for generating text output based on templates. It is written in Java only.
  • Template + Data Model = Output

 

Freemarker is an excellent template engine that can be used in any scenario. freemarker is responsible for merging data in the data model into the template to generate standard output. interface developers only need to Develop interfaces (that is, template files), while business logic developers only need to fill in the data model that needs to be displayed ----- freemarker is responsible for merging data models and templates, generate standard output. freemarker is especially suitable for MVC web applications. Although freemarker has some programming capabilities, it has very limited programming capabilities and cannot implement business logic. It can only provide some data format conversion functions. therefore, the data to be displayed is usually prepared by the Java program and generated by the freemarker template engine, while the freemarker template provides page layout support. . (Benefit: strictly implement MVC separation)In addition, F Reemarker is also irrelevant to the Web Container, that is, freemarker does not necessarily need to run in the Web container:Freemarker can also be applied to non-web application environments, Freemarker can not only generate HTML pages, but also generate various texts, such as XML, RTF, and Java source code. Struts2 uses freemarker as its template file by default,All theme template files of struts2 are written by freemarker, and templates such as JSP and Java in eclipse also adopt freemarker technology. 1. Use freemarker in struts2The general struts2 configuration file is usually configured as follows: <action name = "Action1" class = "com. ABC. Action1">
<Result>/page. jsp </result>
</Action> the view here is a JSP page or a freemarker template page: <action name = "Action1" class = "com. ABC. Action1">
<Result type = "freemarker">/FM. FTL </result>
</Action> of course, we want. use the struts2 tag on the FTL, which must be in the FM. the FTL page first adds a reference to the struts2 Tag: <# assign S = jsptaglibs ["/WEB-INF/struts-tags.tld"]/> before referencing, copy the struts2-core-2.0.x.x.jar/META-INF in the struts-tags.tld package to/WEB-INF/struts-tags.tld which by default does not support references of jsptaglibs, an additional configuration is required to modify the web. XML to add the following content: <servlet>
<Servlet-Name> jspsuppservlet servlet </servlet-Name>
<Servlet-class>
Org. Apache. struts2.views. jspsuppservlet Servlet
</Servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet> An example of a simple FM. FTL file: <# assign S = jsptaglibs ["/WEB-INF/struts-tags.tld"]/>
<HTML>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Title> insert title here </title>
</Head>
<Body>
<@ S. Form Action = "action1.action">
<@ S. textfield name = "username"> </@ s. textfield>
<@ S. textfield name = "password"> </@ s. textfield>
<@ S. Submit value = "Submit"/>
</@ S. Form>
<Br/> logon Username: $ {username}
</Body>
</Html> Note: The tag Writing Method of struts2 on the freemarker page is different from that on the JSP page. In freemarker, It is <@ s. form> in JSP is <s: Form>. Do not make any mistakes! Chinese characters are not supported properly during use. Chinese characters are garbled during display. Modify struts here. xml configuration file: <constant name = "struts. i18n. encoding "value =" gb2312 "/> now we can use freemarker in struts2! Your own instance:(1) Add a jump in struts. xml:
<Package name = "loginpackage" extends = "Jason-Default">
<Action name = "jlogin" class = "jlogin">
<Result name = "success">/WEB-INF/Jason/index. jsp </result>
<Result name = "error">/WEB-INF/Jason/login. jsp </result>
<Result name = "input">/WEB-INF/Jason/login. jsp </result>
<Result name = "Search" type = "freemarker">/WEB-INF/templates/jsearch. FTL </result>
<Interceptor-ref name = "jloginstack"/>
</Action>
</Package> (2)
Set in action:
..........
Hits hits = jluceneutils. lucenesearch (indexpath, searchmess );
System. Out. println ("---------- hits. Length ():" + hits. Length ());
For (int A = 0; A Document doc2 = (document) hits.doc ();
System. Out. println (searchmess + "value:" + doc2.get ("confcontext "));
Actioncontext. getcontext (). getsession (). Put ("jsearch_value", doc2.get ("confcontext "));
}
Actioncontext. getcontext (). getsession (). Put ("jsearch_cout", hits. Length ());
Actioncontext. getcontext (). getsession (). Put ("jsearch_name", searchmess); (3)
Set the template file: jsearch. FTL:
<# Assign S = jsptaglibs ["/WEB-INF/struts-tags.tld"]/>
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Jason search result </title>
</Head> <body>
<Table width = "98%" border = "0" align = "center" cellpadding = "5" cellspacing = "0">
<Tr>
<TD> <strong> the result is obtained by Jason using Lucene. A total of $ {jsearch_cout} items meet the following requirements: </strong> </TD>
</Tr>
<Tr>
<# -- Freemarker interpolation (as follows, the El language is used to put the value in the action into session/Request/application first) -->
<TD> query content: $ {jsearch_name} --- query value: $ {jsearch_value} </TD>
</Tr>
<Tr>
<TD>
<@ S. url action = "jlogin! Login "id =" login "/>
<A href = "$ {login}"> return to the logon homepage </a>
</TD>
</Tr>
</Table>
</Body>
</Html> (4)
If you want to use the struts2.0 tag, as shown above, you need to add the struts2.0 tag Library:
Add web. xml:
<Servlet>
<Servlet-Name> jspsuppservlet servlet </servlet-Name>
<Servlet-class>
Org. Apache. struts2.views. jspsuppservlet Servlet
</Servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>
Add the following at the beginning of jsearch. FTL:
<# Assign S = jsptaglibs ["/WEB-INF/struts-tags.tld"]/> 2. Use freemarker in JavaThe freemarker template is A. FTL text file that uses some special freemarker tags that are dynamically displayed or output by the control program. The template file code is as follows:
$ {Name}, hello! $ {MSG}
The content similar to $ {} is dynamic, called "interpolation". To use freemarker to merge values in the data model into the template file, follow these steps:
1. Create a configuration instance to manage the template loading path of freemarker and generate a template instance.
2. Use the configuration instance to generate a template instance.
3. Fill in the data model. The data model is a map object.
4. Call the process method of the template instance to complete the merge. The following is a Java program that uses freemarker to create the output. The program source code is as follows:
Package Lee;
Import java. util .*;
Import java. Io .*;
Import freemarker. template. *; public class hellofreemarker
{
Private configuration CFG;
Public void Init () throws exception
{
// Initialize freemarker Configuration
// Create a configuration instance
CFG = new configuration ();
// Set the location of the freemarker Template File
Cfg. setdirectoryfortemplateloading (new file ("templates "));
}

Public void process () throws exception
{
Map root = new hashmap ();
Root. Put ("name", "freemarker! ");
Root. Put ("MSG", "you have completed the first freemarker example ");
Template T = cfg. gettemplate ("test. FTL ");
T. Process (root, new outputstreamwriter (system. Out);} public static void main (string [] ARGs) throws exception
{
Hellofreemarker HF = new hellofreemarker ();
HF. INIT ();
HF. Process ();
}
}
The above Code creates a map instance, which serves as the data model of the template file. To use freemarker, you must import the freemarker. jar file, Freemarker's official website is Http://freemarker.sourceforge.net/ , Although freemarker can be used in Java programs, it is usually used to generate HTML pages. 3. Use freemarker in Web ApplicationsUsing freemarker in Web applications is not much different from using freemarker in Java programs. The following is an example of using freemarker in web. The template file used to generate HTML pages is as follows:
<HTML>
<Head>
<Title> freemarker's helloworld </title>
</Head>
<Body>
$ {Message}
</Body>
</Html>
When we use freemarker in Web applications, Servlet should be used to merge templates and data. Therefore, servlet is responsible for creating configuration instances and merging templates and data. below is the Servlet Source Code:
Package Lee;
Import java. util .*;
Import java. Io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import freemarker. template. *; public class helloservlet extends httpservlet
{
Private configuration CFG;
Public void Init ()
{
// Initialize freemarker Configuration
// Create a configuration instance
CFG = new configuration ();
// Set the location of the freemarker Template File
Cfg. setservletcontextfortemplateloading (getservletcontext (), "WEB-INF/templates ");
}

Public void Service (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception
{
// Create a data model
Map root = new hashmap ();
Root. Put ("message", "Hello freemarker! ");
// Obtain the Template File
Template T = cfg. gettemplate ("test. FTL ");
// Start preparing to generate the output
//-Use the charset of the template file as the charset of this page
//-Use text/html mime-type
Response. setcontenttype ("text/html; charset =" + T. getencoding ());
Writer out = response. getwriter ();

// Merge data models and templates and output the results to the out
Try
{
T. Process (root, out );
}
Catch (templateexception E)
{
Throw new servletexception ("error in processing template", e );
}
}
}
We can see that the servlet class code is roughly the same as that of freemarker in common Java programs. There are two differences: 1. The method for setting freemarker to load templates is different, in servlet, the loading method is setservletcontextfortemplateloading. The first parameter is the servletcontext of the Web application, and the second parameter is the template file path .; 2. The result must be output to httpservletresponse to be loaded by the browser.
The following code configures the servlet web. xml file:
<Web-app>
<Servlet>
<Servlet-Name> Hello </servlet-Name>
<Servlet-class> Lee. helloservlet </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-Name> Hello </servlet-Name>
<URL-pattern>/Hello </url-pattern>
</Servlet-mapping>
</Web-app> 4. freemarker Template FileThe preceding example shows that the freemarker template file is not much more complex than the HTML page. The freemarker template file consists of the following four parts:
1. Text: directly output
2. Note: <# --... --> the format is not output.
3. interpolation: that is, the section in the format of $ {...} Or # {...} will be replaced by the Section in the data model.
4. FTL command: Specify freemarker. Similar to HTML Tag, add # Before the name to differentiate it. The following is an example of a freemarker template, which contains the four parts mentioned above.
<HTML> <br>
<Head> <br>
<Title> welcome! </Title> <br>
</Head> <br>
<Body> <br>
<# -- Comment --> <br>
<# -- Use interpolation below -->
<H1> welcome $ {user }! </H1> <br>
<P> we have these animals: <br>
<U1> <br>
<# -- Use the FTL command -->
<# List animals as being> <br>
<Li >$ {being. name} for $ {being. Price} euros <br>
<# List> <br>
<U1> <br>
</Body> <br>
</Html>
Related Article

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.