将之前给自己留的小任务完成之后,就觉得自己分页这方面的领会还不太深,之前跟着学姐学分页,但是完全就是把学姐的所有代码直接copy直接用,基本没有对代码的理解;这次就在自己写的用户管理列表中用了自己写的分页技术,虽然还是参照着原来学姐的代码,不过换了一种方式,没有像学姐一样将分页对象存在session对象中,下面贴上代码
首先是分页接口,由Dao层继承
package com.test.util;
import com.test.entity.Users;
import java.util.List;
/**
* @Description 用于分页的接口,由Dao层继承,重写此两个方法
* Created by sjz on 2016/9/19.
*/
public interface PageInterface {
/**
* 查询所有记录,使用分页对象中的一些变量获取
* @param sPage
* @return list
*/
public List<Users> findAll(SplitPage sPage);
/**
* 查询记录条数
* @return int
*/
public int getTotalRows();
}
Dao层重写了接口中的两个方法
@Override
public List<Users> findAll(SplitPage sPage) {
List<Users> list = new ArrayList<Users>();
ResultSet rs = null;
try{
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql = "SELECT * FROM t_users LIMIT ?,?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, sPage.getPageRow() * (sPage.getCurrentPage() - 1));
ps.setInt(2, sPage.getPageRow());
rs = ps.executeQuery();
while(rs.next()){
Users user = new Users();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setContent(rs.getString("content"));
user.setPhoto(rs.getString("photo"));
list.add(user);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
@Override
public int getTotalRows() {
int totalRows = 0;
try {
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql = "SELECT COUNT(*) FROM t_users";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
totalRows = rs.getInt(1);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return totalRows;
}
然后是分页实体类,用来处理页面之间的跳转
package com.test.util;
/**
* 分页对象
* Created by sjz on 2016/9/19.
*/
public class SplitPage {
public final static String FIRSTPAGE = "first";//首页
public final static String LASTPAGE = "last";//尾页
public final static String PREVIOUSPAGE = "previous";//上一页
public final static String NEXTPAGE = "next";//下一页
private int pageRow = 5;//每页显示5条数据
private int totalRows = 0;//数据条数,由Dao提供
private int currentPage = 1;//当前页
private int firstPage = 1;//首页
private int totalPage = 1;//总页数
public int getPageRow() {
return pageRow;
}
public void setPageRow(int pageRow) {
this.pageRow = pageRow;
this.totalPage = this.totalRows / this.pageRow
+ ((this.totalRows % this.pageRow == 0) ? 0 : 1);
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
this.totalPage = this.totalRows/this.pageRow+((this.totalRows%this.pageRow==0)?0:1);
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getFirstPage() {
return firstPage;
}
public void setFirstPage(int firstPage) {
this.firstPage = firstPage;
}
public int getTotalPage() {
return totalPage;
}
public int toNewPage(String flag) { //得到下次操作的页面数
int newPage = this.currentPage;//定义新页数为当前页
if (flag != null && !"".equals(flag)) { //请求参数不为空
if (SplitPage.FIRSTPAGE.equals(flag)) { //如果传入的参数为第一页
newPage = 1; //新页数为第一页
} else if (SplitPage.LASTPAGE.equals(flag)) { //如果传入的参数为最后一页
newPage = this.totalPage; //新页数为最后一页
} else if (SplitPage.NEXTPAGE.equals(flag)) { //如果传入的参数为下一页
newPage = this.currentPage
+ ((this.currentPage == this.totalPage) ? 0 : 1);// 如果当前页面与总的页面数相等则不再向后(+1)
System.out.println(newPage);
} else if (SplitPage.PREVIOUSPAGE.equals(flag)) { //如果传入的参数为上一页
newPage = this.currentPage
- ((this.currentPage == this.firstPage) ? 0 : 1);// 如果当前页面与首页相等则不再向前(-1)
} else {
// 传入的是个数字字符串参数
//System.out.println(flag+"llll");
newPage = Integer.parseInt(flag.trim());
}
} else {// 请求的参数为空,则当前页码不变
newPage = this.currentPage;
}
this.setCurrentPage(newPage);// 记得重新设置当期页面
return newPage;
}
}
然后是servlet,只是在原来的基础上多了一些传递的参数,和改动了list方法
package com.test.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.test.dao.UsersDao;
import com.test.entity.Users;
import com.test.util.SplitPage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import static java.lang.System.out;
/**
* Created by sjz on 2016/9/14.
*/
public class UsersServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request,response);
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String method = request.getParameter("method");
out.println(method);
switch (method){
case "insert" :
insert(request,response);
break;
case "delete" :
delete(request,response);
break;
case "toUpdate":
int id3 = Integer.parseInt(request.getParameter("id"));
Users user3 = UsersDao.selectById(id3);
request.setAttribute("user",user3);
request.getRequestDispatcher("../show.jsp").forward(request,response);
case "update" :
System.out.println(request.getPart("id")+"aaaa");
int id = Integer.parseInt(request.getParameter("id"));
update(request,response,id);
break;
case "select" :
//select(request,response);
int id2 = Integer.parseInt(request.getParameter("id"));
Users user2 = UsersDao.selectById(id2);
request.setAttribute("user",user2);
request.getRequestDispatcher("../show.jsp").forward(request,response);
break;
case "list" :
//list(request,response);\
UsersDao uDao = new UsersDao();
SplitPage sPage = new SplitPage();
int totalRows = uDao.getTotalRows();
sPage.setTotalRows(totalRows);
String flag = request.getParameter("flag");
String current = request.getParameter("current");
if(current!=null){
int currentPage = Integer.parseInt(current);
sPage.setCurrentPage(currentPage);
}
int newPage = sPage.toNewPage(flag);
List<Users> list = uDao.findAll(sPage);
request.setAttribute("list",list);
request.setAttribute("sPage",sPage);
request.getRequestDispatcher("../list.jsp").forward(request,response);
break;
}
}
private void insert(HttpServletRequest request, HttpServletResponse response) {
SmartUpload su = new SmartUpload();
JspFactory _jspxFactory = null;
PageContext pageContext = null;
_jspxFactory = JspFactory.getDefaultFactory();
pageContext = _jspxFactory.getPageContext(this,request,response,"",true,8192,true);
try {
su.initialize(pageContext);
su.upload();
PrintWriter out = response.getWriter();
out.println("上传" + su.save("picture") + "个文件成功!!!"+"<br>");
String username = su.getRequest().getParameter("username");
String password = su.getRequest().getParameter("password");
String content = su.getRequest().getParameter("content");
File file = su.getFiles().getFile(0);
if (file.isMissing())
System.out.println("未选择文件");
String photo = file.getFileName();
String path = "/picture";
path = path + "/" + photo;
file.saveAs(path, SmartUpload.SAVE_VIRTUAL);
System.out.println(photo);
Users user = new Users();
user.setUsername(username);
user.setPassword(password);
user.setContent(content);
user.setPhoto(photo);
if(UsersDao.insert(user)){
out.println("成功");
response.setHeader("refresh", "3;UsersServlet?method=list&flag=first");
} else{
out.println("失败");
response.setHeader("refresh", "3;UsersServlet?method=insert");
}
} catch (ServletException e) {
e.printStackTrace();
} catch (SmartUploadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void delete(HttpServletRequest request, HttpServletResponse response) {
int id = Integer.parseInt(request.getParameter("id"));
try{
if(UsersDao.delete(id)){
out.println("成功");
request.getRequestDispatcher("UsersServlet?method=list&flag=first").forward(request,response);
} else{
out.println("失败");
request.getRequestDispatcher("../list.jsp").forward(request,response);
}
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void update(HttpServletRequest request, HttpServletResponse response, int id) {
SmartUpload su = new SmartUpload();
JspFactory _jspxFactory = null;
PageContext pageContext = null;
_jspxFactory = JspFactory.getDefaultFactory();
pageContext = _jspxFactory.getPageContext(this,request,response,"",true,8192,true);
try {
su.initialize(pageContext);
su.upload();
PrintWriter out = response.getWriter();
out.println("上传" + su.save("picture") + "个文件成功!!!"+"<br>");
String username = su.getRequest().getParameter("username");
String password = su.getRequest().getParameter("password");
String content = su.getRequest().getParameter("content");
File file = su.getFiles().getFile(0);
if (file.isMissing())
System.out.println("未选择文件");
String photo = file.getFileName();
String path = "/picture";
path = path + "/" + photo;
file.saveAs(path, SmartUpload.SAVE_VIRTUAL);
System.out.println(photo);
Users user = new Users();
user.setUsername(username);
user.setPassword(password);
user.setContent(content);
user.setPhoto(photo);
if(UsersDao.update(user,id)){
out.println("成功");
response.setHeader("refresh", "3;UsersServlet?method=list&flag=first");
} else{
out.println("失败");
response.setHeader("refresh", "3;UsersServlet?method=insert&flag=first");
}
} catch (ServletException e) {
e.printStackTrace();
} catch (SmartUploadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void select(HttpServletRequest request, HttpServletResponse response) {
}
private void list(HttpServletRequest request, HttpServletResponse response) {
}
}
最后是list.jsp,增加了一些代码,用来更好的实现功能
<%@ page import="com.test.entity.Users" %>
<%@ page import="java.util.List" %>
<%@ page import="com.test.util.SplitPage" %><%--
Created by IntelliJ IDEA.
User: lenovo
Date: 2016/9/18
Time: 9:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户列表</title>
</head>
<body>
<tr>
<td>用户ID</td>
<td>用户名</td>
<td>用户简介</td>
<td>照片</td>
</tr><br>
<%
SplitPage sPage = (SplitPage)request.getAttribute("sPage");
List<Users> list = (List<Users>) request.getAttribute("list");
for (int i=0;list!=null&&i<list.size();i++){
%>
<tr>
<td><%=list.get(i).getId()%></td>
<td><%=list.get(i).getUsername()%></td>
<td><%=list.get(i).getContent()%></td>
<td><img src="../picture/<%=list.get(i).getPhoto()%>" style="width:100px;height:100px;"></td>
<a href="UsersServlet?method=select&id=<%=list.get(i).getId()%>">修改</a>
<a href="UsersServlet?method=delete&id=<%=list.get(i).getId()%>">删除</a>
</tr>
<br>
<%
}
%>
<div id="foot">
<a href="UsersServlet?method=list&flag=<%=SplitPage.FIRSTPAGE%>¤t=<%=sPage.getCurrentPage()%>">首页</a>
<a href="UsersServlet?method=list&flag=<%=SplitPage.PREVIOUSPAGE%>¤t=<%=sPage.getCurrentPage()%>">上一页</a>
<a href="UsersServlet?method=list&flag=<%=SplitPage.NEXTPAGE%>¤t=<%=sPage.getCurrentPage()%>">下一页</a>
<a href="UsersServlet?method=list&flag=<%=SplitPage.LASTPAGE%>¤t=<%=sPage.getCurrentPage()%>">末页</a>
<%
for (int i = 1; i <= sPage.getTotalPage(); ++i) { //控制总页数
%>
<a href="UsersServlet?method=list&flag=<%=i%>¤t=1"><%=i%></a>
<%
}
%>
</select>
<label><%=sPage.getCurrentPage()%>/<%=sPage.getTotalPage()%>页 <!-- 当前页数/总页数 -->
</label>
</div>
</body>
</html>
除去这些,其余所有的页面跳转的地址后面全部加上一些参数,用来修改每次访问都重新实例化的sPage对象,以便实现页面跳转