Freemarker例子(struts2实现)

FreeMarker是一个基于Java的开发包和类库的一种将模板和数据进行整合并输出文本的通用工具,FreeMarker实现页面静态化的原理是:将页面中所需要的样式写入到FreeMarker模板文件中,然后将页面所需要的数据进行动态绑定并放入到Map中,然后通过FreeMarker的模板解析类process()方法完成静态页面的生成

这里写图片描述

例子:
struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
          "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <!-- 开发模式开启 -->
    <constant name="struts.devMode" value="true" />
    <package name="person" namespace="/" extends="struts-default">
        <action name="*" class="com.action.PersonAction" method="{1}">
            <result name="list" type="redirect">${url }.html</result>
            <result name="update" type="redirect">${url }.html</result>

        </action>
    </package>
</struts>

bean层:代码不贴出来了,有三个属性id(Int)、name(String)、age(Int)

action层:

public String getAll() throws Exception {
        CreateHtml createHtml = new CreateHtml();
        Map<String, List<Person>> map = new HashMap<String, List<Person>>();
        map.put("personlist", new PersonDao().query());
        System.out.println(map);
        String htmlName = "personList";
        String ftl = "list.ftl";

        try {
          createHtml.init(ftl, htmlName, map);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (TemplateException e) {
          e.printStackTrace();
        }
        url = "/"+htmlName;
        return "list";
    }

    public String addPage() throws Exception {
        CreateHtml createHtml = new CreateHtml();
        //Map<String, List<Person>> map = new HashMap<String, List<Person>>();
        //map.put("personlist", new PersonDao().query());
        String htmlName = "add";
        String ftl = "add.ftl";

        try {
          createHtml.init(ftl, htmlName, null);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (TemplateException e) {
          e.printStackTrace();
        }
        url = "/"+htmlName;
        System.out.println(url);
        return "addPage";
    }

    public String add() throws Exception {
        new PersonDao().add(p);
        return getAll();
    }

Dao层:

public void add(Person p){
        String sql="insert into person(name,age) values(?,?)";
        try {
            qr.update(sql,p.getName(),p.getAge());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
    public List<Person> query(){
        String sql="select * from person";
        try {
            return qr.query(sql,new BeanListHandler<Person>(Person.class));
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

Freemarker模板生成方法类


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 CreateHtml {
     /**
     * 
     * @param ftl       模版名.ftl
     * @param htmlName  静态页面的名字
     * @param map       数据
     * @throws IOException
     * @throws TemplateException
     */

    public void init(String ftl, String htmlName, Map map) throws IOException, TemplateException {

          //创建负责管理 FreeMarker模板的 Configuration对象
          Configuration cfg = new Configuration();

          //指定创建的FreeMarker模板文件的位置
          cfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/WEB-INF/template/");
          //不指定编码格式,则页面会乱码
          cfg.setEncoding(Locale.getDefault(), "utf-8");

          //创建Template对象
          Template template = cfg.getTemplate(ftl);
          template.setEncoding("utf-8");

          //设置文件类型
          htmlName=htmlName+".html";
          //设置页面保存位置
          String path = ServletActionContext.getServletContext().getRealPath("/");
          System.out.println("===静态页面path=="+path+"  "+htmlName);

          File fileName = new File(path + htmlName);
          Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
          //将数据与模版整合,生成静态页面
          template.process(map, out);
          //关闭流
          out.flush();
          out.close();
    }

}

Freemarler模板
1、列表页面 list.ftl
2、增加页面 add.ftl

1、list.ftl

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head> 
    <title>Person|list</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <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">
    <style type="text/css">
    a{
        text-decoration: none;
    }
    table{
        width:500px;
        text-align: center;
        border:solid 2px #ccc;
    }
    th,td{
        border:solid 2px #ccc;
    }
    </style>
  </head>
  <body>
      <center>

      <form action="queryLike.action" method="post">
        <input type="text" name="msg" placeholder="name or age"><input type="submit" value="查询">
      </form>
          <table>
                <tr>
                    <th>ID</th>
                    <th>name</th>
                    <th>age</th>
                    <th>action|<a href="addPage.action">添加</a></th>
                </tr>

              <#list personlist as p>   
                <tr>
                    <td>${p.id }</td>
                    <td>${p.name }</td>
                    <td>${p.age }</td>
                    <td>
                        <a href="queryById.action?id=${p.id}">修改</a> | <a href="delete.action?id=${p.id}">删除</a>
                    </td>
                </tr>
            </#list>
        </table>
       </center>
  </body>
</html>

2、add.ftl
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head> 
    <title>Person|add</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <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">

  </head>
  <body>
    <center>
        <form action="add.action" method="post">
            <h2>添加</h2>
            姓名:<input type="text" name="name"><br>
            年龄:<input type="text" name="age"><br>
            <input type="submit" value="提交">
        </form>     
    </center>
  </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值