freemarker集成maven的简单的应用

1.创建本地maven项目 ,在pom.xml中配置freemarker的架包

  
  4.0.0  
  cn  
  fmarker  
  0.0.1-SNAPSHOT  
  war  
    
    
      
      
         org.freemarker  
         freemarker  
         2.3.23  
      
      
    
  

2.在webapp的web-inf下的web.xml中配置freemarker的服务

  
  
  fmarker  
    
    index.html  
    index.htm  
    index.jsp  
    default.html  
    default.htm  
    default.jsp  
    
    
  freemarker  
  freemarker.ext.servlet.FreemarkerServlet  
      
    
    
    TemplatePath  
    /  
    
    
    
    NoCache  
    true  
    
    
    
    ContentType  
    text/html;charset=UTF-8  
    
      
    
    
    template_update_delay  
    0   
    
    
    default_encoding  
    UTF-8  
    
    
    
    number_format  
    0.##  
    
    
  1  
  
  
  
  freemarker  
  *.ftl  
   
  

3.在webapp创建一个ftl文件,运行后可以直接在浏览器上输入它的路径

<#list 1..10 as i>  
<#if (i_index+1)%2==0>  
    ${i}
<#else> ${i}

4.应用maven ,在数据库创建一张表用来存储,以新闻发布为例 ,新闻的标题 ,内容 ,HTML路径 ,发布时间


5.创建新闻后端上传项目 ,在pom.xml中配置架包

  
  4.0.0  
  cn  
  news  
  0.0.1-SNAPSHOT  
  war  
    
      
      
        mysql  
        mysql-connector-java  
        5.1.26  
      
      
    
    org.freemarker  
    freemarker  
     2.3.23  
    
   
    
    
    
    
      
        org.codehaus.mojo  
            tomcat-maven-plugin  
            1.1  
              
            UTF-8  
          
      
    
    
  

6.在src/main/resources中配置数据的资源文件 .properties

url=jdbc:mysql://localhost:3306/news  
drclass=com.mysql.jdbc.Driver  
userName=root  
password=123456  

7.配置调用数据源的方法

package model;  
  
import java.io.IOException;  
import java.io.InputStream;  
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.ResultSetMetaData;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
import java.util.Properties;  
  
  
  
public class Dbuit {  
    static Properties p = new Properties();  
    static{  
          
        InputStream is = Dbuit.class.getResourceAsStream("/jdbc.properties");  
        try {  
            p.load(is);  
        } catch (IOException e) {  
              
            e.printStackTrace();  
        }  
    }  
/*获取链接 
 * @return 
 *  
 */  
    public static Connection getConnection() throws Exception{  
        String url=p.getProperty("url");  
        String drclass=p.getProperty("drclass");  
        String userName=p.getProperty("userName");  
        String password=p.getProperty("password");  
        Class.forName(drclass);  
        //登录成功  
        Connection conn = DriverManager.getConnection(url,userName,password);  
          
        return conn;  
    }  
    //执行sql语句  
    public static int execute(String sql) throws Exception{  
        //连接数据库  
        Connection con=getConnection();  
        //预编译SQL语句  
        PreparedStatement pst=con.prepareStatement(sql);  
        //执行SQL语句  
        int i=pst.executeUpdate();  
        con.close();  
        pst.close();  
        return i;  
          
    }  
    //查询  
    public static List query(String sql) throws Exception{  
          
        //连接数据库  
        Connection con=getConnection();  
        //预编译SQL语句  
        PreparedStatement pst=con.prepareStatement(sql);  
        //执行SQL语句  
        ResultSet rs=pst.executeQuery();  
        //获取列名  
        ResultSetMetaData remd =rs.getMetaData();  
        List list=new ArrayList();  
        //获取列的个数  
        int columnCount =remd.getColumnCount();  
      
        while(rs.next()){  
            Map map= new HashMap();  
            for(int i=1;i<=columnCount;i++){  
                //获取列名  
                String colName=remd.getColumnName(i);  
                //获取列值  
                String colValue=rs.getString(i);  
                map.put(colName, colValue);  
            }  
            list.add(map);  
        }  
        con.close();  
        pst.close();  
        rs.close();  
        return list;  
          
    }  
      
      
}  

8.创建新闻上传,查询的方法

package model;  
  
