SMBMS(超市管理项目)

  • 项目结构

image-20230707232311327

  • 数据库

image-20230707232655439

img

1. 项目搭建准备

1.1 新建Maven Web项目

1.2 配置Tomcat

1.3 测试启动

image-20230707233531008

1.4 导入依赖

1.4.1 pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!-- servlet 依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- JSP 依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!-- JSTL 依赖 -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- JSTL 实现 -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- MySQL 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>

1.4.2 web.xml

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
</web-app>

1.4.3 index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Index.jsp</title>
</head>
<style>
h1 {
text-align: center;
color: red;
}
</style>
<body>
<h1>Hello World!</h1>
</body>
</html>

1.5 构建项目结构

image-20230707233908335

1.6 编写实体类 ORM

  • 对象关系映射(Object Relational Mapping,简称ORM)- 表-类映射

1.7 编写基本公共类

1.7.1 数据库配置文件 db.properties

1
2
3
4
5
driver=com.mysql.jdbc.Driver
#在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8
url=jdbc:mysql://127.0.0.1:3306/smbms?useSSL=false&useUnicode=true&characterEncoding=utf-8
user=root
password=root

1.7.2 编写数据库的公共类 BaseDao

  • DAO(Data Access Object)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.bayyy.dao;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
private static String driver; // 数据库驱动
private static String url; // 数据库连接地址
private static String username; // 数据库用户名
private static String password; // 数据库密码

// 静态代码块, 类加载时执行
static {
Properties properties = new Properties();
// 通过类加载器加载db.properties文件
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");

try {
properties.load(is);
} catch (Exception e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
}

// 获取数据库的连接
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}

// 编写查询公共方法
public static ResultSet execute(Connection connection, String sql, Object[] params, ResultSet resultSet, PreparedStatement preparedStatement) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
// setObject占位符从1开始, 而数组下标从0开始
preparedStatement.setObject(i + 1, params[i]);
}
resultSet = preparedStatement.executeQuery();
return resultSet;
}

// 编写增删改公共方法
public static int execute(Connection connection, String sql, Object[] params, PreparedStatement preparedStatement) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
// setObject占位符从1开始, 而数组下标从0开始
preparedStatement.setObject(i + 1, params[i]);
}
return preparedStatement.executeUpdate();
}

// 释放资源
public static boolean closeResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
boolean flag = true;
if (resultSet != null) {
try {
resultSet.close();
// GC回收
resultSet = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
// GC回收
preparedStatement = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (connection != null) {
try {
connection.close();
// GC回收
connection = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
}

1.7.2 编写字符编码Filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CharacterEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse.setCharacterEncoding("UTF-8");
servletRequest.setCharacterEncoding("UTF-8");
filterChain.doFilter(servletRequest, servletResponse); // 放行: 交给下一个过滤器
}

@Override
public void destroy() {
}
}

1.8 导入静态代码

jsp、html、css、js…

2. 登录功能实现

image-20230709223919042

2.1 编写前端首页

2.2 设置首页 xml

1
2
3
4
<!-- 设置欢迎页面 -->
<welcome-file-list>
<welcome-file>./login.jsp</welcome-file>
</welcome-file-list>

2.3 编写Dao层用户接口

DAO (Data Access Object 数据访问对象)

1
2
3
4
public interface UserDao {
// 得到登录的用户
public User getLoginUser(Connection connection, String serCode) throws SQLException;
}

2.4 编写dao层接口的实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class UserDaoImpl implements UserDao {
@Override
public User getLoginUser(Connection connection, String serCode) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user = null;

if (connection != null) {
String sql = "select * from user where userCode=?";
Object[] params = {serCode};
resultSet = BaseDao.execute(connection, sql, params, resultSet, preparedStatement);
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id")); // id
user.setUserCode(resultSet.getString("userCode")); // 用户编码
user.setUserName(resultSet.getString("userName")); // 用户名称
user.setUserPassword(resultSet.getString("userPassword")); // 用户密码
user.setGender(resultSet.getInt("gender")); // 性别
user.setBirthday(resultSet.getDate("birthday")); // 出生日期
user.setPhone(resultSet.getString("phone")); // 电话
user.setAddress(resultSet.getString("address")); // 地址
user.setUserRole(resultSet.getInt("userRole")); // 用户角色
user.setCreatedBy(resultSet.getInt("createdBy")); // 创建者
user.setCreationDate(resultSet.getTimestamp("creationDate")); // 创建时间
user.setModifyBy(resultSet.getInt("modifyBy")); // 更新者
user.setModifyDate(resultSet.getTimestamp("modifyDate")); // 更新时间
}
BaseDao.closeResource(null, preparedStatement, resultSet);
return user;
}
return null;
}
}

