以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设定
Log4jInit
com.log4j.Log4jInit
log4j-init
WEB-INF/classes/log4j.properties
1
freemarkertest
com.servlet.FreemarkerList
4
freemarkertest
/testfree
index.jsp
500
/jsp/error.jsp
404
/jsp/error.jsp
400
/jsp/error.jsp
3,ftl模板文件testfm.ftl ,内容:
freemarker测试
${message},${name}
<#list myList as lst>
- ${lst}
#list>
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.
*
* 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.
*
* @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