import java.util.List;  
import java.util.Map;  
  
public class Mynews {  
    //发布新闻  
    public void inserNews(String title,String content,String newspath,String createtime) throws Exception{  
        String sql="insert into mynews(title,content,htmlpath,createtime)values('"+title+"','"+content+"','"+newspath+"','"+createtime+"')";  
        Dbuit.execute(sql);  
    }  
    //查询新闻  
    public List queryNews() throws Exception{  
        String sql="select * from mynews";  
         return Dbuit.query(sql);  
      
    }  
      
}  

9.创建上传新闻的页面

  
  
  
  
Insert title here  
  
  
    

新闻发布

标题:
内容:

10.controller层servlet的调用

package controller;  
  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStreamWriter;  
import java.io.Writer;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.HashMap;  
import java.util.Map;  
import java.util.UUID;  
  
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.DefaultObjectWrapper;  
import freemarker.template.Template;  
import model.Mynews;  
  
/** 
 * Servlet implementation class News 
 */  
public class News extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
  
    /** 
     * Default constructor.  
     */  
    public News() {  
        // TODO Auto-generated constructor stub  
    }  
    //调用插入,查询的方法  
    Mynews my= new Mynews();  
    //设计时间格式  
    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    //生成静态HTML存储的位置  
    public static final String HTML_DIR="E:\\html";  
    /** 
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        //设置字符集  
        response.setContentType("text/html;charset=UTF-8");  
        request.setCharacterEncoding("UTF-8");  
        //获取新闻的标题  
        String title=request.getParameter("title");  
        //获取新闻的内容  
        String content=request.getParameter("content");  
        //获取时间  
        Date date= new Date();  
        String dates=sdf.format(date);  
        //获取唯一的UUID  
        String uuid=UUID.randomUUID().toString();  
        try {  
          
            //生成HTML  
        Configuration config=new Configuration(Configuration.VERSION_2_3_23);    
            //模板文件的位置  
        config.setDirectoryForTemplateLoading(new File("src/main/resources"));    
        config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));  
        //把值注入HTML  
        Map root = new HashMap();  
        root.put("title", title);  
        root.put("content", content);  
        root.put("createtime", dates);  
        ////加载模板文件  -- 实例化模板对象  
        Template temp =config.getTemplate("news.ftl");  
       //文件的保存路径  
        String sa=HTML_DIR+"/"+(uuid)+".html";  
        Writer out =new OutputStreamWriter(new FileOutputStream(sa));    
        //文件的输出  
        temp.process(root, out);    
        out.flush();   
        out.close();  
        //新闻上传到数据库  
        my.inserNews(title, content, (uuid) + ".html", dates);  
        response.getWriter().println("发布成功...");  
        } catch (Exception e) {  
              
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
          
        doGet(request, response);  
    }  
  
}  

11.新闻的模板

${title}

${createtime}
${content}

12.创建前端freemarker项目,在本地pom.xml中配置依赖的架包

  
  4.0.0  
  cn  
  new  
  0.0.1-SNAPSHOT  
  war  
    
      
      
        mysql  
        mysql-connector-java  
        5.1.26  
      
      
    
      org.freemarker  
      freemarker  
      2.3.23  
    
    
    
     org.apache.commons  
     commons-io  
     1.3.2  
  
    
    
    
    
      
        org.codehaus.mojo  
        tomcat-maven-plugin  
        1.1  
          
        UTF-8  
          
      
    
    
  

13.配置连接数据库的四要素,在src/main/resources中创建 .properties文件

url=jdbc:mysql://localhost:3306/news  
drclass=com.mysql.jdbc.Driver  
userName=root  
password=123456  

14.调用封装jdbc的方法类

package model;  
  
import java.io.IOException;  
import java.io.InputStream;  
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.ResultSetMetaData;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
import java.util.Properties;  
  
  
  
public class Dbuit {  
    static Properties p = new Properties();  
    static{  
          
        InputStream is = Dbuit.class.getResourceAsStream("/jdbc.properties");  
        try {  
            p.load(is);  
        } catch (IOException e) {  
              
            e.printStackTrace();  
        }  
    }  
/*获取链接 
 * @return 
 *  
 */  
    public static Connection getConnection() throws Exception{  
        String url=p.getProperty("url");  
        String drclass=p.getProperty("drclass");  
        String userName=p.getProperty("userName");  
        String password=p.getProperty("password");  
        Class.forName(drclass);  
        //登录成功  
        Connection conn = DriverManager.getConnection(url,userName,password);  
          
        return conn;  
    }  
      
    //执行sql  
    public static int execute(String sql) throws Exception{  
        //连接数据库  
        Connection con=getConnection();  
        //预编译SQL语句  
        PreparedStatement pst=con.prepareStatement(sql);  
        //执行SQL语句  
        int i=pst.executeUpdate();  
        con.close();  
        pst.close();  
        return i;  
          
    }  
    //查询  
    public static List query(String sql) throws Exception{  
          
        //连接数据库  
        Connection con=getConnection();  
        //预编译SQL语句  
        PreparedStatement pst=con.prepareStatement(sql);  
        //执行SQL语句  
        ResultSet rs=pst.executeQuery();  
        //获取列名  
        ResultSetMetaData remd =rs.getMetaData();  
        List list=new ArrayList();  
        //获取列的个数  
        int columnCount =remd.getColumnCount();  
      
        while(rs.next()){  
            Map map= new HashMap();  
            for(int i=1;i<=columnCount;i++){  
                //获取列名  
                String colName=remd.getColumnName(i);  
                //获取列值  
                String colValue=rs.getString(i);  
                map.put(colName, colValue);  
            }  
            list.add(map);  
        }  
        con.close();  
        pst.close();  
        rs.close();  
        return list;  
          
    }  
      
      
}  