2.5 业务层接口 UserService

1
2
3
4
public interface UserService {
// 用户登录
public User login(String userCode, String userPassword);
}

2.6 业务层实现类 UserServiceImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class UserServiceImpl implements UserService{
// 业务层都会调用dao层, 通过用户编码获取用户信息
private UserDao userDao;
public UserServiceImpl() {
userDao = new UserDaoImpl();
}

@Override
public User login(String userCode, String userPassword) {
Connection connection = null;
User user = null;

try {
connection = BaseDao.getConnection();
user = userDao.getLoginUser(connection, userCode);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
BaseDao.closeResource(connection, null, null);
}
return user;
}
}

2.7 编写LoginServlet并注册

  • .java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class LoginServlet extends HttpServlet {
// Servlet: 控制层, 调用业务层代码
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("LoginServlet--start...");
// 获取用户名和密码
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");

// 和数据库中的密码进行对比, 调用业务层
UserService userService = new UserServiceImpl();
User user = userService.login(userCode, userPassword);
if (user != null) { // 查有此人, 可以登录
// 将用户的信息放到Session中
req.getSession().setAttribute(Constants.USER_SESSION, user);
// 跳转到主页
resp.sendRedirect("jsp/frame.jsp");
} else {
// 转发回登录页面, 并提示错误信息
req.setAttribute("error", "用户名或密码不正确");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}

}
}
  • web.xml
1
2
3
4
5
6
7
8
9
<!-- Servlet: 注销 -->
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.bayyy.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>

2.8 登录拦截优化

  • SysFilter

    1. ServletRequest/ServletResponse 强转为 HttpServletRequest/HttpServletResponse

      ServletRequest 没有 getSession 方法

      ServletResponse 没有 sendRedirect 方法

      无法实现获取Session和重定向功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class SysFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse respone = (HttpServletResponse) servletResponse;

// 过滤器, 从Session中获取用户
User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);

if (user == null) { // Session失效, 用户不存在(注销或者未登录)
// 已经被移除或者注销了, 或者未登录
respone.sendRedirect("/error.jsp"); // 跳转到错误页面
} else {
filterChain.doFilter(servletRequest, servletResponse); // 放行
}
}
}
  1. xml 注册
1
2
3
4
5
6
7
8
9
<!-- Filter: 登录验证 -->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.bayyy.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>

3. 密码修改

3.1 导入前端素材

1
<li><a href="${pageContext.request.contextPath }/jsp/pwdmodify.jsp">密码修改</a></li>

3.2 项目->从底层向顶层写

1
2
graph LR
程序员 --> 前端JSP --请求--> Servlet --调用--> Service --调用--> Dao --查询--> 数据库

3.3 UserDao接口

1
2
3
4
5
6
7
public interface UserDao {
// 得到登录的用户
public User getLoginUser(Connection connection, String serCode) throws SQLException;

// 修改当前用户密码
public int updatePwd(Connection connection, int id, String password) throws SQLException;
}

3.4 UserDao接口实现类

  • UserDaoImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
public int updatePwd(Connection connection, int id, String password) throws SQLException {
PreparedStatement preparedStatement = null;
int execute = 0;

if (connection != null) {
Object prams[] = {password, id};
String sql = "update smbms_user set userPassword=? where id=?";
execute = BaseDao.execute(connection, sql, prams, preparedStatement);
BaseDao.closeResource(null, preparedStatement, null);
return 0;
}
return execute;
}

3.5 UserService层

1
2
3
4
5
6
7
public interface UserService {
// 用户登录
public User login(String userCode, String userPassword);

// 根据用户id修改密码
public boolean updatePwd(int id, String password);
}

3.6 UserServive实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public boolean updatePwd(int id, String password) {
Connection connection = null;
boolean flag = false;

// 修改密码
try {
connection = BaseDao.getConnection();
if (userDao.updatePwd(connection, id, password) > 0) {
flag = true;
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
BaseDao.closeResource(connection, null, null);
}
return flag;
}

3.7 Servlet复用,提取方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if ("savepwd".equals(method)) {
this.updatePwd(req, resp);
}
}

public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 从Session里面获取用户信息
Object userSession = req.getSession().getAttribute(Constants.USER_SESSION);

String newpassword = req.getParameter("newpassword");

boolean flag = false;

if (userSession != null && !StringUtils.isNullOrEmpty(newpassword)) {
UserService userService = new UserServiceImpl();
flag = userService.updatePwd(((User) userService).getId(), newpassword);
if (flag) {
req.setAttribute("message", "修改密码成功, 请退出, 使用新密码登录");
// 密码修改成功, 移除当前Session
req.getSession().removeAttribute(Constants.USER_SESSION);
} else {
req.setAttribute("message", "密码修改失败");
}
} else {
req.setAttribute("message", "新密码有问题");
}
req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
}

