用戶信息查詢功能
1. 網頁設計
本能地想找一個表格的模板,奈何模板之家裏並沒用,所以只好自己寫一個界面了。。ค(TㅅT)
界面極其簡陋,湊合着用。。
2. 後臺代碼實現
在實現查詢功能之前,先分析一下:在(二)中,管理員登錄完成後重定向到FindServletByPage這個servlet中,我們應該在這個servlet裏面實現分頁查詢的功能,相比較查詢所有信息,分頁查詢每次只查詢一定數量的信息並且顯示在界面中,使得界面條理清晰,更友好,而查詢所有信息並且顯示在一個界面上,顯然當數據龐大時,就顯得界面冗長了。因此,我們將一個Page封裝成一個JavaBean。
PageBean類
package cn.hehewocao.POJO;
import java.util.List;
public class PageBean<T> {
private int page; //當前頁數
private int row; // 分頁條數
private List<T> list; //查詢的每頁記錄
private int count; //總記錄數
private int pages; //展示數據的總頁數
public PageBean() {
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
@Override
public String toString() {
return "PageBean{" +
"page=" + page +
", row=" + row +
", list=" + list +
", count=" + count +
", pages=" + pages +
'}';
}
}
分頁查詢Servlet:FindServletByPage
package cn.hehewocao.Servlet;
import cn.hehewocao.POJO.User;
import cn.hehewocao.Service.UserService;
import cn.hehewocao.Service.UserServiceImp;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import cn.hehewocao.POJO.PageBean;
@WebServlet("/findServletByPage")
public class FindServletByPage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String page = req.getParameter("page");
String rows = req.getParameter("rows");
Map<String, String[]> parameterMap = req.getParameterMap();//查詢條件
UserService us = new UserServiceImp();
PageBean<User> pb = us.findByPage(page, rows, parameterMap);
req.setAttribute("pageBean", pb);//保存查詢後的PageBean對象
req.setAttribute("condition",parameterMap);//將查詢條件保存到request中,以便回顯
req.getRequestDispatcher("list.jsp").forward(req, resp);//轉發到list.jsp顯示數據
}
}
UserServiceImp類中添加方法:
public PageBean<User> findByPage(String _page, String _rows, Map<String,String[]> info) {//封裝PageBean對象
PageBean<User> pb = new PageBean<User>();
//設置默認值
if ("".equals(_page) || _page == null) {
_page = "1";
}
if ("".equals(_rows) || _rows == null) {
_rows = "5";
}
int page = Integer.parseInt(_page);
int rows = Integer.parseInt(_rows);
if(page < 1){
page = 1;
}
if(rows < 1){
rows = 1;
}
//設置查詢的頁數和每頁的記錄條數
pb.setPage(page);
pb.setRow(rows);
UserDao ud = new UserDaoImp();
int count = ud.findCount(info);
//總記錄數
pb.setCount(count);
int startIndex = (page - 1) * rows;
List<User> list = ud.findByPage(startIndex,rows,info);
if (list == null || list.size() == 0){
return null;
}
//該頁記錄集合
pb.setList(list);
//頁數
int pages = count % rows == 0 ? count/rows : count/rows + 1;
pb.setPages(pages);
return pb;
}
UserDaoImp類中添加方法:
public int findCount(Map<String, String[]> info) {//查詢總記錄數
/*初始化sql語句*/
String sql = "select count(*) from user where 1 = 1 ";
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDateSource());
List<String> list = new ArrayList<String>();
for (String key : info.keySet()) {
if (!"".equals(info.get(key)[0]) && info.get(key)[0] != null) {
if (!key.equals("page")) {
if (!key.equals("rows")) {
sql += " and " + key + " like ? ";
list.add("%" + info.get(key)[0] + "%");
}
}
}
}
return jdbcTemplate.queryForObject(sql, list.toArray(), int.class);
}
3. JSP頁面設計
該界面主要就是從request中獲取PageBean對象中保存的數據
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3個meta標籤*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
<title>用戶管理</title>
<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim 和 Respond.js 是爲了讓 IE8 支持 HTML5 元素和媒體查詢(media queries)功能 -->
<!-- 警告:通過 file:// 協議(就是直接將 html 頁面拖拽到瀏覽器中)訪問頁面時 Respond.js 不起作用 -->
<!--[if lt IE 9]>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html5shiv.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dest/respond.min.js"></script>
<![endif]-->
<style>
tr, th, td {
text-align: center;
}
</style>
</head>
<body>
<div style="width: 70%;margin-left: 15%;margin-top: 50px;" align="center">
<form class="form-inline" action="${pageContext.request.contextPath}/findServletByPage" method="post">
<div class="form-group">
<label>編號</label>
<input id="id" type="text" name="id" value="${condition.id[0]}" placeholder="輸入編號" align="center"/>
</div>
<div class="form-group">
<label>用戶名</label>
<input id="username" type="text" value="${condition.username[0]}" name="username" placeholder="輸入用戶名" align="center"/>
</div>
<div class="form-group">
<label>暱稱</label>
<input type="text" id="nickname" value="${condition.nickname[0]}" name="nickname" placeholder="暱稱" align="center"/>
</div>
<div class="form-group">
<label>地址</label>
<input type="text" id="address" value="${condition.address[0]}" name="address" placeholder="地址" align="center"/>
</div>
<button type="submit" class="btn btn-default" id="find">查詢</button>
<a href="register.jsp"><button type="button" class="btn btn-primary">添加用戶</button></a>
</form>
</div>
<div style="width: 80%;margin-left: 10%;margin-top: 50px;">
<table class="table table-hover">
<tr>
<th>編號</th>
<th>用戶名</th>
<th>密碼</th>
<th>暱稱</th>
<th>性別</th>
<th>生日</th>
<th>手機號</th>
<th>郵箱</th>
<th>地址</th>
<th>職業</th>
<th>描述</th>
<th colspan="2">操作</th>
</tr>
<c:if test="${not empty pageBean}">
<c:forEach items="${pageBean.list}" var="user" begin="0" end="${pageBean.list.size() - 1}" step="1"
varStatus="s">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td>${user.nickname}</td>
<td>${user.sex}</td>
<td>${user.birthday}</td>
<td>${user.phone}</td>
<td>${user.email}</td>
<td>${user.address}</td>
<td>${user.occupation}</td>
<td>${user.describes}</td>
<td><a href="${pageContext.request.contextPath}/updateUserForwordServlet?beforeUserId=${user.id}" name="del" id="update${s}">修改</a></td>
<td><a href="${pageContext.request.contextPath}/delServletById?delId=${user.id}" name="del" id="${s}"
onclick="delLine(this)">刪除</a></td>
</tr>
</c:forEach>
</c:if>
</table>
</div>
<%--分頁欄--%>
<div align="center" style="margin-top: 50px;">
<nav aria-label="Page navigation">
<ul class="pagination">
<c:if test="${pageBean.page == 1}">
<li class="disabled">
<a href="#"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:if test="${pageBean.page != 1}">
<li>
<a href="${pageContext.request.contextPath}/findServletByPage?page=${pageBean.page - 1}&rows=5&id=${condition.id[0]}&username=${condition.username[0]}&nickname=${condition.nickname[0]}&address=${condition.address[0]}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach begin="1" end='${pageContext.request.getAttribute("pageBean").pages}' var="i">
<c:if test="${pageBean.page == i}">
<li class="active"><a
href='${pageContext.request.contextPath}/findServletByPage?page=${i}&rows=5&id=${condition.id[0]}&username=${condition.username[0]}&nickname=${condition.nickname[0]}&address=${condition.address[0]}'>${i}</a></li>
</c:if>
<c:if test="${pageBean.page != i}">
<li><a href='${pageContext.request.contextPath}/findServletByPage?page=${i}&rows=5&id=${condition.id[0]}&username=${condition.username[0]}&nickname=${condition.nickname[0]}&address=${condition.address[0]}'>${i}</a></li>
</c:if>
</c:forEach>
<c:if test="${pageBean.pages == pageBean.page}">
<li class="disabled">
<a href="#"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<c:if test="${pageBean.pages != pageBean.page}">
<li>
<a href="${pageContext.request.contextPath}/findServletByPage?page=${pageBean.page + 1}&rows=5&id=${condition.id[0]}&username=${condition.username[0]}&nickname=${condition.nickname[0]}&$address=${condition.address[0]}"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
</ul>
</nav>
<p style="font-weight: bold">
共${pageBean.count == null ? 0 : pageBean.count}條記錄,共${pageBean.pages == null ? 0 : pageBean.pages}頁</p>
</div>
<script>
function delLine(obj) {
if (confirm("確認刪除?")) {
return true;
}
}
</script>
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依賴 jQuery,所以必須放在前邊) -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<!-- 加載 Bootstrap 的所有 JavaScript 插件。你也可以根據需要只加載單個插件。 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
</body>
</html>
至此就實現了用戶信息的分頁查詢功能。