先创建一个Web项目News
在WEB-INF里面创建子目录lib,添加mysql连接的jar包
在web目录里面创建META-INF子目录,然后创建context.xml
<?xml version="1.0" encoding="utf-8" ?>
<Context>
<Resource
name="jdbc/news" auth="Container"
type="javax.sql.DataSource"
maxAlive="100" maxIdle="30" maxWait="10000"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/news"
username="root" password="root"/>
</Context>
在src里创建net.ys.news.bean包,在里面创建新闻实体类News
package net.ys.news.bean;
import java.sql.Timestamp;
public class News {
private int nid;
private int ntid;
private String ntname;
private String ntitle;
private String nauthor;
private Timestamp ncreatedate;
private String npicpath;
private String ncontent;
private Timestamp nmodifydate;
private String nsummary;
public int getNid() {
return nid;
}
public void setNid(int nid) {
this.nid = nid;
}
public int getNtid() {
return ntid;
}
public void setNtid(int ntid) {
this.ntid = ntid;
}
public String getNtname() {
return ntname;
}
public void setNtname(String ntname) {
this.ntname = ntname;
}
public String getNtitle() {
return ntitle;
}
public void setNtitle(String ntitle) {
this.ntitle = ntitle;
}
public String getNauthor() {
return nauthor;
}
public void setNauthor(String nauthor) {
this.nauthor = nauthor;
}
public Timestamp getNcreatedate() {
return ncreatedate;
}
public void setNcreatedate(Timestamp ncreatedate) {
this.ncreatedate = ncreatedate;
}
public String getNpicpath() {
return npicpath;
}
public void setNpicpath(String npicpath) {
this.npicpath = npicpath;
}
public String getNcontent() {
return ncontent;
}
public void setNcontent(String ncontent) {
this.ncontent = ncontent;
}
public Timestamp getNmodifydate() {
return nmodifydate;
}
public void setNmodifydate(Timestamp nmodifydate) {
this.nmodifydate = nmodifydate;
}
public String getNsummary() {
return nsummary;
}
public void setNsummary(String nsummary) {
this.nsummary = nsummary;
}
@Override
public String toString() {
return "News{" +
"nid=" + nid +
", ntid=" + ntid +
", ntname='" + ntname + '\'' +
", ntitle='" + ntitle + '\'' +
", nauthor='" + nauthor + '\'' +
", ncreatedate=" + ncreatedate +
", npicpath='" + npicpath + '\'' +
", ncontent='" + ncontent + '\'' +
", nmodifydate=" + nmodifydate +
", nsummary='" + nsummary + '\'' +
'}';
}
}
创建net.ys.news.dbutil包,在里面创建数据库连接管理类ConnectionManager
package net.ys.news.dbutil;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionManager {
/**
* 私有化构造方法,拒绝实例化
*/
private ConnectionManager() {
}
/**
* 获取数据库连接静态方法
*
* @return 数据库连接
*/
public static Connection getConnection() {
Connection conn = null;
try {
// 创建初始化上下文
Context ctx = new InitialContext();
// 通过数据库连接池查询获取数据源
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/news");
// 通过数据源获取数据库连接
conn = ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭数据库连接静态方法
*
* @param conn 数据库连接
*/
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
创建net.ys.news.dao包,在里面创建新闻数据访问类NewsDao
package net.ys.news.dao;
import net.ys.news.bean.News;
import net.ys.news.dbutil.ConnectionManager;
import javax.xml.transform.Result;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class NewsDao {
/**
* 获取全部新闻列表
*
* @return 全部新闻列表
*/
public List<News> findAllNews() {
// 定义新闻列表
List<News> newsList = new ArrayList<>();
// 获取数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "select * from news";
try {
// 创建语句对象
Statement stmt = conn.createStatement();
// 执行SQL查询,返回结果集
ResultSet rs = stmt.executeQuery(strSQL);
// 遍历结果集
while (rs.next()) {
// 创建新闻实体对象
News news = new News();
// 将当前记录字段值去设置新闻实体属性
news.setNid(rs.getInt("nid"));
news.setNtid(rs.getInt("ntid"));
news.setNtitle(rs.getString("ntitle"));
news.setNauthor(rs.getString("nauthor"));
news.setNcreatedate(rs.getTimestamp("ncreatedate"));
news.setNpicpath(rs.getString("npicpath"));
news.setNcontent(rs.getString("ncontent"));
news.setNmodifydate(rs.getTimestamp("nmodifydate"));
news.setNsummary(rs.getString("nsummary"));
// 将当前新闻实体添加到新闻列表
newsList.add(news);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConn(conn);
}
// 返回新闻列表
return newsList;
}
/**
* 获取总记录数
*
* @return 总记录数
*/
public int getCount() {
// 返回总记录数
return findAllNews().size();
}
/**
* 获取总页数
*
* @param count 总记录数
* @param pageSize 每页记录数
* @return 总页数
*/
public int getTotalPages(int count, int pageSize) {
// 返回总页数
return count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
}
/**
* 按页获取新闻列表
*
* @param pageIndex 当前页码
* @param pageSize 每页记录数
* @return 当前页新闻列表
*/
public List<News> findNewsByPage(int pageIndex, int pageSize) {
// 定义新闻列表
List<News> newsList = new ArrayList<>();
// 获取数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "select * from news limit ?, ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, pageSize * (pageIndex - 1));
pstmt.setInt(2, pageSize);
// 执行SQL查询,返回结果集
ResultSet rs = pstmt.executeQuery();
// 遍历结果集
while (rs.next()) {
// 创建新闻实体对象
News news = new News();
// 将当前记录字段值去设置新闻实体属性
news.setNid(rs.getInt("nid"));
news.setNtid(rs.getInt("ntid"));
news.setNtitle(rs.getString("ntitle"));
news.setNauthor(rs.getString("nauthor"));
news.setNcreatedate(rs.getTimestamp("ncreatedate"));
news.setNpicpath(rs.getString("npicpath"));
news.setNcontent(rs.getString("ncontent"));
news.setNmodifydate(rs.getTimestamp("nmodifydate"));
news.setNsummary(rs.getString("nsummary"));
// 将当前新闻实体添加到新闻列表
newsList.add(news);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConn(conn);
}
// 返回新闻列表
return newsList;
}
}
修改首页index.jsp的内容
在web目录里创建不分页显示全部新闻页面allnews.jsp
<%@ page import="net.ys.news.dao.NewsDao" %>
<%@ page import="net.ys.news.bean.News" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>不分页显示全部新闻列表</title>
</head>
<body>
<%
// 创建新闻数据访问对象
NewsDao newsDao = new NewsDao();
// 获取全部新闻列表
List<News> newsList = newsDao.findAllNews();
// 在页面上显示数据
out.print("<table border='1' cellpadding='10'>");
out.print("<tr><th>编号</th><th>标题</th><th>创建时间</th></tr>");
// 遍历新闻列表
for (News news: newsList) {
out.print("<tr><td>" + news.getNid() + "</td>");
out.print("<td>" + news.getNtitle() + "</td>");
out.print("<td>" + news.getNcreatedate() + "</td></tr>");
}
out.print("</table>");
%>
</body>
</html>
在web目录里创建分页显示全部新闻列表页面pagingnews.jsp
<%@ page import="net.ys.news.dao.NewsDao" %>
<%@ page import="net.ys.news.bean.News" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>分页显示全部新闻列表</title>
</head>
<body>
<%
// 创建新闻数据访问对象
NewsDao newsDao = new NewsDao();
// 获取总记录数
int count = newsDao.getCount();
// 定义每页记录数
int pageSize = 5;
// 获取总页数
int totalPages = newsDao.getTotalPages(count, pageSize);
// 获取当前页码
String currentPage = request.getParameter("pageIndex");
// 首次进入页面,应该显示第一页内容
if (currentPage == null) {
currentPage = "1";
}
// 获取页索引
int pageIndex = Integer.parseInt(currentPage);
// 对首页与末页的页索引进行控制
if (pageIndex < 1) {
pageIndex = 1;
} else if (pageIndex > totalPages) {
pageIndex = totalPages;
}
// 获取当前页新闻列表
List<News> newsList = newsDao.findNewsByPage(pageIndex, pageSize);
// 在页面上显示数据
out.print("<table border='1' cellpadding='10' style='margin: 0px auto'>");
out.print("<tr><th>编号</th><th>标题</th><th>创建时间</th></tr>");
// 遍历新闻列表
for (News news: newsList) {
out.print("<tr><td>" + news.getNid() + "</td>");
out.print("<td>" + news.getNtitle() + "</td>");
out.print("<td>" + news.getNcreatedate() + "</td></tr>");
}
out.print("</table>");
%>
<%-- 实现分页操作【首页、上一页、下一页、末页】--%>
<p style="text-align: center">
<a href="pagingnews.jsp?pageIndex=1">[首页]</a>
<a href="pagingnews.jsp?pageIndex=<%= pageIndex - 1 %>">[上一页]</a>
<a href="pagingnews.jsp?pageIndex=<%= pageIndex + 1 %>">[下一页]</a>
<a href="pagingnews.jsp?pageIndex=<%= totalPages %>">[末页]</a>
<%= pageIndex %> / <%= totalPages %>
</p>
</body>
</html>