3.8 密码修改 - Ajax

3.8.1 阿里巴巴的包

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.35</version>
</dependency>

3.8.2 UserServlet 代码修改

  • 增加 pqdmodify 部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// 实现Servlet复用
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if (method.equals("savepwd")) {
this.updatePwd(req, resp);
} else if (method.equals("pwdmodify")) {
this.pwdModify(req, resp);
}
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}

// 修改密码
public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 从Session里面获取用户信息
Object userSession = req.getSession().getAttribute(Constants.USER_SESSION);

String newpassword = req.getParameter("newpassword");

boolean flag = false;

if (userSession != null && !StringUtils.isNullOrEmpty(newpassword)) {
UserService userService = new UserServiceImpl();
flag = userService.updatePwd(((User) userSession).getId(), newpassword);
if (flag) {
req.setAttribute("message", "修改密码成功, 请退出, 使用新密码登录");
// 密码修改成功, 移除当前Session
req.getSession().removeAttribute(Constants.USER_SESSION);
} else {
req.setAttribute("message", "密码修改失败");
}
} else {
req.setAttribute("message", "新密码有问题");
}
req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
}

// 验证旧密码
public void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
// 1. 从Session里面获取用户信息
Object userSession = req.getSession().getAttribute(Constants.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");

// 使用 Map
HashMap<String, String> resultMap = new HashMap<String, String>();
if (userSession == null) { // Session 过期或不存在
resultMap.put("result", "sessionerror");
} else if (StringUtils.isNullOrEmpty(oldpassword)) { // 旧密码输入为空
resultMap.put("result", "error");
} else {
String userPassword = ((User) userSession).getUserPassword();
if (oldpassword.equals(userPassword)) { // 旧密码输入正确
resultMap.put("result", "true");
} else { // 旧密码输入错误
resultMap.put("result", "false");
}
}

try {
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
// JSONArray 阿里巴巴的 JSON 工具类, 转换格式
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

4. 用户管理实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
graph LR
id1(客户) --发起请求--> id2["Servlet\n1.处理请求\n2.调用业务\n3.返回页面"]
id2 --返回前端页面--> id1
id2 --> id3(用户列表)
id3 --> id6[Service]
id6 --> id9[Dao]
id2 --> id4(角色列表)
id4 --> id7[Service]
id7 --> id10[Dao]
id2 --> id5["分页\npageSize(固定的)\n总数(数据库查)"]
id5 --> id8[Service]
id8 --> id11[Dao]
id9 --> id12{数据库}
id10 --> id12
id11 --> id12

4.1 导入前端界面和相关方法

4.1.1 导入分页工具类

  • PageSupport.java

4.1.2 用户列表页面导入

  • userlist.jap
  • rollpage.jsp

4.2 获取用户数量

4.2.1 UserDao接口

1
2
// 查询用户名或者角色查询用户总数
public int getUserCount(Connection connection, String userName, int userRole) throws SQLException;

4.2.2 Dao接口实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 查询用户名或者角色查询用户总数
@Override
public int getUserCount(Connection connection, String userName, int userRole) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
int count = 0;

if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole=r.id");
// 存放参数
ArrayList<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" and u.userName like ?");
list.add("%" + userName + "%");
}
if (userRole != 0) {
sql.append(" and u.userRole=?");
list.add(userRole);
}
Object[] objects = list.toArray();
System.out.println("UserDaoImpl->getUserCount:" + sql.toString()); // 输出最终的sql语句
System.out.println("UserDaoImpl->getUserCount:" + list.toString()); // 输出最终的参数
resultSet = BaseDao.execute(connection, sql.toString(), objects, resultSet, preparedStatement);
if (resultSet.next()) {
count = resultSet.getInt("count");
}
BaseDao.closeResource(null, preparedStatement, resultSet);
}
return count;
}

4.2.3 UserService 接口

1
2
// 查询记录数
public int getUserCount(String userName, int userRole);

4.2.4 Service接口实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Override
public int getUserCount(String userName, int userRole) {
Connection connection = null;
int count = 0;

try {
connection = BaseDao.getConnection();
count = userDao.getUserCount(connection, userName, userRole);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
BaseDao.closeResource(connection, null, null);
}
return count;
}

4.3 获取用户列表

4.3.1 UserDao接口

1
2
// 获取用户列表(通过条件查询-userList)
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws SQLException;

