java电影列表后台分页,如有问题请与我联系
新建一个class命名为MovieDao
public class MovieDao(){
private Connection conn=null;
private PreparedStatement pstm=null;
private ResultSet rs=null;
/*查询所有电影信息,结果以分页显示*/
public ArrayList<Movie> selectAllMovie(int pageNo) {
private Movie movie=null;
//数据库连接
conn=ConnectionDB.getConnection();
ArrayList<Movie> list=new ArrayList<Movie>();
String sql="select * from movie";
try{
pstm=conn.prepareStatement(sql);
rs=pstm.executeQuery();
// 要显示第一条记录
int begin = (pageNo - 1) * 5 + 1;
// 要显示最后一条记录
int end = pageNo * 5;
// 循环计数器
int index = 0;
while (rs.next()) {
index++;
if (index < begin) {
continue;
}
if (index > end) {
break;
}
movie=new Movie();
movie.setId(rs.getInt(1));
movie.setName(rs.getString(2));
movie.setDirector(rs.getString(3));
movie.setType(rs.getString(5));
list.add(movie);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/*查询所有电影条数,用于确定总页数*/
public int selectMoviePaging() {
int pageCount = 1;
conn = ConnectionDB.getConnection();
String sql = "select count(*) from movie";
try {
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
// 指向结果集的第一条
if(rs.next()){
// 得到第一列
int n = rs.getInt(1);
// 计算总页数,每页显示20条记录
pageCount = (n - 1) / 20 + 1;
}
} catch (SQLException e) {
e.printStackTrace();
}
return pageCount;
}
}
新建一个MovieServlet,在doPost中加入:
ArrayList<Movie> list=new ArrayList<Movie>();
MovieDao movieDao=new MovieDao();
int pageNo = 1;
String strPageNo = request.getParameter("pageNo");
if (strPageNo != null && !strPageNo.equals("")) {
pageNo = Integer.parseInt(strPageNo);
}
int pageCount = movieDao.selectMoviePaging();
list=movieDao.selectAllMovie(pageNo);
request.setAttribute("pageNo", pageNo);
request.setAttribute("pageCount", pageCount);
request.setAttribute("list", list);
request.getRequestDispatcher("movielist.jsp").forward(request, response);
movielist.jsp页面,下面只给出了分页代码
<!-- 分页 -->
<form action="MovieServlet" method="post">
<table width="960px" >
<tr>
<td><div align="right">
<c:if test="${pageNo==1}">
<img src="img/paging/19.gif" />
<img src="img/paging/17.gif" />
</c:if>
<!-- 如果不是第一页的话,就显示超链接 -->
<c:if test="${pageNo!=1}">
<a href="ManageEventServlet?pageNo=1&action=current"><img src="img/paging/20.gif" /> </a>
<a href="ManageEventServlet?pageNo=${pageNo-1}&action=current"><img src="img/paging/18.gif" /> </a>
</c:if>
<!-- 如果是最后一页的话,就不显示超链接 -->
<c:if test="${pageNo==pageCount}">
<img src="img/paging/13.gif" />
<img src="img/paging/15.gif" />
</c:if>
<!-- 如果不是最后一页的话,就显示超链接 -->
<c:if test="${pageNo!=pageCount}">
<a href="ManageEventServlet?pageNo=${pageNo+1}&action=current"><img src="img/paging/14.gif" /> </a>
<a href="ManageEventServlet?pageNo=${pageCount}&action=current"><img src="img/paging/16.gif" /> </a>
</c:if>当前[${pageNo }/${pageCount }]
第<input type="text" name="pageNo" style="width:20px"/>页
<input type="submit" value="go"/>
</div></td>
</tr>
</table>
</form>