FreeMarker generation page (3): freemarker generation page

Source: Internet
Author: User

FreeMarker generation page (3): freemarker generation page

This article introduces Freemarker's core functions, or what problems it can solve. In the first article, we mentioned that Freemarker is a template language. What is a template language.

 

I also searched for information on the Internet in a short time. The following is a blog I found about Java template technology, I think the template I want to know is basically mentioned in this blog. If you are interested, visit http://blog.csdn.net/logic_202/article/details/573850.

 

I will briefly summarize the template language I understand. In essence, it is a placeholder Dynamic Replacement Technology. The EL expressions that we often use in web development, struts tablib and other technologies are also a placeholder Dynamic Replacement Technology. But Freemarker is different from them. The first blog mentioned that Freemarker is an independent template technology that runs independently from servlet containers, this is different from the jsp technology we often use. Jsp can run only when it depends on the servlet container, because jsp is essentially a servlet. Jsp is used to transmit data to the foreground through the request stream, while Freemarker only needs to input a POJO to the page instead of the request object to transmit data to the foreground.

 

An example is provided after you have understood the template language!

1. Create a web project in MyEclipse and add the jar package of Freemarker. Create a templates folder under the WebRoot folder to store the page template to be output.


2. Compile a template

Create a file named ftl and put it in the templates folder. The content of the file is as follows.



(Note: If the file is red after the file is created, you can use the following method to remove it)

 

3. obtain data using background code

The data we need from the above ftl file is: $ {title}, userList, $ {user. id}, $ {user. name}; then we need to pass the data to these placeholders in the background.

 

Code in FreeMarkerHandler class:

Package com. ftl; import java. io. IOException; import java. io. printWriter; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import com. entity. user; import freemarker. template. configuration; import freemarker. template. template; import freemarker. template. templateException; public class FreeMarkerHandler extends HttpServlet {private Configuration configuration = null; // explains the Configuration // constructor public FreeMarkerHandler () {// creates a Configuration instance configuration = new Configuration (); // The default encoding type configuration of the output data. setDefaultEncoding ("UTF-8") ;}@ SuppressWarnings ("unchecked") public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// ------------- 1. prepare data --------------- // Map dataMap = new HashMap () as the data file to be filled in; // the container that interprets the data // Add the data dataMap. put ("title", "FreeMarker example"); List <User> userList = new ArrayList <User> (); User user1 = new User (); user1.setId ("1"); user1.setName ("Xiaoyi"); User user2 = new User (); user2.setId ("2"); user2.setName ("ears"); userList. add (user1); userList. add (user2); dataMap. put ("userList", userList); // put the data in Map // ------------------------------------------- // --------------- 2. method for setting template loading (multiple methods are available)-// two methods are described: configuration. setServletContextForTemplateLoading (getServletContext (), "templates"); // configuration. setClassForTemplateLoading (this. getClass (), "/com/template"); // ----------------------------------------- // ------------------ 3. obtain the Template -------------- // obtain the template to be loaded = null; try {Template = configuration. getTemplate ("hello. ftl "); template. setEncoding ("UTF-8");} catch (IOException e) {e. printStackTrace ();} // ----------------------------------------- // -------------- 4. 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 =" + template. getEncoding (); PrintWriter out = response. getWriter (); // combines the data model and template, and outputs the result to try {template. process (dataMap, out); // use a template to develop a servlet. You can only add dynamic data to the Code} catch (TemplateException e) {throw new ServletException ("error occurred in Template processing", e );}//------------------------------------------}}

4. configuration information in web. xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  <servlet>    <servlet-name>FreeMarkerHandler</servlet-name>    <servlet-class>com.ftl.FreeMarkerHandler</servlet-class></servlet><servlet-mapping>    <servlet-name>FreeMarkerHandler</servlet-name>    <url-pattern>*.do</url-pattern></servlet-mapping></web-app>

5. index. jsp provides the access location

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 


6. Display Results

Deploy the project to tomcat, and then access the project to see the effect.



Summary

The preceding test example does not use any web framework. In fact, this template language can be used with our commonly used frameworks. I have found some relevant materials and shared them with you, if you are interested, go and check it out!

Freemarker all documents: http://www.open-open.com/doc/list/101? O = p

Example: http://www.zuidaima.com/share/kfreemarker-p1-s1.htm

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.