內存分頁
分頁工具類
package com.baojiwenli.utils;
import java.util.ArrayList;
import java.util.List;
/**
* 內存分頁
* @param <T>
*/
@SuppressWarnings("all")
public class PageBean2<T> {
private int curPageno; //當前頁號
private int totalPagecount; //總頁數
private int totalRows; //總記錄數
private int rowsPerPage = 2; //每頁記錄數
private List<T> data = new ArrayList<>();
/*
list表示所有的記錄數
curPage:當前頁號
已知條件
總記錄數
每頁的記錄數
*/
public void pages(List<T> list,String curPage){
if(list==null||list.size()==0){
return ;
}
//1總記錄數
this.totalRows = list.size();
try{
//當前頁號
this.curPageno = Integer.parseInt(curPage);
}catch (Exception e){
//如果異常,默認顯示第一頁,如果傳入的curPage 爲空,或者傳入的是一個字符串
this.curPageno = 1;
}
//2計算總頁數, pages = total %perPage? total/perPage:total/perPage+1;
totalPagecount = totalRows%rowsPerPage==0?totalRows/rowsPerPage:totalRows/rowsPerPage+1;
//再次修正對當前頁號 進行判斷當前頁數的取值範圍是否合理,並修正
if(curPageno<=0){
curPageno = 1;
}if(curPageno>totalPagecount){
curPageno = totalPagecount;
}
//給每頁先固定記錄條數
//4數據,獲取每頁的開始記錄數
int fromIndex= (curPageno-1)*rowsPerPage;
int toIndex = fromIndex+rowsPerPage;
//修正
if(toIndex > totalRows){
toIndex = totalRows;
}
//5在list拿到的結果集裏重新截取
this.data = list.subList(fromIndex,toIndex);
}
public int getCurPageno() {
return curPageno;
}
public void setCurPageno(int curPageno) {
this.curPageno = curPageno;
}
public int getTotalPagecount() {
return totalPagecount;
}
public void setTotalPagecount(int totalPagecount) {
this.totalPagecount = totalPagecount;
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public int getRowsPerPage() {
return rowsPerPage;
}
public void setRowsPerPage(int rowsPerPage) {
this.rowsPerPage = rowsPerPage;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
}
控制層
package com.baojiwenli.controller;
import com.baojiwenli.entity.Student;
import com.baojiwenli.service.StudentService;
import com.baojiwenli.utils.*;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@WebServlet(urlPatterns = "/score_student")
public class StudentServlet extends BaseDaoServlet {
private StudentService service = new StudentService();
/**
* 判斷session
* @param request
* @param response
* @throws IOException
*/
public static void session(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// 獲取Session
HttpSession session = request.getSession(false);
if (session == null||session.getAttribute("loginmethod") == null) {
request.setAttribute("msg", "非法訪問!");
String context = request.getContextPath();
System.out.println("列表路徑"+context);
// 非方法的訪問
request.getRequestDispatcher( "login.jsp").forward(request, response);
return;
}
}
/*
列表
*/
public void list(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("=============列表============");
//來判斷session是否爲空的情況
HttpSession session = request.getSession(false);
if (session == null||session.getAttribute("loginmethod") == null) {
request.setAttribute("msg", "非法訪問!");
String context = request.getContextPath();
System.out.println("列表路徑"+context);
// 非方法的訪問
request.getRequestDispatcher( "login.jsp").forward(request, response);
return;
}
String method = (String) session.getAttribute("loginmethod");
if(method.equals("66")) {
//獲取前端模糊查詢的數據
Student student = MyBeanUtils1.requestToBean(Student.class,request);
//內存分頁
//獲取當前頁號,從前端獲取,第一次獲取的時候肯定是null值
List<Student> list = service.queryAll(student);
PageBean2<Student> pageBean2 = new PageBean2<>();
String curPage = request.getParameter("curPage");
System.out.println("當前頁:"+curPage);
pageBean2.pages(list,curPage);
request.setAttribute("pageBean",pageBean2);
// 將查詢數據庫的信息存放到request對象,目的頁面(新聞列表頁面)通過轉發獲取到
// request.setAttribute("list", list);
// 轉發到newslist.jsp
request.getRequestDispatcher("teachers/listStudent.jsp").forward(request, response);
}else if(method.equals("11")) {
Student stu = (Student) session.getAttribute("frontstudent");
Student student = service.query(stu);
request.setAttribute("student", student);
// 轉發到studentscore.jsp
request.getRequestDispatcher("students/studentScore.jsp").forward(request, response);
}
}
前端頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<script src="${pageContext.request.contextPath}/ckeditor/ckeditor.js"></script>
<meta charset="UTF-8">
<title>學生成績單</title>
<style type="text/css">
#header {
width: 500px;
margin: 0 auto;
text-align: center
}
td, th, form {
text-align: center;
}
</style>
<script type="text/javascript">
function go(pageNo) {
// alert(pageNo);
myForm.curPage.value = pageNo;
myForm.submit();
}
</script>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// alert(44444);
$("[name=all]").click(function () {
$("[name=id]").prop("checked", $(this).prop("checked"));
});
$("[value=全部刪除]").click(function () {
alert("全部刪除!");
idform.submit();
});
});
</script>
</head>
<body>
<div id="header">
<a href="teachers/addStudent.jsp">添加學生信息</a>
<c:if test="${empty sessionScope.adminteacher}">
<a href="${pageContext.request.contextPath}/login.jsp">去登錄</a>
</c:if>
<c:if test="${not empty sessionScope.adminteacher}">
教師頁面歡迎您,${adminteacher.name } <a href="teacher?action=logout">註銷</a>
</c:if>
</div>
<hr>
<div>
<input style="float:right; margin-right: 150px" type="button" value="全部刪除">
<form name="myForm" action="score_student?action=list" method="post">
<input type="hidden" name="curPage">
學生姓名關鍵字:<input name="name" value="${param.name}">
學生院系: <input name="dept" value="${param.dept}">
<input type="submit" value="搜索">
</form>
</div>
<hr>
<form name="idform" action="score_student?action=deleteall" method="post">
<table id="tab" align="center" width="80%" border="1"
style="border-collapse: collapse;">
<thead>
<tr bgcolor="#acacac">
<th width="8%"><input type="checkbox" name="all">全部</th>
<th width="15%">學生姓名</th>
<th>學生院系</th>
<th>院系主任</th>
<th>專業課</th>
<th>成績</th>
<th>學生圖像</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- varStatus="st" 取下標 通過下標隔行換色-->
<c:forEach items="${pageBean.data}" var="stu" varStatus="st">
<tr bgcolor="${st.count%2==0?'#EEEE11':''}">
<td><input type="checkbox" name="id" value="${stu.stuid}"></td>
<td>${stu.name }</td>
<td>${stu.dept}</td>
<td>${stu.deptteacher}</td>
<td>${stu.course}</td>
<td>${stu.score}</td>
<td><img width="120" src="upload/${stu.photo}">
<c:if test="${not empty stu.photo}">
<a href="score_student?action=download&filename=${stu.photo}">下載圖片</a>
</c:if>
</td>
<td><a onclick="return confirm('你確定要刪除此記錄嗎?')"
href="score_student?action=delete&stuid=${stu.stuid}&photo=${stu.photo}">刪除</a>|
<a href="score_student?action=queryupdate&stuid=${stu.stuid}">修改</a>
</td>
</tr>
</c:forEach>
<c:if test="${empty pageBean.data}">
<tr>
<th colspan="8">沒有記錄</th>
</tr>
</c:if>
</tbody>
<tfoot>
<tr>
<th colspan="8">
當前頁${pageBean.curPageno}/${pageBean.totalPagecount}
<a href="#" onclick="go(1)">首頁</a>
<a href="#" onclick="go(${pageBean.curPageno-1})">上一頁</a>
<a href="#" onclick="go(${pageBean.curPageno+1})">下一頁</a>
<a href="#" onclick="go(${pageBean.totalPagecount})">尾頁</a>
總記錄數:${pageBean.totalRows}
<select name="curPage" onchange="go(this.value)">
<c:forEach begin="1" end="${pageBean.totalPagecount}" var="cc">
<c:if test="${cc==pageBean.curPageno}">
<option selected="selected">${cc }</option>
</c:if>
<c:if test="${cc!=pageBean.curPageno}">
<option>${cc }</option>
</c:if>
</c:forEach>
</select>
</th>
</tr>
</tfoot>
</table>
</form>
</body>
</html>
頁面效果
數據庫分頁
分頁工具類
package com.baojiwenli.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 分頁組件:數據庫端分頁 當前頁 總頁數 總記錄數 每頁顯示的記錄數
*
* 當前頁顯示記錄
*/
public class PageBean<T> {
private int curPageno; // 當前頁號
private int totalPagecount; // 總頁數
private long totalRows; // 總記錄數
private int rowsPerPage = 3; // 每頁的記錄數
private int startRow = 0;
private long endRow = 0;
private List<T> data = new ArrayList<T>();
public PageBean() {}
public void setCurPageno(int curPageno) {
this.curPageno = curPageno;
}
public int getTotalPagecount() {
return totalPagecount;
}
public void setTotalPagecount(int totalPagecount) {
this.totalPagecount = totalPagecount;
}
public void setEndRow(long endRow) {
this.endRow = endRow;
}
//封裝當前頁號和總記錄數
public PageBean(String curPage,long totalRows){
this.setTotalRows(totalRows);
this.setCurPageno(curPage);
}
public int getCurPageno() {
return curPageno;
}
public int getStartRow() {
return startRow;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
public long getEndRow() {
return endRow;
}
public void setEndRow(int endRow) {
this.endRow = endRow;
}
//設置當前頁號:對當前頁進行正確判斷
public void setCurPageno(String curPageno) {
if(Objects.equals(curPageno,null)){
this.curPageno = 1;
}else{
this.curPageno = Integer.parseInt(curPageno);
}
try {
if (this.curPageno <= 0) {
this.curPageno = 1;
}
} catch (Exception e) {
this.curPageno = 1;
}
// 修正 當前頁號
if (this.curPageno <= 0) {
this.curPageno = 1;
}
// 當前頁超出總頁數範圍時
if (this.curPageno > totalPagecount) {
this.curPageno = totalPagecount;
}
//計算開始位置的記錄數號
//數據 截取 rowsPerPage
System.out.println("curpage:"+this.curPageno);
this.startRow = (this.curPageno-1)*rowsPerPage;
//計算結束位置的記錄數號
this.endRow = startRow + rowsPerPage;
System.out.println("start:"+this.startRow);
System.out.println("end:"+this.endRow);
//修正
if(endRow > totalRows) {
endRow = totalRows;
}
}
public int getTotalPageCount() {
return totalPagecount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPagecount = totalPageCount;
}
public long getTotalRows() {
return totalRows;
}
/**
* 設置總記錄數 同時計算總頁數
*/
public void setTotalRows(long totalRows) {
this.totalRows = totalRows;
// 計算總頁數 pages = total/perPage; 100 5----100/5=20 101 5 ----21
if (totalRows % rowsPerPage == 0) {
totalPagecount = (int) (totalRows / rowsPerPage);
} else {
totalPagecount = (int) (totalRows / rowsPerPage + 1);
}
}
public int getRowsPerPage() {
return rowsPerPage;
}
public void setRowsPerPage(int rowsPerPage) {
this.rowsPerPage = rowsPerPage;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
}
dao 層
package com.baojiwenli.dao;
import com.baojiwenli.entity.Student;
import com.baojiwenli.utils.ConnectionUtil;
import com.baojiwenli.utils.PageBean;
import com.baojiwenli.utils.PageBeanSQL;
import com.wdzl.dao.BaseDao;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 學生持久層
*/
public class StudentDao extends BaseDao {
/**
* 帶搜索的sql分頁:需要 傳入對象 當前頁
*/
public PageBean<Student> queryAll(Student student, String curPage) {
String sql = "select stuid,name,dept,deptteacher,course,score,photo"
+ " from student_score where 1=1";
String cql = "select count(*) "
+ " from student_score where 1=1";
String name = null;
String dept = null;
//記錄條件查詢總記錄數
//記錄條件查詢
List<Object> list = new ArrayList<>();
if (student != null) {
name = student.getName();
dept = student.getDept();
System.out.println("name:" + name);
System.out.println("dept:" + dept);
if (name != null && !name.equals("")) {
sql += " and name like ?";
cql += " and name like ?";
list.add("%" + name + "%");
}
if (dept != null && !dept.equals("")) {
sql += " and dept like ?";
cql += " and dept like ?";
list.add("%" + dept + "%");
}
}
//sql語句分頁排序拼接
sql += " order by score desc";
sql += " limit ?,?";//數據庫分頁
//分頁組件
//1.總記錄數
int count = getCount(cql, list.toArray());
//2.通過構造方法給工具類進行封裝數據:當前頁 總頁數 每頁條數 總記錄數
PageBean<Student> pageBean = new PageBean<Student>(curPage, count);
//開始位置 --startRow =--(curPage-1)*rowsPerPage
//每頁開始位置
list.add(pageBean.getStartRow());
//每頁顯示記錄數
list.add(pageBean.getRowsPerPage());
List<Student> list1 = super.query(sql, Student.class, list.toArray());
pageBean.setData(list1);
//這步的時候已經獲取的數據---總記錄數 當前頁 總頁數 條數每頁 顯示當前頁數據記錄
return pageBean;
}
/**
* String sql = select title,content from news where 1=1 and title='sss';
* String cql = "select count(*)"+sql.subString(sql.lastIndexOf(" from "));
* <p>
* select count(*) from news where 1=1 and title='sss'
*/
public int getCount(String sql,Object[] param) {
String xxx = "select count(*) from student_score ";
Connection conn = ConnectionUtil.getConnection();
int count = 0;
try {
pst = conn.prepareStatement(xxx);
rst = pst.executeQuery();
//給佔位符賦值
for (int i = 0; i < param.length; i++) {
pst.setObject(i + 1, param[i]);
}
if (rst.next()) {
count = rst.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
public static void main(String[] args) {
StudentDao dao = new StudentDao();
List<Object> list = new ArrayList<>();
int count = dao.getCount(null,list.toArray());
System.out.println("===="+count);
}
}
控制層
package com.baojiwenli.controller;
import com.baojiwenli.entity.Student;
import com.baojiwenli.service.StudentService;
import com.baojiwenli.utils.*;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@WebServlet(urlPatterns = "/score_student")
public class StudentServlet extends BaseDaoServlet {
private StudentService service = new StudentService();
/**
* 判斷session
* @param request
* @param response
* @throws IOException
*/
public static void session(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// 獲取Session
HttpSession session = request.getSession(false);
if (session == null||session.getAttribute("loginmethod") == null) {
request.setAttribute("msg", "非法訪問!");
String context = request.getContextPath();
System.out.println("列表路徑"+context);
// 非方法的訪問
request.getRequestDispatcher( "login.jsp").forward(request, response);
return;
}
}
/*
列表
*/
public void list(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("=============列表============");
//來判斷session是否爲空的情況
HttpSession session = request.getSession(false);
if (session == null||session.getAttribute("loginmethod") == null) {
request.setAttribute("msg", "非法訪問!");
String context = request.getContextPath();
System.out.println("列表路徑"+context);
// 非方法的訪問
request.getRequestDispatcher( "login.jsp").forward(request, response);
return;
}
String method = (String) session.getAttribute("loginmethod");
if(method.equals("66")) {
//獲取前端模糊查詢的數據
Student student = MyBeanUtils1.requestToBean(Student.class,request);
//數據庫分頁
//獲取下頁頁號
String curPage = request.getParameter("curPage");
System.out.println("當前頁:"+curPage);
PageBean<Student> pageBean = service.queryAll(student,curPage); //帶條件
request.setAttribute("pageBean",pageBean);
// 將查詢數據庫的信息存放到request對象,目的頁面(新聞列表頁面)通過轉發獲取到
// request.setAttribute("list", list);
// 轉發到newslist.jsp
request.getRequestDispatcher("teachers/listStudent.jsp").forward(request, response);
}else if(method.equals("11")) {
Student stu = (Student) session.getAttribute("frontstudent");
Student student = service.query(stu);
request.setAttribute("student", student);
// 轉發到studentscore.jsp
request.getRequestDispatcher("students/studentScore.jsp").forward(request, response);
}
}
前端頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<script src="${pageContext.request.contextPath}/ckeditor/ckeditor.js"></script>
<meta charset="UTF-8">
<title>學生成績單</title>
<style type="text/css">
#header {
width: 500px;
margin: 0 auto;
text-align: center
}
td, th, form {
text-align: center;
}
</style>
<script type="text/javascript">
function go(pageNo) {
// alert(pageNo);
myForm.curPage.value = pageNo;
myForm.submit();
}
</script>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// alert(44444);
$("[name=all]").click(function () {
$("[name=id]").prop("checked", $(this).prop("checked"));
});
$("[value=全部刪除]").click(function () {
alert("全部刪除!");
idform.submit();
});
});
</script>
</head>
<body>
<div id="header">
<a href="teachers/addStudent.jsp">添加學生信息</a>
<c:if test="${empty sessionScope.adminteacher}">
<a href="${pageContext.request.contextPath}/login.jsp">去登錄</a>
</c:if>
<c:if test="${not empty sessionScope.adminteacher}">
教師頁面歡迎您,${adminteacher.name } <a href="teacher?action=logout">註銷</a>
</c:if>
</div>
<hr>
<div>
<input style="float:right; margin-right: 150px" type="button" value="全部刪除">
<form name="myForm" action="score_student?action=list" method="post">
<input type="hidden" name="curPage">
學生姓名關鍵字:<input name="name" value="${param.name}">
學生院系: <input name="dept" value="${param.dept}">
<input type="submit" value="搜索">
</form>
</div>
<hr>
<form name="idform" action="score_student?action=deleteall" method="post">
<table id="tab" align="center" width="80%" border="1"
style="border-collapse: collapse;">
<thead>
<tr bgcolor="#acacac">
<th width="8%"><input type="checkbox" name="all">全部</th>
<th width="15%">學生姓名</th>
<th>學生院系</th>
<th>院系主任</th>
<th>專業課</th>
<th>成績</th>
<th>學生圖像</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- varStatus="st" 取下標 通過下標隔行換色-->
<c:forEach items="${pageBean.data}" var="stu" varStatus="st">
<tr bgcolor="${st.count%2==0?'#EEEE11':''}">
<td><input type="checkbox" name="id" value="${stu.stuid}"></td>
<td>${stu.name }</td>
<td>${stu.dept}</td>
<td>${stu.deptteacher}</td>
<td>${stu.course}</td>
<td>${stu.score}</td>
<td><img width="120" src="upload/${stu.photo}">
<c:if test="${not empty stu.photo}">
<a href="score_student?action=download&filename=${stu.photo}">下載圖片</a>
</c:if>
</td>
<td><a onclick="return confirm('你確定要刪除此記錄嗎?')"
href="score_student?action=delete&stuid=${stu.stuid}&photo=${stu.photo}">刪除</a>|
<a href="score_student?action=queryupdate&stuid=${stu.stuid}">修改</a>
</td>
</tr>
</c:forEach>
<c:if test="${empty pageBean.data}">
<tr>
<th colspan="8">沒有記錄</th>
</tr>
</c:if>
</tbody>
<tfoot>
<tr>
<th colspan="8">
當前頁${pageBean.curPageno}/${pageBean.totalPagecount}
<a href="#" onclick="go(1)">首頁</a>
<a href="#" onclick="go(${pageBean.curPageno-1})">上一頁</a>
<a href="#" onclick="go(${pageBean.curPageno+1})">下一頁</a>
<a href="#" onclick="go(${pageBean.totalPagecount})">尾頁</a>
總記錄數:${pageBean.totalRows}
<select name="curPage" onchange="go(this.value)">
<c:forEach begin="1" end="${pageBean.totalPagecount}" var="cc">
<c:if test="${cc==pageBean.curPageno}">
<option selected="selected">${cc }</option>
</c:if>
<c:if test="${cc!=pageBean.curPageno}">
<option>${cc }</option>
</c:if>
</c:forEach>
</select>
</th>
</tr>
</tfoot>
</table>
</form>
</body>
</html>
頁面效果