采用freemarker静态化页面以及freemarker视图展现简介

以freemarker为展现方式或以freemarker ftl模板为框架生成静态化页面:

freemarker库:freemarker-2.3.19.jar

涉及4种应用方式

1,页面静态化之Servlet中使用freemarker
2,页面展现之Struts2结合freemarker使用
3,页面静态化之Struts2结合freemarker使用
4,页面展现之Servlet中使用freemarker(略,改一下输出流即可)

一,页面静态化之Servlet中使用freemarker

目标:
以freemarker的ftl模板文件为页面框架,
实现以html静态页面方式展现http servlet请求,html文件不存在时servlet生成html文件并重定向至该html页面,html文件存在时直接重定向至该html页面

1,java web项目文件目录设定
静态页面输出目录:WebRoot/html/
ftl模板目录:WebRoot/templates/

2,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">

 <servlet>
 	<servlet-name>Log4jInit</servlet-name>
 	<servlet-class>com.log4j.Log4jInit</servlet-class>
 	<init-param>
 		<param-name>log4j-init</param-name>
 		<param-value>WEB-INF/classes/log4j.properties</param-value>
 	</init-param>
 	<load-on-startup>1</load-on-startup>
 </servlet>
 
  <servlet>
 	<servlet-name>freemarkertest</servlet-name>
 	<servlet-class>com.servlet.FreemarkerList</servlet-class>
 	<load-on-startup>4</load-on-startup>
 </servlet>
 <servlet-mapping>
 	<servlet-name>freemarkertest</servlet-name>
 	<url-pattern>/testfree</url-pattern> 	
 </servlet-mapping> 
 
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list> 
 <error-page>
  <error-code>500</error-code>
  <location>/jsp/error.jsp</location>
 </error-page> 
  <error-page>  
  <error-code>404</error-code>
  <location>/jsp/error.jsp</location>
 </error-page>
<error-page>
  <error-code>400</error-code>
  <location>/jsp/error.jsp</location>
 </error-page>
</web-app>
<strong><span style="font-size:12px;">
</span></strong>

3,ftl模板文件testfm.ftl ,内容:

扫描二维码关注公众号,回复: 654945 查看本文章
<html>  
  <head>  
  	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>freemarker测试</title>  
  </head>  
    <body>  
        <h1>${message},${name}</h1>
        
        
        <ol>
        <#list myList as lst>
        	<li><a href="javascript:void(0)"> ${lst}</a>  </li>
        </#list>
        </ol>
          
    </body>     
</html> 

4,Servlet内容

package com.servlet;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/** * 
 * 页面静态化之Servlet中使用freemarker *
 */
public class FreemarkerList extends HttpServlet {
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	
	// 负责管理FreeMarker模板的Configuration实例  
    private Configuration cfg = null;  
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
		 // 创建一个FreeMarker实例  
        cfg = new Configuration();  
        // 指定FreeMarker模板文件的位置  
        cfg.setServletContextForTemplateLoading(this.getServletContext(),"templates");  
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
        // 建立数据模型  
        Map root = new HashMap();  
        root.put("message", "hello");  
        root.put("name", "java中文");  
        root.put("myList", Arrays.asList(new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M"}));
        // 获取模板文件  
        Template t = cfg.getTemplate("testfm.ftl","utf-8");     //如果未指定编码,那么展现html时中文是乱码        
        resp.setContentType("text/html;charset=UTF-8"  ); 
        resp.setCharacterEncoding("utf-8");
        
        try {  
        	String contextpath = this.getServletContext().getRealPath("") + "/html/";//绝对路径
        	String fname =  sdf.format(new Date()) + ".html";
            File f = new File(contextpath + fname);//绝对路径
            if(f.exists()){//已存在文件
            	resp.sendRedirect("html/" + fname);//相对项目根目录,重定向
            }else{//还没生成文件时
            	Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),Charset.forName("utf-8")));            	
                t.process(root, out); // 往模板里写数据  ,   先生成文件
                out.flush();
                out.close();
                resp.sendRedirect("html/"+ fname);//相对项目根目录,重定向,页面静态化
            }                        
            
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
	}
	
}


5,测试

浏览器输入url:http://localhost:8080/prjname/testfree
html/20160419.html文件存在或不存在时,浏览器地址栏都变为:http://localhost:8080/prjname/html/20160419.html,
内容:

