【項目實踐】SMBMS(Javaweb版)(四)用戶管理
用戶管理模塊
用戶管理模塊需要包含的功能需要有添加用戶、刪除用戶、查詢用戶、修改用戶;顯示時會進行表單顯示,有分頁功能,頁碼計算功能。
前期準備
共同工具類
翻頁使用的對象工具類,計算頁數方式如下:
每次顯示的頁數 = 總件數 % 單頁顯示的件數 == 0 ? 總件數 / 單頁顯示的件數 :(總件數 / 單頁顯示的件數)+1;
package com.common.utils;
public class PageSupport {
private int pageIndex = 1; // 當前頁碼
private int pageSize; // 總頁數
private int totalCount; // 總記錄數
private int totalPageCount; // 每頁顯示的記錄數
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
if (pageIndex > 0) {
this.pageIndex = pageIndex;
}
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
if (pageSize > 0) {
this.pageSize = pageSize;
}
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
if (totalCount > 0) {
this.totalCount = totalCount;
setByPageNo(totalCount);
}
}
public int getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
/**
* 根據總記錄數設置總頁數
* 此方法用于計算分頁時的總頁數,基于當前的每頁記錄數(pageSize)
*
* @param totalCount 總記錄數,即需要分頁處理的數據總量
*/
private void setByPageNo(int totalCount) {
// 計算總頁數:如果總記錄數除以每頁記錄數的余數為0,則總頁數為總記錄數除以每頁記錄數;
// 否則,總頁數為總記錄數除以每頁記錄數加1
this.totalPageCount = totalCount % pageSize == 0 ? totalCount / pageSize :
totalCount / pageSize + 1;
}
}
導入前端代碼
導入前端頁面和相關js,跳轉頁面的時候及翻頁的時候使用。
獲取用戶數量
需要為查詢數據做好基礎,涉嫌到數據統計。
UserDao
通過用戶名稱或角色查詢獲取用戶數量,設計的功能模塊有關下拉選擇查詢總數。
- UserDao
/**
* 獲取用戶數量(根據用戶名和角色篩選)
*
* @param connection 數據庫連接對象
* @param queryUserName 查詢的用戶名
* @param queryUserRole 查詢的角色
* @return 用戶數量
* @throws Exception 異常處理
*/
int getUserCount(Connection connection, String queryUserName, Integer queryUserRole) throws Exception;
- UserDaoImpl
/**
* 獲取用戶數量(根據用戶名和角色篩選)
*
* @param connection 數據庫連接對象
* @param queryUserName 查詢的用戶名
* @param queryUserRole 查詢的角色
* @return 用戶數量
* @throws Exception 異常處理
*/
@Override
public int getUserCount(Connection connection, String queryUserName, Integer queryUserRole) throws Exception {
// 初始化用戶數量為0
int userCount = 0;
// 預編譯SQL語句對象
PreparedStatement preparedStatement = null;
// 結果集對象
ResultSet resultSet = null;
// 存儲查詢參數的列表
ArrayList<Object> list = new ArrayList<>();
// 檢查數據庫連接是否不為空
if (connection != null) {
// 構建基礎SQL查詢語句
String sql = "select count(1) as userCount from smbms_user u, smbms_role r where u" +
".userRole = r.id ";
// 如果查詢用戶名不為空,則添加用戶名模糊查詢條件
if (queryUserName != null && !queryUserName.isEmpty()) {
sql += "and u.userName like ? ";
list.add("%" + queryUserName + "%");
}
// 如果查詢角色不為空且大于0,則添加角色精確查詢條件
if (queryUserRole != null && queryUserRole > 0) {
sql += "and u.userRole = ? ";
list.add(queryUserRole);
}
// 準備SQL語句執行
preparedStatement = connection.prepareStatement(sql);
// 將查詢參數列表轉換為數組形式
Object[] params = list.toArray();
// 執行查詢并獲取結果集
resultSet = BaseDao.executeQuery(connection, sql, preparedStatement, params, resultSet);
// 如果結果集不為空,則從結果集中獲取用戶數量
if (resultSet != null) {
userCount = resultSet.getInt("userCount");
} else {
// 如果結果集為空,輸出提示信息
System.out.println("用戶查詢不到");
}
// 關閉數據庫資源
BaseDao.closeResource(connection, preparedStatement, resultSet);
}
// 返回用戶數量
return userCount;
}
UserService
調用Dao層的sql處理,如果出現問題及時拋出異常,之后在進行關閉連接。
- UserService
public int getUserCount(String queryUserName, Integer queryUserRole);
- UserServiceImpl
/**
* 獲取用戶數量
* 根據用戶名和用戶角色查詢用戶數量
*
* @param queryUserName 查詢的用戶名,如果為null,則不根據用戶名進行篩選
* @param queryUserRole 查詢的用戶角色,如果為null,則不根據用戶角色進行篩選
* @return 返回查詢到的用戶數量
*/
@Override
public int getUserCount(String queryUserName, Integer queryUserRole) {
// 定義數據庫連接對象
Connection conn = null;
// 初始化用戶數量為0
int userCouts = 0;
try {
// 獲取數據庫連接
conn = BaseDao.connection();
// 調用UserDao的getUserCount方法查詢用戶數量
userCouts = userDao.getUserCount(conn, queryUserName, queryUserRole);
} catch (Exception e) {
// 打印異常信息
e.printStackTrace();
} finally {
// 關閉數據庫資源
BaseDao.closeResource(conn, null, null);
}
// 返回查詢到的用戶數量
return userCouts;
}
獲取用戶列表
根據查詢條件查詢需要的數據,根據翻頁頁數計算需要顯示的數據是那些條;
UserDao
使用order by和 limit 關鍵字 應用;
- userDao
List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception;
- userDaoImpl
/**
* 分頁查詢用戶集合
* @param connection 數據庫連接
* @param userName 用戶名字
* @param userRole 角色id
* @param currentPageNo 當前頁碼
* @param pageSize 每頁數量
* @return 用戶對象集合
* @throws Exception 拋出SQL異常
*/
@Override
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
List<User> users = new ArrayList<>();
if (connection == null) {
return users;
}
PreparedStatement preparedStatement = null;
ResultSet rs = null;
StringBuilder sql = new StringBuilder();
sql.append("select u.*, r.roleName as userRoleName from smbms_user u, smbms_role r where u.userRole = r.id");
List<Object> list = new ArrayList<>();
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" and u.userName like ?");
list.add("%" + userName + "%");
}
if (userRole > 0) {
sql.append(" and u.userRole = ?");
list.add(userRole);
}
sql.append(" order by creationDate DESC limit ?, ?");
// 準備SQL語句執行
preparedStatement = connection.prepareStatement(sql.toString());
currentPageNo = (currentPageNo - 1) * pageSize;
list.add(currentPageNo);
list.add(pageSize);
Object[] params = list.toArray();
rs = BaseDao.executeQuery(connection, sql.toString(),preparedStatement, params, rs);
while (rs.next()) {
User user = getUserByResult(rs);
user.setUserRoleName(rs.getString("userRoleName"));
users.add(user);
}
BaseDao.closeResource(connection,preparedStatement, rs);
return users;
}
UserService
- UserService
List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo,
int pageSize);
- UserServiceImpl
/**
* @param queryUserName
* @param queryUserRole
* @param currentPageNo
* @param pageSize
* @return
*/
@Override
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo,
int pageSize) {
Connection conn = null;
List<User> userList = null;
try {
conn = BaseDao.connection();
userList = userDao.getUserList(conn, queryUserName, queryUserRole, currentPageNo,
pageSize);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(conn, null, null);
}
return userList;
}
獲取用戶角色 列表
查詢數據庫中的角色
RoleDao
- RoleDao
package com.dashangms.dao.role;
import com.dashangms.dao.BaseDao;
import com.dashangms.pojo.Role;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public interface RoleDao {
List<Role> getRoleList(Connection connection) throws SQLException;
}
- RoleDaoImpl
package com.dashangms.dao.role;
import com.dashangms.dao.BaseDao;
import com.dashangms.pojo.Role;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class RoleDaoImpl implements RoleDao {
/**
* 獲取角色列表
*
* @param connection 數據庫連接對象,用于執行SQL查詢
* @return 返回一個Role對象列表,包含從數據庫查詢到的所有角色信息
* @throws SQLException 如果在執行數據庫操作時發生錯誤
*/
@Override
public List<Role> getRoleList(Connection connection) throws SQLException {
// 創建一個ArrayList用于存儲Role對象
ArrayList<Role> roleList = new ArrayList<Role>();
// 定義ResultSet對象用于存儲查詢結果
ResultSet resultSet = null;
// 檢查傳入的數據庫連接對象是否不為空
if (connection != null) {
// 定義SQL查詢語句,用于從smbms_role表中查詢所有數據
String sql = "select * from smbms_role";
// 定義一個空的參數數組,用于執行帶有參數的SQL語句(此處無參數)
Object[] params = {};
// 執行SQL查詢,并將結果存儲在resultSet中
resultSet = BaseDao.executeQuery(connection, sql, null, params, resultSet);
// 遍歷查詢結果,將每條記錄封裝成Role對象
while (resultSet.next()) {
Role role = new Role();
// 從結果集中獲取id、roleCode、roleName等字段,并設置到Role對象中
role.setId(resultSet.getInt("id"));
role.setRoleCode(resultSet.getString("roleCode"));
role.setRoleName(resultSet.getString("roleName"));
role.setCreateBy(resultSet.getInt("createBy"));
role.setCreateDate(resultSet.getTimestamp("createDate"));
role.setModifyBy(resultSet.getInt("modifyBy"));
role.setModifyDate(resultSet.getTimestamp("modifyDate"));
// 將封裝好的Role對象添加到列表中
roleList.add(role);
}
// 關閉數據庫資源,包括連接、聲明和結果集
BaseDao.closeResource(connection, null, resultSet);
}
// 返回角色列表
return roleList;
}
}
RoleService
- RoleService
package com.dashangms.service.role;
import com.dashangms.pojo.Role;
import java.util.List;
public interface RoleService {
List<Role> getRoleList();
}
- RoleServiceImpl
package com.dashangms.service.role;
import com.dashangms.dao.BaseDao;
import com.dashangms.dao.role.RoleDaoImpl;
import com.dashangms.pojo.Role;
import com.dashangms.dao.role.RoleDao;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
public class RoleServiceImpl implements RoleService{
private RoleDao roleDao;
public RoleServiceImpl() {
roleDao = new RoleDaoImpl();
}
/**
*/
@Override
public List<Role> getRoleList() {
Connection connection = null;
List<Role> roleList = null;
try {
connection = BaseDao.connection();
roleList = roleDao.getRoleList(connection);
}catch (Exception e){
e.printStackTrace();
}
finally {
BaseDao.closeConnection(connection);
}
return roleList;
}
}
編寫查詢用戶的Servlet
編寫查詢的servlet,在畫面初次加載或者查詢的時候調用該方法,查詢數據,顯示分頁,避免非空場景。
doGet方法
if ("query".equals(method)) {
query(req, resp);
}
query方法
/**
* 處理用戶查詢請求的方法
* 該方法根據用戶輸入的查詢條件(用戶名和用戶角色)以及分頁信息(當前頁碼),
* 查詢并返回用戶列表同時將結果存儲在HttpServletRequest對象中,
* 以便在JSP頁面中顯示
*
* @param req 用于獲取請求參數和設置屬性的HttpServletRequest對象
* @param resp 用于響應的HttpServletResponse對象
*/
private void query(HttpServletRequest req, HttpServletResponse resp) {
// 獲取查詢條件:用戶名和用戶角色
String queryUserName = req.getParameter("queryUserName");
String queryUserRoleTemp = req.getParameter("queryUserRole");
String pageIndex = req.getParameter("pageIndex");
int queryUserRole = 0; // 默認用戶角色
// 創建UserService實例
UserService userService = new UserServiceImpl();
List<User> userList;
// 默認分頁設置
int currentPageNo = 1;
int pageSize = 5;
// 處理查詢條件,確保空值安全
queryUserName = queryUserName == null ? "" : queryUserName;
queryUserRole = queryUserRoleTemp.isEmpty() ? queryUserRole :
Integer.parseInt(queryUserRoleTemp);
currentPageNo = pageIndex == null ? currentPageNo : Integer.parseInt(pageIndex);
// 獲取用戶總數,用于分頁
int totalCount = userService.getUserCount(queryUserName, queryUserRole);
// 創建并配置PageSupport對象
PageSupport pageSupport = new PageSupport();
pageSupport.setPageIndex(currentPageNo);
pageSupport.setPageSize(pageSize);
pageSupport.setTotalCount(totalCount);
// 計算總頁數
int totalPageCount = pageSupport.getTotalPageCount();
// 校驗當前頁碼
if (currentPageNo < 1) {
currentPageNo = 1;
} else {
if (currentPageNo > totalPageCount) {
currentPageNo = totalPageCount;
}
}
// 根據查詢條件和分頁信息獲取用戶列表
userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
// 將用戶列表和其他信息存儲在請求對象中
req.setAttribute("userList", userList);
// 創建RoleService實例并獲取角色列表
RoleService 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);
// 轉發到userlist.jsp頁面顯示結果
try {
req.getRequestDispatcher("/userlist.jsp").forward(req, resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
添加用戶子模塊
添加用戶,查找用戶是否存在;需要考慮到添加失敗后事務回滾
導入jsp請求按鈕
UserDao邏輯
- UserDao
//用戶管理模塊中的 子模塊—— 添加用戶
public int addUser(Connection conn,User user)throws SQLException;
- UserDaoImpl
//用戶管理模塊中的 子模塊—— 添加用戶
public int addUser(Connection conn,User user)throws SQLException{{
PreparedStatement preparedStatement;
int updateRows = 0;
if(connection != null){
String sql = "insert into smbms_user (userCode,userName,userPassword,gender,birthday,phone,address,userRole,createdBy,creationDate)values(?,?,?,?,?,?,?,?,?,?)";
Object[] params ={user.getUserRole(),user.getUserName(),user.getUserPassword(),user.getGender(),user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole(),user.getCreatedBy(),user.getCreateDate()};
preparedStatement = connection.prepareStatement(sql);
//執行sql 返回執行結果(成功的語句數量)
updateRows= BaseDao.executeUpdate(connection,sql,preparedStatement,params);
//釋放資源
BaseDao.closeResource(null,preparedStatement,null);
}
return updateRows;
}
UserService邏輯
- UserService
//用戶管理模塊中的 子模塊—— 添加用戶
boolean addUser(User user);
- UserServiceImpl
/**
* @param user
* @return
*/
@Override
public boolean addUser(User user) throws SQLException {
Connection conn = null;
boolean flag = false;
try {
//獲取數據庫連接
conn = BaseDao.connection();
//開啟JDBC事務管理
conn.setAutoCommit(false);
//Service層調用dao層的方法添加用戶
int updateRows = userDao.add(conn, user);
conn.commit();
if(updateRows > 0){
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
if (conn != null) {
conn.rollback();
}
}finally {
//釋放連接
BaseDao.closeResource(conn,null,null);
}
return flag;
}
刪除用戶子模塊
導入jsp請求按鈕
UserDao邏輯
- UserDao
int deleteUserById(Connection connection, Integer delId) throws Exception;
- UserDaoImpl
/**
* 根據用戶id刪除用戶
*
* @param connection 數據庫連接對象
* @param delId 刪除的用戶id
* @return 影響行數
* @throws Exception 異常處理
*/
@Override
public int deleteUserById(Connection connection, Integer delId) throws Exception {
PreparedStatement preparedStatement = null;
int updateRows = 0;
if(connection != null){
String sql = "delete from smbms_user where id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, delId);
updateRows = preparedStatement.executeUpdate();
}
BaseDao.closeResource(connection, preparedStatement, null);
return updateRows;
}
UserService邏輯
- UserService
int deleteUser(Integer delId);
- UserServiceImpl
/**
* @param delId
* @return
*/
@Override
public int deleteUser(Integer delId) {
Connection conn = null;
int delectedRows = 0;
try {
conn = BaseDao.connection();
delectedRows = userDao.deleteUserById(conn, delId);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(conn, null, null);
}
return delectedRows;
}
修改用戶子模塊
導入jsp請求按鈕,檢查
UserDao邏輯
- UserDao
int modify(Connection connection, User user) throws Exception;
- UserDaoImpl
/**
* 修改用戶信息
*
* @param connection 數據庫連接對象
* @param user 用戶對象
* @return 影響行數
* @throws Exception 異常處理
*/
@Override
public int modify(Connection connection, User user) throws Exception {
PreparedStatement preparedStatement = null;
int updateRows = 0;
if(connection != null){
String sql = "update smbms_user " +
" set userName = ?, " +
" gender = ?, " +
" birthday = ?, " +
" phone = ?, " +
" address = ?, " +
" userRole = ?, " +
" modifyBy = ?, " +
" modifyDate = ? " +
"where " +
" id = ?";
Object[] params = {
user.getUserName(),
user.getGender(),
user.getBirthday(),
user.getPhone(),
user.getAddress(),
user.getUserRole(),
user.getModifyBy(),
user.getModifyDate(),
user.getId()
};
preparedStatement = connection.prepareStatement(sql);
updateRows = BaseDao.executeUpdate(connection, sql, preparedStatement, params);
BaseDao.closeResource(connection, preparedStatement, null);
}
return updateRows;
}
UserService邏輯
- UserService
int modifyUser(User user);
- UserServiceImp
/**
* @param user
* @return
*/
@Override
public int modifyUser(User user) {
Connection conn = null;
int updateRows = 0;
try {
conn = BaseDao.connection();
updateRows = userDao.modify(conn, user);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(conn, null, null);
}
return updateRows;
}
查詢用戶子模塊
導入jsp請求按鈕,檢查
思路:
- 跟前面查詢數據走同一個Dao的數據查詢邏輯,在service/servlet層對數據進行區分?
- 通過畫面hidden項傳遞?
- 通過頁面id(主鍵查詢)傳遞?
Servlet
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if ("savePassword".equals(method)) {
savePassword(req, resp);
} else if ("query".equals(method)) {
query(req, resp);
} else if ("modify".equals(method)) {
modify(req, resp);
} else if ("delete".equals(method)) {
delete(req, resp);
} else if ("add".equals(method)) {
try {
add(req, resp);
} catch (SQLException e) {
throw new RuntimeException(e);
}
} else if ("viewUser".equals(method)) {
viewUser(req, resp);
}
}
/**
* 該方法用于處理用戶信息查看請求
* 它從HTTP請求中提取用戶ID,調用服務層方法獲取用戶信息,
* 并將用戶信息發送到前端頁面進行展示
*
* @param req HTTP請求對象,用于獲取請求參數和設置屬性
* @param resp HTTP響應對象,用于跳轉到其他頁面
* @throws ServletException 如果Servlet操作失敗
* @throws IOException 如果輸入輸出操作失敗
*/
private void viewUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//從前端獲取 要查詢用戶 的id
String id = req.getParameter("id");
int userId = 0;
try {
//將獲取到的字符串id轉換為整型,以便后續使用
userId = Integer.parseInt(id);
} catch (Exception e) {
//異常處理:打印錯誤信息,如果轉換失敗
e.printStackTrace();
}
//調用 根據id查詢用戶信息的方法
UserServiceImpl userService = new UserServiceImpl();
User user = userService.getUserById(userId);
//將此user發送到展示前端 的頁面進行展示
req.setAttribute("user", user);
//跳轉到前端 的展示頁面
req.getRequestDispatcher("userview.jsp").forward(req, resp);
}
}
UserService邏輯 :getUserById
- UserService
User getUserById(int userId);
- UserServiceImpl
/**
* @param userId
* @return
*/
@Override
public User getUserById(int userId) {
Connection conn = null;
User user = null;
try {
conn = BaseDao.connection();
user = userDao.getUserById(conn, userId);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(conn, null, null);
}
return user;
}
UserDao
- UserDao
/**
* 根據用戶id獲取用戶信息
*
* @param connection 數據庫連接對象
* @param id 用戶id
* @return 用戶對象
* @throws Exception 異常處理
*/
User getUserById(Connection connection, int id) throws Exception;
- UserDaoImpl :主鍵查詢
/**
* 根據用戶id獲取用戶信息
*
* @param connection 數據庫連接對象
* @param id 用戶id 主鍵
* @return 用戶對象
* @throws Exception 異常處理
*/
@Override
public User getUserById(Connection connection, int id) throws Exception {
PreparedStatement preparedStatement = null;
ResultSet rs = null;
List<User> users = new ArrayList<>();
User user = new User();
if(connection != null){
String sql = "select * from smbms_user where id = ?";
preparedStatement = connection.prepareStatement(sql);
// Object[] parmes = new Object[1];
// parmes[0] = Integer.parseInt(id);
preparedStatement.setInt(1, id);
// rs = BaseDao.executeQuery(connection, sql, preparedStatement, parmes, rs);
rs = preparedStatement.executeQuery();
// while (rs.next()){
user = getUserByResult(rs);
// users.add(user);
// }
BaseDao.closeResource(connection, preparedStatement, rs);
}
return user;
}

浙公網安備 33010602011771號