15.创建查询新闻的方法

package model;  
  
import java.util.List;  
import java.util.Map;  
  
public class Mynews {  
      
    //查询  
    public List queryNews() throws Exception{  
        String sql="select * from mynews";  
         return Dbuit.query(sql);  
      
    }  
      
}  


16.刷新新闻页面

package main;  
  
import java.util.Timer;  
  
public class Index {  
    public static void main(String[] args) {  
        Timer ti= new Timer();  
        //new执行任务,执行时间,执行第一次之后多少时间之后执行下一次  
        ti.schedule(new MyTimerTask(), 1000,5000);  
    }  
}  

17.生成前端模板

<#list List as new>  
<#-- 首页显示新闻的连接与标题-->  
${new.title}

18.生成前端首页

package main;  
  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.OutputStreamWriter;  
import java.io.Writer;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
import java.util.TimerTask;  
  
import freemarker.template.Configuration;  
import freemarker.template.DefaultObjectWrapper;  
import freemarker.template.Template;  
import model.Mynews;  
  
public class MyTimerTask extends TimerTask{  
    //调用查询的方法  
    Mynews my= new Mynews();  
  
    public void run(){  
        try {  
            // 生成html  
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);  
            //模板文件的位置  
            cfg.setDirectoryForTemplateLoading(new File("src/main/resources"));  
            cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));  
            //获取所有的新闻  
            List result=my.queryNews();  
            Map root = new HashMap();  
            root.put("List", result);  
              //加载模板文件  -- 实例化模板对象  
            Template temp = cfg.getTemplate("index.ftl");  
            //生成首页页面的位置  
            String saveFile =  "src/main/webapp/index.html";  
            //写入内容  
            Writer out = new OutputStreamWriter(new FileOutputStream(saveFile));  
            temp.process(root, out);  
            out.flush();  
            out.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  

19 读取新闻的内容

package main;  
  
import java.io.File;  
import java.io.IOException;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.apache.commons.io.FileUtils;  
  
/** 
 * Servlet implementation class NewServler 
 */  
public class NewServler extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
  
    /** 
     * Default constructor.  
     */  
    public NewServler() {  
        // TODO Auto-generated constructor stub  
    }  
    //新闻存储的位置  
    public static final String HTML_DIR = "E:\\html\\";  
    /** 
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        //获取模板传过来的连接路径  
        String path=request.getParameter("path");  
        //完整的文件存储路径  
        String abs=HTML_DIR+path;  
        //读取存储的新闻内容  
        byte[] bt=FileUtils.readFileToByteArray(new File(abs));  
        //输出到首页连接  
        response.getOutputStream().write(bt);  
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
        doGet(request, response);  
    }  
  
}  

20.启动后台发布新闻项目,在运行前台新闻首页

你可能感兴趣的:(freemarker)