4.3.2 Dao接口实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, 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 u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole=r.id");
ArrayList<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" and u.userName like ?");
list.add("%" + userName + "%");
}
if (userRole != 0) {
sql.append(" and u.userRole=?");
list.add(userRole);
}
// 在数据库中,分页使用limit startIndex,pageSize; 总数
sql.append(" order by creationDate DESC limit ?,?");
currentPageNo = (currentPageNo - 1) * pageSize;
list.add(currentPageNo);
list.add(pageSize);

Object[] params = list.toArray();
System.out.println("UserDaoImpl->getUserList:" + sql.toString()); // 输出最终的sql语句
resultSet = BaseDao.execute(connection, sql.toString(), params, resultSet, preparedStatement);

while (resultSet.next()) {
User _user = new User();
_user.setId(resultSet.getInt("id")); // 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("userRoleName"));
userList.add(_user);
}
BaseDao.closeResource(null, preparedStatement, resultSet);
}
return userList;
}

4.3.3 UserService接口

1
2
// 查询用户列表
public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize);

4.3.4 Service接口实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize) {
Connection connection = null;
List<User> userList = null;
try {
connection = BaseDao.getConnection();
userList = userDao.getUserList(connection, userName, userRole, currentPageNo, pageSize);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
BaseDao.closeResource(connection, null, null);
}
return userList;
}

4.4 获取角色操作

  • 为了职责统一,将角色操作单独放在一个包中,和 enity(pojo) 类对应

4.4.1 RoleDao

1
2
3
4
5
public interface RoleDao {
// 获取角色列表
public List<Role> getRoleList(Connection connection) throws SQLException;

}

4.4.2 RoleDaoIpml实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class RoleDaoImpl implements RoleDao {
// 获取角色列表
@Override
public List<Role> getRoleList(Connection connection) throws SQLException {
ArrayList<Role> roleList = new ArrayList<Role>();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
if (connection != null) {
String sql = "select * from smbms_role";
Object[] params = {};
resultSet = BaseDao.execute(connection, sql, params, resultSet, preparedStatement);
while (resultSet.next()) {
Role _role = new Role();
_role.setId(resultSet.getInt("id"));
_role.setRoleCode(resultSet.getString("roleCode"));
_role.setRoleName(resultSet.getString("roleName"));
roleList.add(_role);
}
BaseDao.closeResource(null, preparedStatement, resultSet);
}
return roleList;
}
}

4.4.3 RoleService

1
2
3
4
public interface RoleService {
// 获取角色列表
public List<Role> getRoleList() throws SQLException;
}

4.4.4 RoleServiceImpl实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class RoleServiceImpl implements RoleService {
// 引入Dao
private RoleDao roleDao;
public RoleServiceImpl() {
roleDao = new RoleDaoImpl();
}
@Override
public List<Role> getRoleList(){
Connection connection = null;
List<Role> roleList = null;
try {
connection = BaseDao.getConnection();
roleList = roleDao.getRoleList(connection);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
BaseDao.closeResource(connection, null, null);
}
return roleList;
}
}

4.5 用户显示 - UserServlet

  • 获取用户前端的数据(查询)
  • 判断请求是否需要执行,看参数的值判断
  • 为了实现分页,需要计算出当前页面和总页面,页面大小…
  • 用户列表展示
  • 返回前端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// 查询用户列表
public void query(HttpServletRequest req, HttpServletResponse resp) {
// 查询用户列表

// 从前端获取数据
String queryUserName = req.getParameter("queryname");
String temp = req.getParameter("queryUserRole");
String pageIndex = req.getParameter("pageIndex");
int queryUserRole = 0;

// 获取用户列表
UserService userService = new UserServiceImpl();
List<User> userList = null;

// 第一次走这个请求, 一定是第一页, 页面大小固定的
int pageSize = 5;
int currentPageNo = 1;

if (queryUserName == null) {
queryUserName = "";
}
if (temp != null && !temp.equals("")) { // 前端获取数据出错
queryUserRole = Integer.parseInt(temp);
}
if (pageIndex != null) {
currentPageNo = Integer.parseInt(pageIndex);
}
System.out.println("queryUserName servlet: " + queryUserName);
System.out.println("queryUserRole servlet: " + queryUserRole);

// 获取用户总数(分页: 上一页, 下一页)
int totalCount = userService.getUserCount(queryUserName, queryUserRole);
// 总页数支持
PageSupport pageSupport = new PageSupport();
pageSupport.setPageSize(pageSize); // 设置页面容量
pageSupport.setTotalCount(totalCount); // 总数量(表)
pageSupport.setCurrentPageNo(currentPageNo); // 当前页码

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 = 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);

// 返回前端
try {
req.getRequestDispatcher("userlist.jsp").forward(req, resp);
} catch (ServletException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

4.6 小黄鸭调试法