>  기사  >  웹 프론트엔드  >  FreeMarker之生成页面(三)_html/css_WEB-ITnose

FreeMarker之生成页面(三)_html/css_WEB-ITnose

WBOY
WBOY원래의
2016-06-24 11:52:211224검색

       这篇文章介绍Freemarker最核心的功能,或者说它的出现是用来解决什么问题的。在第一篇提到了Freemarker是一种模板语言,那么什么叫做模板语言呢。

 

       自己也是接触没多久就在网上搜了搜资料,下面是我搜到的一篇介绍Java模板技术的博客觉得写的听清楚的,觉得我想知道的关于模板的知识,这篇博客中基本上都讲到了,有兴趣的可以看看:。

 

       我简单的总结一下我理解的模板语言,从本质上讲他就是一个占位符动态替换技术。而我们在web开发中经常使用的EL表达式,struts tablib等技术也是一种占位符动态替换技术。但是Freemarker和他们却有不同的地方,第一篇博客中提到了Freemarker是一种独立的模板技术,他是脱离servlet容器独立运行的,这一点与我们平时经常使用的jsp技术是不同的。Jsp必须依赖servlet容器才可以运行,因为jsp本质上就是servlet。使用jsp这种机制,向前台传送数据是通过request流中,而Freemarker中向前台传送数据只需要向页面传入一个POJO就行而不是request对象。

 

简单了解模板语言之后就来实现一个例子吧!

1. 在MyEclipse上创建一个web项目,然后添加Freemarker的jar包; 在WebRoot文件夹下新建templates文件夹,用于存放需要输出的页面模板。

    

2. 编写模板

新建名为ftl的文件放到templates文件夹中,文件的内容如下所示。

  


(注意:如果创建文件之后文件报红,可以使用如下的方式就可以消除)

 

3. 后台代码获得数据

从上面的ftl文件中得出我们需要的数据有:${title},userList,${user.id},${user.name};那么我们在后台就需要传递给她这些占位符上数据

 

FreeMarkerHandler类中的代码:

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);        }      //------------------------------------------        	}	}</user></user>

4. 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提供访问位置

      <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">	-->       	 点击下面链接查看效果:	<hr>	<a href="freeMarkerHandler.do">点击查看效果</a>   


6. 效果展示

将项目部署到tomcat上,然后访问就可以看到效果了。



总结

以上测试的例子没有使用任何的web框架,其实这种模板语言是可以和我们常用的框架一起使用的,自己查找到了一些相关的资料分享给大家,有兴趣的可以去看看!

       Freemarker全部文档:http://www.open-open.com/doc/list/101?o=p

       具体实例:http://www.zuidaima.com/share/kfreemarker-p1-s1.htm

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.