1、编写分页工具类
package com.smbms.util;
public class PageSupport {
//当前页码-来自于用户输入
private int currentPageNo = 1;
//总数量(表)
private int totalCount = 0;
//页面容量
private int pageSize = 0;
//总页数-totalCount/pageSize(+1)
private int totalPageCount = 1;
public int getCurrentPageNo() {
return currentPageNo;
}
public void setCurrentPageNo(int currentPageNo) {
if(currentPageNo > 0){
this.currentPageNo = currentPageNo;
}
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
if(totalCount > 0){
this.totalCount = totalCount;
//设置总页数
this.setTotalPageCountByRs();
}
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
if(pageSize > 0){
this.pageSize = pageSize;
}
}
public int getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public void setTotalPageCountByRs(){
if(this.totalCount % this.pageSize == 0){
this.totalPageCount = this.totalCount / this.pageSize;
}else if(this.totalCount % this.pageSize > 0){
this.totalPageCount = this.totalCount / this.pageSize + 1;
}else{
this.totalPageCount = 0;
}
}
}
2、在jsp文件夹编写用户管理页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%--UTF-8-Bom--%>
<%@include file="/jsp/common/head.jsp"%>
<div class="right">
<div class="location">
<strong>你现在所在的位置是:</strong>
<span>用户管理页面</span>
</div>
<div class="search">
<form method="get" action="${pageContext.request.contextPath }/jsp/user.do">
<input name="method" value="query" class="input-text" type="hidden">
<span>用户名:</span>
<input name="queryname" class="input-text" type="text" value="${queryUserName }">
<span>用户角色:</span>
<select name="queryUserRole">
<c:if test="${roleList != null }">
<option value="0">--请选择--</option>
<c:forEach var="role" items="${roleList}">
<option <c:if test="${role.id == queryUserRole }">selected="selected"</c:if>
value="${role.id}">${role.roleName}</option>
</c:forEach>
</c:if>
</select>
<input type="hidden" name="pageIndex" value="1"/>
<input value="查 询" type="submit" id="searchbutton">
<a href="${pageContext.request.contextPath}/jsp/useradd.jsp" >添加用户</a>
</form>
</div>
<!--用户-->
<table class="providerTable" cellpadding="0" cellspacing="0">
<tr class="firstTr">
<th width="10%">用户编码</th>
<th width="20%">用户名称</th>
<th width="10%">性别</th>
<th width="10%">年龄</th>
<th width="10%">电话</th>
<th width="10%">用户角色</th>
<th width="30%">操作</th>
</tr>
<c:forEach var="user" items="${userList }" varStatus="status">
<tr>
<td>
<span>${user.userCode }</span>
</td>
<td>
<span>${user.userName }</span>
</td>
<td>
<span>
<c:if test="${user.gender==1}">男</c:if>
<c:if test="${user.gender==2}">女</c:if>
</span>
</td>
<td>
<span>${user.age}</span>
</td>
<td>
<span>${user.phone}</span>
</td>
<td>
<span>${user.userRoleName}</span>
</td>
<td>
<span><a class="viewUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a></span>
<span><a class="modifyUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span>
<span><a class="deleteUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a></span>
</td>
</tr>
</c:forEach>
</table>
<input type="hidden" id="totalPageCount" value="${totalPageCount}"/>
<c:import url="rollpage.jsp">
<c:param name="totalCount" value="${totalCount}"/>
<c:param name="currentPageNo" value="${currentPageNo}"/>
<c:param name="totalPageCount" value="${totalPageCount}"/>
</c:import>
</div>
</section>
<!--点击删除按钮后弹出的页面-->
<div class="zhezhao"></div>
<div class="remove" id="removeUse">
<div class="removerChid">
<h2>提示</h2>
<div class="removeMain">
<p>你确定要删除该用户吗?</p>
<a href="#" id="yes">确定</a>
<a href="#" id="no">取消</a>
</div>
</div>
</div>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/userlist.js"></script>
3、在jsp文件夹增加分页页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
</script>
</head>
<body>
<div class="page-bar">
<ul class="page-num-ul clearfix">
<li>共${param.totalCount }条记录 ${param.currentPageNo }/${param.totalPageCount }页</li>
<c:if test="${param.currentPageNo > 1}">
<a href="javascript:page_nav(document.forms[0],1);">首页</a>
<a href="javascript:page_nav(document.forms[0],${param.currentPageNo-1});">上一页</a>
</c:if>
<c:if test="${param.currentPageNo < param.totalPageCount }">
<a href="javascript:page_nav(document.forms[0],${param.currentPageNo+1 });">下一页</a>
<a href="javascript:page_nav(document.forms[0],${param.totalPageCount });">最后一页</a>
</c:if>
</ul>
<span class="page-go-form"><label>跳转至</label>
<input type="text" name="inputPage" id="inputPage" class="page-key" />页
<button type="button" class="page-btn" onClick='jump_to(document.forms[0],document.getElementById("inputPage").value)'>GO</button>
</span>
</div>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/rollpage.js"></script>
</html>
4、 UserDao 增加 用户管理页面相关方法信息
package com.smbms.dao.user;
import com.smbms.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public interface UserDao {
//得到要登录的用户
......
//修改用户密码
......
//获取用户数量
......
//获取用户信息
public List<User> getUserList(Connection connection, String userName, int userRole,int pageIndex,int pageSize) throws SQLException;
//添加用户信息
int addUserInfo(Connection connection,User user) throws SQLException;
//根据ID获取用户信息,用作编辑,查看使用
User getUserInfoById(Connection connection,int id) throws SQLException;
//根据ID删除用户信息
int deleteUserInfo(Connection connection,int id) throws SQLException;
//根据用户编码查询用户是否存在
int userExistByCode(Connection connection,String userCode) throws SQLException;
}
5、 UserDaoImpl 实现用户管理页面相关方法信息
package com.smbms.dao.user;
import com.mysql.jdbc.StringUtils;
import com.smbms.dao.BaseDao;
import com.smbms.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements UserDao {
//获取用户登录
......
//修改用户密码
......
//获取用户数量
......
//获取用户信息
public List<User> getUserList(Connection connection, String userName, int userRole,int pageIndex,int pageSize) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<User> userList=new ArrayList<User>();
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT su.*,sr.roleName FROM smbms_user su ,smbms_role sr WHERE su.userRole=sr.id ");
ArrayList<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" and su.userName like ?");
list.add("%" + userName + "%");
}
if (userRole > 0) {
sql.append(" and su.userRole=?");
list.add(userRole);
}
sql.append(" ORDER BY su.creationDate DESC limit ?,?");
pageIndex=(pageIndex-1)*pageSize;
list.add(pageIndex);
list.add(pageSize);
Object[] objects = list.toArray();
resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql.toString(), objects);
while (resultSet.next()) {
User user=new User();
user.setId(resultSet.getInt("id"));
user.setUserCode(resultSet.getString("userCode"));
user.setUserName(resultSet.getString("userName"));
user.setGender(resultSet.getInt("gender"));
user.setBirthday(resultSet.getDate("birthday"));
user.setPhone(resultSet.getString("phone"));
user.setUserRole(resultSet.getInt("userRole"));
user.setUserRoleName(resultSet.getString("roleName"));
userList.add(user);
}
BaseDao.closeResource(null, resultSet, preparedStatement);
}
return userList;
}
//增加用户信息
public int addUserInfo(Connection connection,User user) throws SQLException {
PreparedStatement preparedStatement = null;
int execute = 0;
if (connection != null) {
String sql = "INSERT INTO smbms_user(userCode,userName,userPassword,gender,birthday,phone,address,userRole,createdBy,creationDate) VALUES(?,?,?,?,?,?,?,?,?,?)";
Object[] params = {user.getUserCode(), user.getUserName(),user.getUserPassword(),user.getGender(),user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole(),user.getCreatedBy(),user.getCreationDate()};
execute = BaseDao.execute(connection, preparedStatement, sql, params);
BaseDao.closeResource(null, null, preparedStatement);
}
return execute;
}
//根据ID获取用户信息,用作编辑,查看使用
public User getUserInfoById(Connection connection,int id) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user = null;
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT su.userCode,su.userName,su.gender,su.birthday,su.phone,su.address,su.userRole,sr.roleName AS `userRoleName` FROM smbms_user su,smbms_role sr WHERE sr.id=su.userRole and su.id=?");
Object[] objects = {id};
resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql.toString(), objects);
while (resultSet.next()) {
user =new User();
user.setUserCode(resultSet.getString("userCode"));
user.setUserName(resultSet.getString("userName"));
user.setGender(resultSet.getInt("gender"));
user.setBirthday(resultSet.getDate("birthday"));
user.setPhone(resultSet.getString("phone"));
user.setAddress(resultSet.getString("address"));
user.setUserRoleName(resultSet.getString("userRoleName"));
user.setUserRole(Integer.parseInt(resultSet.getString("userRole")));
}
BaseDao.closeResource(null, resultSet, preparedStatement);
}
return user;
}
//根据ID删除用户信息
public int deleteUserInfo(Connection connection,int id) throws SQLException {
PreparedStatement preparedStatement = null;
int execute = 0;
if (connection != null) {
String sql = "DELETE FROM smbms_user WHERE id=?";
Object[] params = {id};
execute = BaseDao.execute(connection, preparedStatement, sql, params);
BaseDao.closeResource(null, null, preparedStatement);
}
return execute;
}
//根据用户编码查询用户是否存在
public int userExistByCode(Connection connection, String userCode) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
int isExist = 0;
if (connection != null) {
String sql = "SELECT COUNT(1) as existCount FROM smbms_user su WHERE su.userCode=?";
Object[] objects = {userCode};
resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql.toString(), objects);
if (resultSet.next()) {
isExist = resultSet.getInt("existCount");
}
BaseDao.closeResource(null, resultSet, preparedStatement);
}
return isExist;
}
}
6、 UserService 增加 用户管理页面相关方法信息
package com.smbms.service.user;
import com.smbms.pojo.User;
import java.util.List;
public interface UserService {
//用户登录
......
//修改用户密码
......
//获取用户数量
......
//获取用户信息
public List<User> getUserList(String userName, int userRole,int pageIndex,int pageSize);
//添加用户信息
boolean addUserInfo(User user);
//根据ID获取用户信息,用作编辑,查看使用
User getUserInfoById(int id);
//根据ID删除用户信息
boolean deleteUserInfo(int id);
//根据用户编码查询用户是否存在
boolean userExistByCode(String userCode);
}
7、 UserServiceImpl 实现用户管理页面相关方法信息
package com.smbms.service.user;
import com.smbms.dao.BaseDao;
import com.smbms.dao.user.UserDao;
import com.smbms.dao.user.UserDaoImpl;
import com.smbms.pojo.Role;
import com.smbms.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserServiceImpl implements UserService {
//业务层调用Dao层,所以要引用Dao层
private UserDao userDao;
public UserServiceImpl() {
userDao = new UserDaoImpl();
}
//用户登录
.....
//修改密码
.....
//获取用户数量
.....
//获取用户信息
@Override
public List<User> getUserList(String userName, int userRole, int pageIndex, int pageSize) {
Connection connection=null;
List<User> userList=new ArrayList<User>();
try {
connection=BaseDao.getConnection();
userList = userDao.getUserList(connection, userName, userRole,pageIndex,pageSize);
} catch (SQLException e) {
e.printStackTrace();
}
finally {
BaseDao.closeResource(connection,null,null);
}
return userList;
}
//添加用户信息
public boolean addUserInfo(User user) {
Connection connection=null;
boolean flag=false;
try {
connection=BaseDao.getConnection();
connection.setAutoCommit(false);//开启JDBC事务管理
int addUserInfo = userDao.addUserInfo(connection, user);
connection.commit();
if(addUserInfo>0){
flag=true;
}
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
//根据ID获取用户信息,用作编辑,查看使用
public User getUserInfoById(int id) {
Connection connection=null;
User user=null;
try {
connection=BaseDao.getConnection();
user=userDao.getUserInfoById(connection, id);
} catch (SQLException e) {
e.printStackTrace();
}
finally {
BaseDao.closeResource(connection,null,null);
}
return user;
}
//根据ID删除用户信息
public boolean deleteUserInfo(int id) {
Connection connection=null;
boolean flag=false;
try {
connection=BaseDao.getConnection();
connection.setAutoCommit(false);//开启JDBC事务管理
int deluser = userDao.deleteUserInfo(connection, id);
connection.commit();
if(deluser>0){
flag=true;
}
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
//根据用户编码查询用户是否存在
public boolean userExistByCode(String userCode) {
Connection connection=null;
boolean flag=false;
try {
connection=BaseDao.getConnection();
if(userDao.userExistByCode(connection, userCode)>0){
flag=true;
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
}
8、 UserServlet 增加 获取用户信息方法
package com.smbms.servlet.user;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import com.smbms.pojo.Role;
import com.smbms.pojo.User;
import com.smbms.service.role.RoleServiceImpl;
import com.smbms.service.user.UserService;
import com.smbms.service.user.UserServiceImpl;
import com.smbms.util.Constants;
import com.smbms.util.PageSupport;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//method 方便Servlet复用
String method = req.getParameter("method");
if (method != null && method.equals("savepwd")) { //修改密码
this.updatePwd(req, resp);
}
else if (method != null && method.equals("pwdmodify")) { //验证旧密码
this.pawModify(req, resp);
}
else if (method != null && method.equals("getrolelist")) {//获取用户角色
this.getRoleList(req, resp);
}
else if (method != null && method.equals("query")) { //用户列表
this.getUserList(req, resp);
}
else if (method != null && method.equals("ucexist")) {//判断用户编码是否存在
this.userExistByCode(req, resp);
}
else if (method != null && method.equals("add")) {//添加用户信息
this.addUserInfo(req, resp);
}
else if (method != null && (method.equals("modify") || method.equals("view"))) {//修改回显、查看
String url="";
if(method.equals("modify")){
url="usermodify.jsp";
}
if(method.equals("view")){
url="userview.jsp";
}
this.getUserInfoById(req, resp,url);
}
else if (method != null && method.equals("deluser")) {//删除用户
this.deleteUserInfo(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
//修改用户密码
......
//验证旧密码
......
//获取角色列表
......
//获取用户信息
public void getUserList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String queryUserName = req.getParameter("queryname");
String temp = req.getParameter("queryUserRole");
String pageIndex = req.getParameter("pageIndex");
String pageSize = req.getParameter("pageSize");
int queryUserRole=0;
int PageSize=5;
int currentPageNo=1;
UserServiceImpl userService = new UserServiceImpl();
if(queryUserName==null){
queryUserName="";
}
if(temp!=null && !temp.equals(""))
{
queryUserRole=Integer.parseInt(temp);
}
if(pageIndex!=null){
currentPageNo=Integer.parseInt(pageIndex);
}
if(pageSize!=null){
PageSize=Integer.parseInt(pageSize);
}
//获取用户数量
int totalCount = userService.getUserCount(queryUserName, queryUserRole);
//设置分页信息
PageSupport pageSupport=new PageSupport();
pageSupport.setCurrentPageNo(currentPageNo);
pageSupport.setPageSize(PageSize);
pageSupport.setTotalCount(totalCount);
//获取总页数
int totalPageCount = ((int)(totalCount/PageSize))+1;
//控制首页和尾页
//如果页面小于1 默认第一页
if(totalCount<1){
currentPageNo=1;
}else if(currentPageNo>totalCount){//当前页面大于最后一页,显示最后一页
currentPageNo=totalCount;
}
//获取用户信息
List<User> userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, PageSize);
req.setAttribute("userList",userList);
RoleServiceImpl roleService=new RoleServiceImpl();
//获取角色列表
List<Role> roleList = roleService.getRoleList();
req.setAttribute("roleList",roleList);
//返回分页信息
req.setAttribute("totalCount",totalCount);
req.setAttribute("currentPageNo",currentPageNo);
req.setAttribute("totalPageCount",totalPageCount);
//返回查询信息
req.setAttribute("queryUserName",queryUserName);
req.setAttribute("queryUserRole",queryUserRole);
//返回前端
req.getRequestDispatcher("userlist.jsp").forward(req,resp);
}
//添加用户信息
public void addUserInfo(HttpServletRequest req, HttpServletResponse resp) {
String userCode = req.getParameter("userCode");
String userName = req.getParameter("userName");
String userPassword = req.getParameter("userPassword");
String gender = req.getParameter("gender");
String birthday = req.getParameter("birthday");
String phone = req.getParameter("phone");
String address = req.getParameter("address");
String userRole = req.getParameter("userRole");
Date date= null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
} catch (ParseException e) {
e.printStackTrace();
}
User user=new User();
user.setUserCode(userCode);
user.setUserName(userName);
user.setUserPassword(userPassword);
user.setGender(Integer.parseInt( gender));
user.setBirthday(date);
user.setPhone(phone);
user.setAddress(address);
user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
user.setCreationDate(new Date());
user.setUserRole(Integer.parseInt(userRole));
UserService service = new UserServiceImpl();
boolean info = service.addUserInfo(user);
if(info) {
try {
resp.sendRedirect("user.do?method=query");
} catch (IOException e) {
e.printStackTrace();
}
}else {
try {
req.setAttribute("message", "添加失败!");
req.getRequestDispatcher("useradd.jsp").forward(req, resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//根据ID获取用户信息,用作编辑,查看使用
public void getUserInfoById(HttpServletRequest req, HttpServletResponse resp,String url) throws ServletException, IOException {
String id=req.getParameter("uid");
if(!StringUtils.isNullOrEmpty(id)){
UserService userService=new UserServiceImpl();
User userInfoById = userService.getUserInfoById(Integer.parseInt(id));
req.setAttribute("user", userInfoById);
req.getRequestDispatcher(url).forward(req,resp);
}
}
//根据ID删除用户信息
public void deleteUserInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String id=req.getParameter("uid");
Integer delid=0;
try {
delid=Integer.parseInt(id);
}catch (Exception e)
{
delid=0;
}
HashMap<String,String>resultMpa=new HashMap<String, String>();
if(delid<=0){
resultMpa.put("delResult", "notexist");
}else {
UserService userService=new UserServiceImpl();
if(userService.deleteUserInfo(delid)){
resultMpa.put("delResult", "true");
}
else {
resultMpa.put("delResult", "false");
}
}
//把resultMpa转换成json对象输出
resp.setContentType("application/json");
PrintWriter outPrintWriter=resp.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMpa));
outPrintWriter.flush();
outPrintWriter.close();
}
//根据用户编码查询用户是否存在
public void userExistByCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String userCode=req.getParameter("userCode");
HashMap<String,String>resultMpa=new HashMap<String, String>();
UserService userService=new UserServiceImpl();
boolean exist = userService.userExistByCode(userCode);
if(exist){
resultMpa.put("userCode", "exist");
}
else {
resultMpa.put("userCode", "false");
}
//把resultMpa转换成json对象输出
resp.setContentType("application/json");
PrintWriter outPrintWriter=resp.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMpa));
outPrintWriter.flush();
outPrintWriter.close();
}
}
8、测试