CMS新闻DEMO

来源:互联网 发布:淘宝上怎么搜才能买烟 编辑:程序博客网 时间:2024/06/06 05:16

1.在数据库中创建新闻数据库表news,包含标题,作者,日期,正文等字段

CREATE DATABASE newsUSE newsCREATE TABLE news (title VARCHAR(20),author VARCHAR(10),publishtime CHAR(10),content VARCHAR(225))INSERT INTO news VALUE ('马克隆','腾讯网','2017-05-02','韩国首尔闹市现状')

创建HTML模板文件

<html>    <head>        <title></title>    </head>    <body >        <table border="1">            <tr>                <td>标题</td>                <td>#{title}</td>            </tr>            <tr>                <td>作者</td>                <td>#{author}</td>            </tr>            <tr>                <td>时间</td>                <td>#{date}</td>            </tr>            <tr>                <td>内容</td>                <td>#{content}</td>            </tr>        </table>    </body></html>

读取数据库中所有新闻信息,并使用新闻信息替换模板文件中占位符,从而为每一条新闻生成一个HTML静态页面
1.创建NewsDao接口,实现增删查该的方法

public List<News> getNews();public int insert(News news);public int delete(int id);public int update(News news);

2.创建接口的实现类,重写方法实现增删查改

@Override    public List<News> getNews() {           List<News> list = new ArrayList<News>();        Connection conn  = DBUtil.getConnection();        PreparedStatement prepStmt = null;        ResultSet rs = null;        try {            String sql = "select * from news";            prepStmt = conn.prepareStatement(sql);            rs = prepStmt.executeQuery();            while(rs.next()){                News news = new News();                news.setTitle(rs.getString("title"));                news.setAuthor(rs.getString("author"));        news.setPublishDate(rs.getString("publishDate"));                news.setContent(rs.getString("content"));                list.add(news);            }        } catch (SQLException e) {            e.printStackTrace();        }finally{            DBUtil.closeAll(conn, prepStmt, rs);        }        return list;    }    @Override    public int insert(News news) {        String sql = "insert into news(title, author, publisDate, content) values(?,?,?,?)";        return DBUtil.execute(sql, new Object[]{news.getTitle(), news.getAuthor(), news.getPublishDate(), news.getContent()});    }    @Override    public int delete(int id) {        String sql = "delete from news where id = ?";        return DBUtil.execute(sql, new Object[]{id});    }    @Override    public int update(News news) {        // TODO Auto-generated method stub        return 0;    }

3.创建实体类

    private String title;    private String author;    private String publishDate;    private String content;    //省略getter、setting方法

4.工具类
a.数据库操作工具类

static Properties prop = PropUtil.getProperties("db.properties");private static final String url = prop.getProperty("url");private static final String user = prop.getProperty("user");private static final String password = prop.getProperty("password");/*private static final String url = "jdbc:mysql://localhost:3306/news";    private static final String user = "root";    private static final String password = "hbtt";*///获取JDBC连接对象方法public static Connection getConnection(){        Connection conn = null;        try {            Class.forName("com.mysql.jdbc.Driver");            conn = DriverManager.getConnection(url, user, password);        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (SQLException e) {            e.printStackTrace();        }           return conn;    }//关闭数据库连接对象public static void closeAll(Connection conn, Statement stmt, ResultSet rs){        try {            if(rs != null){                rs.close();            }            if(stmt != null){                stmt.close();            }            if(conn != null){                conn.close();            }        } catch (Exception e) {            e.printStackTrace();        }    }//执行查询 SQLpublic static int execute(String sql, Object[] params){        Connection conn = getConnection();        int result = 0;        try {            PreparedStatement prepStmt = conn.prepareStatement(sql);            //设置查询参数            if(params != null && params.length > 0){                for(int i = 0; i < params.length; i++){                    prepStmt.setObject(i+1, params[i]);                }            }            result = prepStmt.executeUpdate();        } catch (SQLException e) {            e.printStackTrace();        }        return result;    }

b.文件读写工具类

//读文件public static String readFile(String fileName){        FileReader fr = null;        BufferedReader br = null;        StringBuffer sb = new StringBuffer();        try {            fr = new FileReader(fileName);            br = new BufferedReader(fr);            String tmp = br.readLine();            while(tmp != null){                sb.append(tmp).append("\r\n");                tmp = br.readLine();            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                if(br != null){                    br.close();                }                if(fr != null){                    fr.close();                }            } catch (Exception e) {                e.printStackTrace();            }        }           return sb.toString();    }//写文件public static void writeFile(String content, String fileName){        FileWriter fw = null;        BufferedWriter bw = null;        try {            fw = new FileWriter(fileName);            bw = new BufferedWriter(fw);            bw.write(content);        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                if(bw != null){                    bw.close();                }                if(fw != null){                    fw.close();                }            } catch (Exception e) {                e.printStackTrace();            }        }    }

c.properties 属性文件工具类,

//properties 属性文件工具类,专门用来读取properties文件public static Properties getProperties(String fileName){        Properties prop = new Properties();        try {   prop.load(PropUtil.class.getClassLoader().getResourceAsStream(fileName));        } catch (IOException e) {            e.printStackTrace();        }        return prop;    }//properties 的文件配置driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/newsuser=rootpassword=hbtt

5.内容管理系统的业务处理
替换模板并生成新的文件,步骤如下:

  1. 读取模板内容
  2. 从数据库中读取替换内容
  3. 找到替换字段,然后进行替换
  4. 把替换后的新内容写入新文件中,即生成新文件。
public void contentToHTML(){        String path = "d:/html/";        String templateContent = FileUtil.readFile(path + "template.html");        List<News> list = dao.getNews();        //把数据库的新闻内容通过循环写入到html文件中        for(News n : list){            String content = templateContent.replace("#{title}", n.getTitle()).            replace("#{author}", n.getAuthor()).            replace("#{date}", n.getPublishDate()).            replace("#{content}", n.getContent());            FileUtil.writeFile(content, path + n.getTitle() + ".html");        }

6.测试类

CMSManager manager = new CMSManager();manager.contentToHTML();

内容替换成功!

这里写图片描述

效果图

0 0
原创粉丝点击