FreeMarker使用实例

来源:互联网 发布:淘宝网店没生意怎么办 编辑:程序博客网 时间:2024/04/29 12:08

 FreeMarker使用实例 - qincidong - qincidong的博客

所需Jar包:freemarker.jar本例使用了struts2commons-logging.jarognlXXX.jarstruts2-coreXXX.jarxwork.jar这是struts2必须的Jar包。在web.xml中加入struts2过滤器,拦截请求。<filter>  <filter-name>struts2</filter-name>  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping>  <filter-name>struts2</filter-name>  <url-pattern>/*</url-pattern> </filter-mapping>struts.xml配置:<!DOCTYPE struts PUBLIC        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"        "http://struts.apache.org/dtds/struts-2.0.dtd"><struts>    <package name="user" extends="struts-default" namespace="/user">       <action name="login" class="com.freemarker.test.LoginAction">         <result type="redirect">/${flag}</result>       </action>    </package></struts> JAVA类:StaticFreeMarker.javapackage com.freemarker.test;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.util.Locale;import java.util.Map;import org.apache.struts2.ServletActionContext;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;public class StaticFreemarker {  @SuppressWarnings("unchecked") public void init(String ftl,Map map,String htmlName,String fileName) throws IOException, TemplateException {  Configuration cfg = new Configuration();  cfg.setEncoding(Locale.getDefault(), "gbk");  cfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/" + fileName);    Template template = cfg.getTemplate(ftl);  template.setEncoding("gbk");    String path = ServletActionContext.getServletContext().getRealPath("/");  File file = new File(path + htmlName);  Writer  out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"gbk"));  template.process(map, out);  out.flush();  out.close(); }}User.javapackage com.freemarker.test;import java.io.Serializable;public class User implements Serializable{ /**  *   */ private static final long serialVersionUID = 1L;  private Integer id; private String name; private String password; public Integer getId() {  return id; } public void setId(Integer id) {  this.id = id; } public String getName() {  return name; } public void setName(String name) {  this.name = name; } public String getPassword() {  return password; } public void setPassword(String password) {  this.password = password; }}LoginAction.javapackage com.freemarker.test;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import com.opensymphony.xwork2.ActionSupport;import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH;import freemarker.template.TemplateException;public class LoginAction extends ActionSupport { /**  *   */ private static final long serialVersionUID = 1L; // 跳转标识 private String flag;  private User user; public String getFlag() {  return flag; } public void setFlag(String flag) {  this.flag = flag; }  public User getUser() {  return user; } public void setUser(User user) {  this.user = user; } @Override public String execute() {  if (user == null) {   this.flag = "login.jsp";  }  else {   StaticFreemarker sf = new StaticFreemarker();   Map map = new HashMap();   String htmlName = "success.html";      // 1.添加对象   map.put("user", this.user);   List<User> userList = new ArrayList<User>();   User user1 = new User();   user1.setId(100);   user1.setName("scott");   user1.setPassword("tiger");      User user2 = new User();   user2.setId(200);   user2.setName("root");   user2.setPassword("123");   userList.add(user1);   userList.add(user2);      // 添加集合   map.put("userList", userList);      // 添加bool值   map.put("isTrue", true);   try {    sf.init("test.ftl", map, htmlName, "demo");   } catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (TemplateException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }   this.flag = htmlName; // 决定要跳转到哪个页面  }  return SUCCESS; }}在webContent下有demo目录,其中有login.jsp和test.ftl文件。login.jsp<%@ page language="java" contentType="text/html;"    pageEncoding="utf-8"%>    <%@ taglib uri="/struts-tags" prefix="s"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>用户登录</title></head><body> <s:form action="/user/login.action">  <table>   <tr>    <td>用户名</td>    <td><input type="text" name="user.name"/></td>   </tr>   <tr>    <td>密码</td>    <td><input type="text" name="user.password"/></td>   </tr>   <tr align="center">    <td colspan="2">     <input type="submit" value="登录"/>    </td>   </tr>  </table>  </s:form></body></html> test.ftl:<html> <body>   您好,您已成功登录系统!<br>   以下是您的登录信息:<br>   用户名:${user.name}<br>   密码:${user.password}<br><br>      <span>以下为测试信息:<span><br>   <#list userList as user>    Id:${user.id}<br>    Name:${user.name}<br>    Pwd:${user.password}<br><br>   </#list>      <hr>   Boolean:<br>   <#if isTrue>       isTrue = true;   </#if> </body></html>


 

原创粉丝点击