hello,java中文
1.A
2. B
3. C
4. D
5. E
6. F
7. G
8. H
9. I
10. J
11. K
12. L
13. M


二,页面静态化之Struts2结合freemarker使用
目标:
以freemarker的ftl模板文件为页面框架,实现以html静态页面方式展现Action请求,html文件不存在时Action生成html文件并重定向至该html页面,html文件存在时直接重定向至该html页面
三,页面展现之Struts2结合freemarker使用
目标:
以freemarker的ftl模板文件为页面框架,freemarker为视图,实现动态显示页面内容

--------------------------------------------------------------
1,java web项目文件目录设定

静态页面输出目录:WebRoot/html/
ftl模板目录:WebRoot/templates/
2,web.xml设定

3,struts.xml设定
采用convention注解方式,xml略

4,Action类内容
页面静态化之Struts2结合freemarker使用,Action方法为turndir(),结果类型redirect;
页面展现之Struts2结合freemarker使用,Action方法为resftl(),结果类型freemarker;

package com.actions;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionSupport;
import freemarker.template.Configuration;
import freemarker.template.Template;

/** * 
 * Struts2结合Struts2结合freemarker使用,页面静态化 以及 以ftl模板为视图展现方式
 *
 */
@Results(value = { 
		@Result(name="ftl",type="freemarker",location="/templates/testfm.ftl"  ) ,//注意拼写
		@Result(name="turndirection",type="redirect",location="${htmlurl}")
		
})
public class FreemarkertestAction extends ActionSupport {
	
	public HttpServletRequest request =  ServletActionContext.getRequest();
	public HttpServletResponse response = ServletActionContext.getResponse();

	/**
	 * 
	 */
	private static final long serialVersionUID = -8894067364939169084L;	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	public String htmlurl;

	public String getHtmlurl() {
		return htmlurl;
	}

	public void setHtmlurl(String htmlurl) {
		this.htmlurl = htmlurl;
	}
	
	String message;
	String name;
	List myList;
	
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List getMyList() {
		return myList;
	}

	public void setMyList(List myList) {
		this.myList = myList;
	}

	public String resftl(){		


        this.setMessage("hello");
        this.setName("Java 中文 Ftl Action");
        this.setMyList(Arrays.asList(new String[]{"a","b","c","d","e","f","g","h","I","J","K","L","M"}));    

		
		return "ftl";
	}
	
	public String turndir(){
		// 负责管理FreeMarker模板的Configuration实例  
	    Configuration cfg = null;  
	 // 建立数据模型  
        Map root = new HashMap();  
        root.put("message", "hello");  
        root.put("name", "java中文");  
        root.put("myList", Arrays.asList(new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M"}));
	    
		try {
			cfg = new Configuration();  
			// 指定FreeMarker模板文件的位置  
			
			String contextpath = ServletActionContext.getServletContext().getRealPath("/") + "/html/" ;
        	String fname =  sdf.format(new Date()) + ".html";			
			cfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(),"templates"); 
			cfg.setEncoding(Locale.getDefault(), "utf-8");
			Template t = cfg.getTemplate("testfm.ftl","utf-8");     //如果未指定编码,那么展现html时中文是乱码		
			
			response.setContentType("text/html;charset=UTF-8"  );
			
			
            File f = new File(contextpath + fname);//绝对路径
            if(f.exists()){//已存在文件
            	this.setHtmlurl("/html/" + fname);
            	return "turndirection";            	
            }else{//还没生成文件时
            	Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),Charset.forName("utf-8")));            	
                t.process(root, out); // 往模板里写数据       ,   先生成文件
                out.flush();
                out.close();
                this.setHtmlurl("/html/" + fname);
            }
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "turndirection";
	}
	
}


5,测试

测试静态页面生成展现浏览器输入url:http://localhost:8080/prjname/freemarkertest!turndir.do
正常内容:

hello,java中文
1.A
2. B
3. C
4. D
5. E
6. F
7. G
8. H
9. I
10. J
11. K
12. L
13. M


测试freemarker展现浏览器输入url:http://localhost:8080/prjname/freemarkertest!resftl.do
正常内容:

hello,Java 中文 Ftl Action
1. a
2. b
3. c
4. d
5. e
6. f
7. g
8. h
9. I
10. J
11. K
12. L
13. M



猜你喜欢

转载自fall10.iteye.com/blog/2315312