This article introduces the core functions of Freemarker, or what problems it appears to solve. In the first article, I mentioned that Freemarker is a template language, so what is a template language?
I also searched for information on the Internet not long after I got in touch. The following is a blog I found that introduced Java template technology. I thought it was written clearly and I thought I wanted to know. The knowledge about templates is basically covered in this blog. If you are interested, you can take a look:.
I will briefly summarize what I understand about the template language. Essentially, it is a placeholder dynamic replacement technology. The EL expressions, struts tablib and other technologies we often use in web development are also placeholder dynamic replacement technologies. But Freemarker is different from them. The first blog mentioned that Freemarker is an independent template technology. It runs independently from the servlet container. This is different from the jsp technology we often use. Jsp must rely on the servlet container to run, because jsp is essentially a servlet. Using the jsp mechanism, data is transmitted to the frontend through the request stream. In Freemarker, transmitting data to the frontend only requires passing a POJO to the page instead of the request object.
After briefly understanding the template language, let’s implement an example!
1. Create a web project on MyEclipse, and then add the Freemarker jar package; create a new templates folder under the WebRoot folder to store the page templates that need to be output.
Create a new file named ftl and place it in the templates folder. The content of the file is as follows.
(Note: If the file is red after creating the file, you can use the following method to eliminate it)
From the above ftl file, the data we need is: ${title}, userList, ${user.id }, ${user.name}; then we need to pass the data on these placeholders to her in the background
Code in the 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; //解释Configuration //构造函数 public FreeMarkerHandler(){ //创建Configuration实例 configuration = new Configuration(); //输出的数据默认的编码类型 configuration.setDefaultEncoding("utf-8"); } @SuppressWarnings("unchecked") public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { //---------------1.准备数据----------------- //要填入的数据文件 Map dataMap = new HashMap();//解释数据的容器 //添加数据 dataMap.put("title", "FreeMarker示例"); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setId("1"); user1.setName("小依"); User user2 = new User(); user2.setId("2"); user2.setName("小耳"); userList.add(user1); userList.add(user2); dataMap.put("userList", userList); //将数据放到Map中 //--------------------------------------- //---------------2.设置模板装载的方法(有多种方法)- //介绍两种方法: configuration.setServletContextForTemplateLoading(getServletContext(),"templates");// configuration.setClassForTemplateLoading(this.getClass(),"/com/template"); //--------------------------------------- //----------------3.获得模板---------------- //获得需要装载的模版 Template template = null; try { template = configuration.getTemplate("hello.ftl"); template.setEncoding("utf-8"); } catch (IOException e) { e.printStackTrace(); } //--------------------------------------- //--------------4.开始准备生成输出-------------- //使用模版文件的charset作为本页面的charset //使用text/html MIME-type response.setContentType("text/html; charset=" + template.getEncoding()); PrintWriter out = response.getWriter(); //合并数据模型和模版,并将结果输出到out中 try { template.process(dataMap,out);// 用模板来开发servlet可以只在代码里面加入动态的数据 } catch(TemplateException e) { throw new ServletException("处理Template模版中出现错误", e); } //------------------------------------------ } }
<?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>
<%@ 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"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 点击下面链接查看效果: <hr> <a href="freeMarkerHandler.do">点击查看效果</a> </body></html>
Deploy the project Go to tomcat and then access to see the effect.
The above test examples do not use any web framework. In fact, this template language can be used with our commonly used frameworks Yes, I have found some relevant information to share with you. If you are interested, you can check it out!
Freemarker full documents: http://www.open-open.com/doc/list/101?o=p
Specific examples: http://www.zuidaima.com/ share/kfreemarker-p1-s1.htm