【学习笔记】FreeMarker 之于Servlet与Stuts2的应用
FreeMarker应用在Servlet(0配置web.xml形式):
准备环境:
tomcat7、eclipse最新版、jdk1.8、freemarker v2.3.20.jar
举例项目结构图:
创建DynamicWebProject,在WEB-INF/lib中引入freemarker.jar
在WEB-INF下创建templates文件夹,在templates文件夹下创建test.ftl模板文件
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Test Freemarker by servlet</title> 6 </head> 7 <body> 8 ${message} 9 </body> 10 </html>
创建FreeMarkerServlet
1 package com.github.hellxz; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import freemarker.template.Configuration; 15 import freemarker.template.Template; 16 import freemarker.template.TemplateException; 17 18 /** 19 * Servlet implementation class FreeMarkerServlet 20 */ 21 @SuppressWarnings("serial") 22 @WebServlet("/test") 23 public class FreeMarkerServlet extends HttpServlet { 24 25 Configuration conf; //声明FreeMarker配置文件 26 @Override 27 public void init() throws ServletException { 28 super.init(); 29 conf = new Configuration();//初始化FreeMarker配置文件 30 //设置模板文件目录 31 conf.setServletContextForTemplateLoading(getServletContext(), "/WEB-INF/templates"); 32 } 33 34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 //数据模型 36 Map<String,Object> root = new HashMap<>(); 37 root.put("message", "本条消息由servlet转发FreeMarker展现"); 38 //设置字符集,防止乱码 39 response.setCharacterEncoding("UTF-8"); 40 //获取输出流 41 PrintWriter writer = response.getWriter(); 42 //获取模板 43 Template template = conf.getTemplate("test.ftl"); 44 try { 45 //生成html文件并输出 46 template.process(root, writer); 47 } catch (TemplateException e) { 48 e.printStackTrace(); 49 } 50 writer.flush(); 51 writer.close(); 52 } 53 54 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 55 doGet(request, response); 56 } 57 58 }
启动tomcat查看输出:
Struts2实现FreeMarker模板应用:
准备环境:
struts-2.5.14.1(min)、tomcat7、eclipse最新版、jdk1.8、freemarker v2.3.20.jar
举例项目结构图:
lib中引入官网下载的struts2 min必要jar包
将struts2.core解压找到struts-tags.tld放入WEB-INF中(为了能让模板支持类struts标签)
WebContent下新建success.ftl模板文件:
1 <#assign s=JspTaglibs["/WEB-INF/struts-tags.tld"] /> <#--这一句是为了让Freemarker识别struts2的标签 --> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4 <head> 5 <title>My JSP 'index.jsp' starting page</title> 6 <meta http-equiv="pragma" content="no-cache"> 7 <meta http-equiv="cache-control" content="no-cache"> 8 <meta http-equiv="expires" content="0"> 9 <meta http-equiv="description" content="This is my page"> 10 <!-- 11 <link rel="stylesheet" type="text/css" href="styles.css"> 12 --> 13 </head> 14 <body> 15 <h1>${companyName}</h1> 16 <@s.form action="reg" > 17 <@s.textfield label="用户名" name="uname" /> 18 <@s.submit /> 19 </@s.form> 20 </body> 21 </html>
WEB-INF下创建web.xml文件(filter-class中注掉的是老版本的,请按照实际能找到的类进行配置,否则会报ClassNotFoundException)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 <filter> 11 <filter-name>struts2</filter-name> 12 <filter-class> 13 org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter 14 <!-- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter --> 15 </filter-class> 16 </filter> 17 <filter-mapping> 18 <filter-name>struts2</filter-name> 19 <url-pattern>/*</url-pattern> 20 </filter-mapping> 21 22 <servlet> 23 <servlet-name>freemarker</servlet-name> 24 <servlet-class> 25 freemarker.ext.servlet.FreemarkerServlet 26 </servlet-class> 27 <!--下面的配置freemarke的ftl文件的位置 --> 28 <init-param> 29 <param-name>TemplatePath</param-name> 30 <param-value>/</param-value> 31 </init-param> 32 <!-- 是否和服务器(tommcat)一起启动。0为不。1为是--> 33 <load-on-startup>1</load-on-startup> 34 </servlet> 35 36 <servlet-mapping> 37 <servlet-name>freemarker</servlet-name> 38 <url-pattern>*.ftl</url-pattern> 39 </servlet-mapping> 40 41 42 <servlet> 43 <!-- define a JspSupportServlet Object --> 44 <servlet-name>JspSupportServlet</servlet-name> 45 <servlet-class>org.apache.struts2.views.JspSupportServlet</servlet-class> 46 <!-- setting JspSupportServlet auto start --> 47 <load-on-startup>1</load-on-startup> 48 </servlet> 49 50 </web-app> 51 52 53 54
在src下新建TestAction类(注意包名):
1 package test; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 public class TestAction extends ActionSupport { 6 7 private String companyName="北京尚学堂"; 8 9 //不指定方法默认执行此方法 10 public String execute() throws Exception { 11 System.out.println("TestAction.execute()"); 12 return SUCCESS; 13 } 14 15 public String getCompanyName() { 16 return companyName; 17 } 18 19 public void setCompanyName(String companyName) { 20 this.companyName = companyName; 21 } 22 23 24 }
src下创建struts.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> 3 <struts> 4 <constant name="struts.devMode" value="true" /> 5 <constant name="struts.i18n.encoding" value="utf8" /> 6 <constant name="struts.enable.DynamicMethodInvocation" value="true" /> 7 <package name="default" extends="struts-default"> 8 <action name="test" class="test.TestAction"> 9 <result name="success" type="freemarker">success.ftl</result> 10 </action> 11 </package> 12 13 14 </struts>
启动tomcat并测试: