【JavaWeb】JavaWeb从入门到实战(14)
前言:
本文内容:smbms管理系统项目实战
推荐免费JavaWeb入门到实战视频:【狂神说Java】JavaWeb入门到实战_哔哩哔哩_bilibili
smbms项目搭建
结构图
Smbms.sql
1 | -- 创建smbms数据库 |
表结构
项目如何搭建,是否使用Maven?依赖:jar包
项目搭建
-
搭建一个Maven项目
-
创建Tomcat创建的项目可以运行
-
导入需要的Jar包
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<!-- 导入项目需要依赖-->
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies> -
创建项目包结构
-
编写实体类
ORM映射:表—类映射
-
编写基础公共类
数据库配置文件
db.properties
1
2
3
4driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useSSL=false&serverTimezone=UTC
username=root
password=123456编写数据库公共类
BaseDao.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
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
99
100package com.jokerdig.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* @author Joker大雄
* @data 2022/4/13 - 21:01
**/
// 陈宗座数据库公共类
public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;
// 静态代码块 类加载就初始化
static {
Properties pro = new Properties();
// 通过类加载器读取行响应的资源
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver = pro.getProperty("driver");
url = pro.getProperty("url");
username = pro.getProperty("username");
password = pro.getProperty("password");
}
// 获取数据库连接
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
// 编写查询公共类
public static ResultSet execute(Connection conn,PreparedStatement ps,ResultSet re,String sql,Object[] para) throws SQLException {
ps = conn.prepareStatement(sql);
for (int i = 0; i < para.length; i++) {
// setObject 占位符从1开始
ps.setObject(i+1,para[i]);
}
re = ps.executeQuery();
return re;
}
// 编写增删改公共方法
public static int execute(Connection conn,PreparedStatement ps,String sql,Object[] para) throws SQLException {
ps = conn.prepareStatement(sql);
for (int i = 0; i < para.length; i++) {
// setObject 占位符从1开始
ps.setObject(i+1,para[i]);
}
int back = ps.executeUpdate();
return back;
}
// 释放资源
public static boolean closeResource(Connection conn,PreparedStatement ps,ResultSet re){
boolean flag = true;
if(re!=null){
try {
re.close();
re=null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag=false;
}
}
if(ps!=null){
try {
ps.close();
ps=null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag=false;
}
}
if(conn!=null){
try {
conn.close();
conn=null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag=false;
}
}
return flag;
}
}编写字符编码过滤器
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
31package com.jokerdig.filter;
import javax.servlet.*;
import java.io.IOException;
/**
* @author Joker大雄
* @data 2022/4/13 - 21:24
**/
public class CharacterEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 编码过滤器
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html; charset=utf-8");
// Chain
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
}
}web.xml
配置1
2
3
4
5
6
7
8
9<!--编码过滤器注册-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.jokerdig.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> -
导入静态资源
静态资源下载 访问密码:joker
-
项目基本架构搭建完成
smbms登录流程实现
实现流程图
-
导入前端页面
-
设置首页
1
2
3
4
5
6
7
8<!--设置欢迎页面-->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!-- session默认会过期-->
<session-config>
<session-timeout>30</session-timeout>
</session-config> -
编写Dao层用户登录的接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package com.jokerdig.dao.user;
import com.jokerdig.pojo.User;
import java.sql.Connection;
/**
* @author Joker大雄
* @data 2022/4/14 - 16:37
**/
public interface UserDao {
// 得到要登录的用户
public User getLoginUser(Connection conn,String userCode,String userPassword);
} -
编写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
43
44
45
46
47
48
49
50
51
52
53
54
55package com.jokerdig.dao.user;
import com.jokerdig.dao.BaseDao;
import com.jokerdig.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Joker大雄
* @data 2022/4/14 - 16:39
**/
public class UserDaoImpl implements UserDao{
// 用户登录
public User getLoginUser(Connection conn, String userCode,String userPassword) {
PreparedStatement ps =null;
ResultSet re = null;
User user = null;
if(conn!=null){
String sql ="select * from smbms_user where userCode=? and userPassword=?";
Object [] para = {userCode,userPassword};
try {
re=BaseDao.execute(conn,ps,re,sql,para);
if(re.next()){
user = new User();
user.setId(re.getInt("id"));
user.setUserCode(re.getString("userCode"));
user.setUserName(re.getString("userName"));
user.setUserPassword(re.getString("userPassword"));
user.setGender(re.getInt("gender"));
user.setBirthday(re.getDate("birthday"));
user.setPhone(re.getString("phone"));
user.setAddress(re.getString("address"));
user.setUserRole(re.getInt("userRole"));
user.setCreatedBy(re.getInt("createdBy"));
user.setCreationDate(re.getTimestamp("creationDate"));
user.setModifyBy(re.getInt("modifyBy"));
user.setModifyDate(re.getTimestamp("modifyDate"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally{
//释放资源
BaseDao.closeResource(null,ps,re);
}
}
return user;
}
} -
业务层接口
1
2
3
4
5
6
7
8
9
10
11
12package com.jokerdig.service.user;
import com.jokerdig.pojo.User;
/**
* @author Joker大雄
* @data 2022/4/14 - 17:00
**/
public interface UserService {
//用户登录
public User login(String userCode,String password);
} -
业务层实现类
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
36package com.jokerdig.service.user;
import com.jokerdig.dao.BaseDao;
import com.jokerdig.dao.user.UserDao;
import com.jokerdig.pojo.User;
import java.sql.Connection;
/**
* @author Joker大雄
* @data 2022/4/14 - 17:00
**/
public class UserServiceImpl implements UserService{
// 引入Dao层
private UserDao userDao;
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
// 登录业务实现层
public User login(String userCode, String password) {
Connection conn = null;
User loginUser = null;
conn= BaseDao.getConnection();
// 通过业务层调用Dao
loginUser = userDao.getLoginUser(conn, userCode,password);
BaseDao.closeResource(conn,null,null);
return loginUser;
}
} -
编写登录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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52package com.jokerdig.servlet.user;
import com.jokerdig.pojo.User;
import com.jokerdig.service.user.UserServiceImpl;
import com.jokerdig.until.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Joker大雄
* @data 2022/4/14 - 17:18
**/
public class LoginServlet extends HttpServlet {
// 调用Service层
// 登录
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("LoginServlet..in..");
// 获取用户名和密码
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");
// 和数据库进行对比
UserServiceImpl userService = new UserServiceImpl();
User back = userService.login(userCode, userPassword);
if(back!=null){
// 登录成功
req.getSession().setAttribute(Constants.USER_SESSION,back);
resp.sendRedirect("../jsp/frame.jsp");
}else {
// 登录失败
req.setAttribute("error","用户名或密码不正确");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}创建一个常量工具类
1
2
3
4
5
6
7
8
9
10package com.jokerdig.until;
/**
* @author Joker大雄
* @data 2022/4/14 - 17:24
**/
// 常量工具列
public class Constants {
public final static String USER_SESSION = "userSession";
} -
在web.xml注册登录Servlet
1
2
3
4
5
6
7
8
9<!-- 登录Servlet-->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.jokerdig.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping> -
登录功能实现
smbms注销及权限过滤
注销功能
实现思路:移除Session,返回登录页面
LogoutServlet.java
1 | package com.jokerdig.servlet.user; |
web.xml
配置
1 | <!-- 注销登录 --> |
登录拦截优化
通过编写滤器器,并注册以实现未登录拦截
SysFilter.java
1 | package com.jokerdig.filter; |
web.xml
配置
1 | <!-- 登录拦截过滤器--> |
smbms密码修改实现
-
导入前端素材
-
写项目建议从底层开始写
-
编写Dao层
UserDao.java
接口1
2// 修改用户密码
public int updatePwd(Connection conn,int id, String password);UserDaoImpl.java实现类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20// 修改密码
public int updatePwd(Connection conn, int id, String password) {
PreparedStatement ps =null;
int back=0;
if(conn!=null){
String sql ="update smbms_user set userPassword=? where id=?";
Object [] para = {password,id};
try {
back=BaseDao.execute(conn,ps,sql,para);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally{
//释放资源
BaseDao.closeResource(null,ps,null);
}
}
return back;
} -
编写Service层
UserService.java
接口1
2// 修改用户密码
public boolean updatePwd(int id, String password);UserServiceImpl.java
实现类1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// 修改用户面膜业务实现层
public boolean updatePwd(int id, String password) {
Connection conn = null;
boolean flag = false;
// 获取连接
conn = BaseDao.getConnection();
// 通过调用Dao 修改密码
int back = userDao.updatePwd(conn, id, password);
if(back>0){
flag = true;
}
BaseDao.closeResource(conn,null,null);
return flag;
} -
编写Servlet层
添加常量工具类
1
public final static String MESSAGE="message";
UserServlet.java
(注意:这里没有实现旧密码的Ajax验证,在下节课实现)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
61package com.jokerdig.servlet.user;
import com.jokerdig.pojo.User;
import com.jokerdig.service.user.UserService;
import com.jokerdig.service.user.UserServiceImpl;
import com.jokerdig.until.Constants;
import com.mysql.cj.util.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Joker大雄
* @data 2022/4/15 - 14:33
**/
public class UserServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if(method.equals("savepwd")&&method!=null){
// 修改密码
this.updatePwd(req,resp);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
// 实现Servlet复用
// 用户修改密码
public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 从session中获取用户id
Object ob = req.getSession().getAttribute(Constants.USER_SESSION);
// 从页面拿到新密码
String newPwd = req.getParameter("newpassword");
// 判断用户是否登录且新密码不为空
if(ob!=null && !StringUtils.isNullOrEmpty(newPwd)){
UserService userService = new UserServiceImpl();
// 把用户id和新密码赋值
boolean flag = false;
flag = userService.updatePwd(((User) ob).getId(), newPwd);
if(flag){
// 修改成功
req.setAttribute(Constants.MESSAGE,"密码修改成功,请重新登录");
// 移除session 用户使用新密码登录
req.getSession().removeAttribute(Constants.USER_SESSION);
}else {
// 修改失败
req.setAttribute(Constants.MESSAGE,"密码修改失败");
}
}else {
req.setAttribute(Constants.MESSAGE,"密码输入有误");
}
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
}
}web.xml
配置1
2
3
4
5
6
7
8
9<!-- UserServlet-->
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.jokerdig.servlet.user.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/jsp/user.do</url-pattern>
</servlet-mapping> -
密码修改完成(通过Ajax验证旧密码在下节课实现)
smbms通过Ajax验证旧密码
-
阿里巴巴的fastjson
1
2
3
4
5
6<!-- fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency> -
编写验证的Servlet
UserServlet.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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if(method.equals("savepwd")&&method!=null){
// 修改密码
this.updatePwd(req,resp);
}else if(method.equals("pwdmodify")&&method!=null){
// 验证旧密码
this.pwdModify(req,resp);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
// 验证旧密码 通过ajax
public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
Object ob = req.getSession().getAttribute(Constants.USER_SESSION);
// 从ajax请求中拿到旧密码
String oldPwd = req.getParameter("oldpassword");
// 使用万能的map
Map<String,String> resultMap = new HashMap<String,String>();
if(ob==null){
// session过期
resultMap.put("result","sessionerror");
}else if(StringUtils.isNullOrEmpty(oldPwd)){
// 密码为空
resultMap.put("result","error");
}else {
String userPassword = ((User) ob).getUserPassword();//session中用户的密码
if(oldPwd.equals(userPassword)){
resultMap.put("result","true");
}else {
resultMap.put("result","false");
}
}
try {
resp.setContentType("application/json");
PrintWriter wt = resp.getWriter();
// JSONArray 阿里巴巴JSON工具类
wt.write(JSONArray.toJSONString(resultMap));
wt.flush();
wt.close();
} catch (IOException e) {
e.printStackTrace();
}
} -
实现旧密码验证
smbms用户管理查询分页
实现流程图
实现步骤
-
导入分页的工具类
工具类下载 密码:joker
-
用户列表页面导入
-
编写用户显示、分页及查询相关功能
UserDao.java
1
2
3
4// 获取用户总数
public int getUserCount(Connection conn,String username,int userRole);
// 获取用户列表
public List<User> getUserList(Connection conn,String userName,int userRole,int currentPageNo,int pageSize);UserDaoImpl.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
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
99// 查询用户总人数
public int getUserCount(Connection conn, String username, int userRole) {
PreparedStatement ps =null;
ResultSet re = null;
int count = 0;
if(conn!=null) {
StringBuffer sql = new StringBuffer();
sql.append("select count(1) as count from smbms_user su, smbms_role sr where su.userRole = sr.id");
ArrayList<Object> list = new ArrayList<>();
if (!StringUtils.isNullOrEmpty(username)) {
// username不为空
sql.append(" and su.userName like ?");
list.add("%" + username + "%");
}
if (userRole > 0) {
// userRole不为空
sql.append(" and su.userRole = ?");
list.add(userRole);
}
// 把list转换为数组
Object[] arr = list.toArray();
// 调试sql语句是否正常
System.out.println("UserDaoImpl->getUserCount:" + sql.toString());
try {
re = BaseDao.execute(conn, ps, re, sql.toString(), arr);
if (re.next()) {
// 取出总人数
count = re.getInt("count");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.closeResource(null, ps, re);
}
}
return count;
}
// 查询用户列表
public List<User> getUserList(Connection conn, String userName, int userRole, int currentPageNo, int pageSize) {
PreparedStatement ps =null;
ResultSet re = null;
List<User> userList = new ArrayList<>();
if(conn!=null){
StringBuffer sql = new StringBuffer();
sql.append("select su.*,sr.roleName as userRoleName from smbms_user su,smbms_role sr where su.userRole = sr.id");
List<Object> list = new ArrayList<>();
if (!StringUtils.isNullOrEmpty(userName)) {
// username不为空
sql.append(" and su.userName like ?");
list.add("%" + userName + "%");
}
if (userRole > 0) {
// userRole不为空
sql.append(" and su.userRole = ?");
list.add(userRole);
}
/*
在数据库中 分页使用 limit startIndex,pageSize 总数
当前页 (当前页-1)*页面大小
0,5 0 1 2 3 4
5,5 5 6 7 8 9
....
*/
sql.append(" order by creationDate DESC limit ?,?");
// 分页计算
currentPageNo = (currentPageNo-1)*pageSize;
list.add(currentPageNo);
list.add(pageSize);
Object[] para = list.toArray();
System.out.println("getUserListSQL->"+sql.toString());
try {
re=BaseDao.execute(conn,ps,re,sql.toString(),para);
while(re.next()){
User user = new User();
user.setId(re.getInt("id"));
user.setUserCode(re.getString("userCode"));
user.setUserName(re.getString("userName"));
user.setGender(re.getInt("gender"));
user.setBirthday(re.getDate("birthday"));
user.setUserRole(re.getInt("userRole"));
user.setUserRoleName(re.getString("userRoleName"));
userList.add(user);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally{
//释放资源
BaseDao.closeResource(null,ps,re);
}
}
return userList;
}UserService.java
1
2
3
4// 获取用户总数
public int getUserCount(String username,int userRole);
// 获取用户列表
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize);UserServiceImpl.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// 查询用户人数
public int getUserCount(String username, int userRole) {
Connection conn = null;
// 获取连接
conn = BaseDao.getConnection();
// 通过调用Dao 修改密码
int count = userDao.getUserCount(conn, username, userRole);
BaseDao.closeResource(conn,null,null);
return count;
}
// 获取用户列表
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
Connection conn = null;
List<User> list = new ArrayList<>();
// 获取连接
conn = BaseDao.getConnection();
// 通过调用Dao 获取用户列表
list = userDao.getUserList(conn,queryUserName,queryUserRole,currentPageNo,pageSize);
BaseDao.closeResource(conn,null,null);
return list;
}UserServlet.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
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// 用户显示
public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 查询用户列表
// 从前端获取数据
String queryUserName = req.getParameter("queryname");
String temp = req.getParameter("queryUserRole");
String pageIndex = req.getParameter("pageIndex");
int queryUserRole = 0;
List<User> userList = null;
List<Role> roleList = null;
// 获取用户列表
UserServiceImpl userService = new UserServiceImpl();
// 第一次请求默认是第一页
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);
}
// 获取用户总数
int totalCount = userService.getUserCount(queryUserName, queryUserRole);
// 总页数
PageSupport pageSupport = new PageSupport();
pageSupport.setCurrentPageNo(currentPageNo);
pageSupport.setPageSize(pageSize);
pageSupport.setTotalCount(totalCount);
// 控制首页和尾页
int totalPageCount = pageSupport.getTotalPageCount();// 获取总页数
if(totalPageCount<1){
currentPageNo = 1;
}else if(currentPageNo>totalPageCount){//尾页
currentPageNo = totalPageCount;
}
// 获取用户列表展示
userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
req.setAttribute("userList",userList);
// 获取角色列表
RoleService roleService = new RoleServiceImpl();
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);
} -
编写角色相关功能、
RoleDao.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package com.jokerdig.dao.role;
import com.jokerdig.pojo.Role;
import java.sql.Connection;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/18 - 14:07
**/
public interface RoleDao {
// 获取角色列表
public List<Role> getRoleList(Connection conn);
}RoleDaoImpl.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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47package com.jokerdig.dao.role;
import com.jokerdig.dao.BaseDao;
import com.jokerdig.pojo.Role;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/18 - 14:10
**/
public class RoleDaoImpl implements RoleDao{
// 获取角色列表
public List<Role> getRoleList(Connection conn) {
PreparedStatement ps =null;
ResultSet re = null;
List<Role> list = new ArrayList<>();
if(conn!=null){
String sql = "select * from smbms_role";
Object[] para = {};
try {
re = BaseDao.execute(conn, ps, re, sql, para);
while(re.next()){
Role role = new Role();
role.setId(re.getInt("id"));
role.setRoleName(re.getString("roleName"));
role.setRoleCode(re.getString("roleCode"));
list.add(role);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally{
//释放资源
BaseDao.closeResource(null,ps,re);
}
}
return list;
}
}RoleService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package com.jokerdig.service.role;
import com.jokerdig.pojo.Role;
import java.sql.Connection;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/18 - 14:15
**/
public interface RoleService {
// 获取角色列表
public List<Role> getRoleList();
}RoleServiceImpl.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
26
27
28
29
30
31
32
33
34
35
36package com.jokerdig.service.role;
import com.jokerdig.dao.BaseDao;
import com.jokerdig.dao.role.RoleDao;
import com.jokerdig.dao.role.RoleDaoImpl;
import com.jokerdig.pojo.Role;
import java.sql.Connection;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/18 - 14:15
**/
public class RoleServiceImpl implements RoleService {
// 引入dao
private RoleDao roleDao;
public RoleServiceImpl() {
roleDao = new RoleDaoImpl();
}
// 获取角色信息
public List<Role> getRoleList() {
Connection conn = null;
List<Role> roleList = null;
conn = BaseDao.getConnection();
roleList = roleDao.getRoleList(conn);
BaseDao.closeResource(conn,null,null);
return roleList;
}
} -
用户管理模块实现
smbms用户管理增删改
增删改实现思路
实现步骤
-
编写用户增删改相关功能
UserDao.java
1
2
3
4
5
6
7
8// 添加用户
public int add(Connection conn,User user);
// 删除用户
public int deleteUserById(Connection conn,Integer delId);
// 获取修改用户
public User getUserById(Connection conn,String id);
// 修改用户
public int modify(Connection conn,User user);UserDaoImpl.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
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
99
100
101// 添加用户
public int add(Connection conn, User user) {
PreparedStatement ps = null;
int back = 0;
if(conn!=null){
String sql = "insert into smbms_user (userCode,userName,userPassword,"+
"userRole,gender,birthday,phone,address,creationDate,createdBy)"+
"values(?,?,?,?,?,?,?,?,?,?)";
Object[] para = {user.getUserCode(), user.getUserName(), user.getUserPassword(),
user.getUserRole(), user.getGender(), user.getBirthday(),
user.getPhone(), user.getAddress(), user.getCreationDate(), user.getCreatedBy()};
try {
back = BaseDao.execute(conn,ps,sql,para);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally{
BaseDao.closeResource(null,ps,null);
}
}
return back;
}
// 删除用户
public int deleteUserById(Connection conn, Integer delId) {
PreparedStatement ps = null;
int back = 0;
if(conn!=null){
String sql = "delete from smbms_user where id=?";
Object[] para = {delId};
try {
back = BaseDao.execute(conn,ps,sql,para);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally{
BaseDao.closeResource(null,ps,null);
}
}
return back;
}
// 获取修改用户
public User getUserById(Connection conn, String id) {
PreparedStatement ps =null;
ResultSet re = null;
User user = null;
if(conn!=null) {
conn = BaseDao.getConnection();
String sql = "select su.*,sr.roleName as userRoleName from smbms_user su,smbms_role sr where su.id=? and su.userRole = sr.id";
Object[] para = {id};
try {
re=BaseDao.execute(conn,ps,re,sql,para);
while(re.next()){
user = new User();
user.setId(re.getInt("id"));
user.setUserCode(re.getString("userCode"));
user.setUserName(re.getString("userName"));
user.setUserPassword(re.getString("userPassword"));
user.setGender(re.getInt("gender"));
user.setBirthday(re.getDate("birthday"));
user.setPhone(re.getString("phone"));
user.setAddress(re.getString("address"));
user.setUserRole(re.getInt("userRole"));
user.setCreatedBy(re.getInt("createdBy"));
user.setCreationDate(re.getTimestamp("creationDate"));
user.setModifyBy(re.getInt("modifyBy"));
user.setModifyDate(re.getTimestamp("modifyDate"));
user.setUserRoleName(re.getString("userRoleName"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally{
//释放资源
BaseDao.closeResource(null,ps,re);
}
}
return user;
}
// 修改用户
public int modify(Connection conn, User user) {
int back = 0;
PreparedStatement pstm = null;
if (null != conn) {
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()};
try {
back = BaseDao.execute(conn, pstm, sql, params);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
BaseDao.closeResource(null, pstm, null);
}
return back;
}UserService.java
1
2
3
4
5
6
7
8
9
10// 添加用户
public boolean add(User user);
// 删除用户
public boolean deleteUserById(Integer delId);
// 获取要求改的用户
public User getUserById(String id);
// 修改用户
public boolean modify(User user);
// 获取用户编码
public User selectUserCodeExist(HttpServletRequest req , String userCode);UserServiceImpl.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127// 添加用户
public boolean add(User user) {
boolean flag = false;
Connection conn = null;
try {
conn = BaseDao.getConnection();
conn.setAutoCommit(false);//关闭自动提交
int back = userDao.add(conn,user);
System.out.println(back+"返回值");
if(back>0){
flag = true;
conn.commit();
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
// 失败后数据回滚
System.out.println("数据回滚");
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}finally{
// 释放资源
BaseDao.closeResource(conn,null,null);
}
return flag;
}
// 删除用户
public boolean deleteUserById(Integer id) {
Connection conn = null;
boolean flag = false;
try {
conn = BaseDao.getConnection();
conn.setAutoCommit(false);//关闭自动提交
if(userDao.deleteUserById(conn,id)>0){
System.out.println("删除成功");
flag = true;
conn.commit();
}else{
System.out.println("删除失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
// 失败后数据回滚
System.out.println("数据回滚");
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}finally{
// 释放资源
BaseDao.closeResource(conn,null,null);
}
return flag;
}
// 获取要修改的用户
public User getUserById(String id) {
User user = null;
Connection conn = null;
try {
conn = BaseDao.getConnection();
user = userDao.getUserById(conn,id);
} catch (Exception e) {
e.printStackTrace();
user = null;
}finally{
BaseDao.closeResource(conn,null,null);
}
return user;
}
//修改用户
public boolean modify(User user) {
boolean flag = false;
Connection conn = null;
try {
conn = BaseDao.getConnection();
conn.setAutoCommit(false);//关闭自动提交
int back = userDao.modify(conn,user);
if(back>0){
flag = true;
conn.commit();
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
// 失败后数据回滚
System.out.println("数据回滚");
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}finally{
// 释放资源
BaseDao.closeResource(conn,null,null);
}
return flag;
}
// 获取用户编码
public User selectUserCodeExist( HttpServletRequest req ,String userCode) {
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
user = userDao.getLoginUser(connection, userCode, ((User) req.getSession().getAttribute(Constants.USER_SESSION)).getUserPassword());
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return user;
}UserServlet.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363package com.jokerdig.servlet.user;
import com.alibaba.fastjson.JSONArray;
import com.jokerdig.pojo.Role;
import com.jokerdig.pojo.User;
import com.jokerdig.service.role.RoleService;
import com.jokerdig.service.role.RoleServiceImpl;
import com.jokerdig.service.user.UserService;
import com.jokerdig.service.user.UserServiceImpl;
import com.jokerdig.until.Constants;
import com.jokerdig.until.PageSupport;
import com.mysql.cj.util.StringUtils;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Joker大雄
* @data 2022/4/15 - 14:33
**/
public class UserServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if(method.equals("savepwd")&&method!=null){
// 修改密码
this.updatePwd(req,resp);
}else if(method.equals("pwdmodify")&&method!=null){
// 验证旧密码
this.pwdModify(req,resp);
}else if(method.equals("query")&&method!=null){
// 用户显示
this.query(req,resp);
}else if(method.equals("add")&& method!=null){
// 添加用户
this.add(req,resp);
}else if(method.equals("deluser")&&method!=null){
//删除用户
this.delUser(req,resp);
}else if(method.equals("modify")&&method!=null){
// 获取要修改的用户
this.getUserById(req,resp,"usermodify.jsp");
}else if(method.equals("modifyexe")&&method!=null){
//修改用户
this.modify(req,resp);
} else if (method != null && method.equals("getrolelist")) {
// 获取角色列表
this.getRoleList(req, resp);
}else if (method != null && method.equals("view")) {
// 显示用户信息
this.getUserById(req, resp, "userview.jsp");
} else if (method != null && method.equals("ucexist")) {
// 验证用户编码
this.userCodeExist(req, resp);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
// 实现Servlet复用
// 用户修改密码
public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 从session中获取用户id
Object ob = req.getSession().getAttribute(Constants.USER_SESSION);
// 从页面拿到新密码
String newPwd = req.getParameter("newpassword");
// 判断用户是否登录且新密码不为空
if(ob!=null && !StringUtils.isNullOrEmpty(newPwd)){
UserService userService = new UserServiceImpl();
// 把用户id和新密码赋值
boolean flag = false;
flag = userService.updatePwd(((User) ob).getId(), newPwd);
if(flag){
// 修改成功
req.setAttribute(Constants.MESSAGE,"密码修改成功,请重新登录");
// 移除session 用户使用新密码登录
req.getSession().removeAttribute(Constants.USER_SESSION);
}else {
// 修改失败
req.setAttribute(Constants.MESSAGE,"密码修改失败");
}
}else {
req.setAttribute(Constants.MESSAGE,"密码输入有误");
}
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
}
// 验证旧密码 通过ajax
public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
Object ob = req.getSession().getAttribute(Constants.USER_SESSION);
// 从ajax请求中拿到旧密码
String oldPwd = req.getParameter("oldpassword");
// 使用万能的map
Map<String,String> resultMap = new HashMap<String,String>();
if(ob==null){
// session过期
resultMap.put("result","sessionerror");
}else if(StringUtils.isNullOrEmpty(oldPwd)){
// 密码为空
resultMap.put("result","error");
}else {
String userPassword = ((User) ob).getUserPassword();//session中用户的密码
if(oldPwd.equals(userPassword)){
resultMap.put("result","true");
}else {
resultMap.put("result","false");
}
}
try {
resp.setContentType("application/json");
PrintWriter wt = resp.getWriter();
// JSONArray 阿里巴巴JSON工具类
wt.write(JSONArray.toJSONString(resultMap));
wt.flush();
wt.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 用户显示
public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 查询用户列表
// 从前端获取数据
String queryUserName = req.getParameter("queryname");
String temp = req.getParameter("queryUserRole");
String pageIndex = req.getParameter("pageIndex");
int queryUserRole = 0;
List<User> userList = null;
List<Role> roleList = null;
// 获取用户列表
UserServiceImpl userService = new UserServiceImpl();
// 第一次请求默认是第一页
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);
}
// 获取用户总数
int totalCount = userService.getUserCount(queryUserName, queryUserRole);
// 总页数
PageSupport pageSupport = new PageSupport();
pageSupport.setCurrentPageNo(currentPageNo);
pageSupport.setPageSize(pageSize);
pageSupport.setTotalCount(totalCount);
// 控制首页和尾页
int totalPageCount = pageSupport.getTotalPageCount();// 获取总页数
if(totalPageCount<1){
currentPageNo = 1;
}else if(currentPageNo>totalPageCount){//尾页
currentPageNo = totalPageCount;
}
// 获取用户列表展示
userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
req.setAttribute("userList",userList);
// 获取角色列表
RoleService roleService = new RoleServiceImpl();
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 add(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");
User user = new User();
user.setUserCode(userCode);
user.setUserName(userName);
user.setUserPassword(userPassword);
user.setAddress(address);
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
user.setGender(Integer.valueOf(gender));
user.setPhone(phone);
user.setUserRole(Integer.valueOf(userRole));
user.setCreationDate(new Date());
user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
UserService userService = new UserServiceImpl();
// 调用前端请求
try {
if(userService.add(user)){
resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
}else {
req.getRequestDispatcher("useradd.jsp").forward(req,resp);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
// 删除用户
public void delUser(HttpServletRequest req,HttpServletResponse resp){
String id = req.getParameter("uid");
Integer delId = 0;
try {
delId = Integer.parseInt(id);
} catch (NumberFormatException e) {
e.printStackTrace();
delId = 0;
}
HashMap<String,String>resultMap = new HashMap<>();
if(delId <=0){
resultMap.put("delResult","notexist");
}else {
UserService userService = new UserServiceImpl();
if(userService.deleteUserById(delId)){
resultMap.put("delResult","true");
}else{
resultMap.put("delResult","false");
}
}
// 把resultMap转换未JSON
resp.setContentType("application/json");
try {
PrintWriter out = resp.getWriter();
out.write(JSONArray.toJSONString(resultMap));
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 获取要修改的用户
public void getUserById(HttpServletRequest req,HttpServletResponse resp,String url){
String id =req.getParameter("uid");
if(!StringUtils.isNullOrEmpty(id)){
// 调用后台得到的User
UserService userService = new UserServiceImpl();
User user = userService.getUserById(id);
req.setAttribute("user",user);
try {
req.getRequestDispatcher(url).forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 修改用户
public void modify(HttpServletRequest req,HttpServletResponse resp){
String id = req.getParameter("uid");
String userName = req.getParameter("userName");
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");
User user = new User();
user.setId(Integer.valueOf(id));
user.setUserName(userName);
user.setGender(Integer.valueOf(gender));
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
user.setPhone(phone);
user.setAddress(address);
user.setUserRole(Integer.valueOf(userRole));
user.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
user.setModifyDate(new Date());
UserService userService = new UserServiceImpl();
try {
if (userService.modify(user)) {
resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
} else {
req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
// 获取角色列表
public void getRoleList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Role> roleList = null;
RoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
//把roleList转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(roleList));
outPrintWriter.flush();
outPrintWriter.close();
}
// 验证用户编码
public void userCodeExist(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//判断用户账号是否可用
String userCode = request.getParameter("userCode");
HashMap<String, String> resultMap = new HashMap<String, String>();
if (StringUtils.isNullOrEmpty(userCode)) {
resultMap.put("userCode", "exist");
} else {
UserService userService = new UserServiceImpl();
User user = userService.selectUserCodeExist(request,userCode);
if (null != user) {
resultMap.put("userCode", "exist");
} else {
resultMap.put("userCode", "notexist");
}
}
//把resultMap转为json字符串以json的形式输出
//配置上下文的输出类型
response.setContentType("application/json");
//从response对象中获取往外输出的writer对象
PrintWriter outPrintWriter = response.getWriter();
//把resultMap转为json字符串 输出
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();//刷新
outPrintWriter.close();//关闭流
}
} -
实现用户管理模块
smbms供应商管理模块
实现步骤
-
编写供应商增删改查相关功能
ProviderDao.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
26
27
28package com.jokerdig.dao.provider;
import com.jokerdig.pojo.Provider;
import java.sql.Connection;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 11:06
**/
public interface ProviderDao {
// 查询和分页
List<Provider> getProviderList(Connection connection, String proName, String proCode) throws Exception;
// 添加供应商
int add(Connection connection, Provider provider) throws Exception;
// 删除供应商
int deleteProviderById(Connection connection, String delId) throws Exception;
// 通过id获取供应商
Provider getProviderById(Connection connection, String id) throws Exception;
// 修改供应商
int modify(Connection connection, Provider provider) throws Exception;
}ProviderDaoImpl.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146package com.jokerdig.dao.provider;
import com.jokerdig.dao.BaseDao;
import com.jokerdig.pojo.Provider;
import com.mysql.cj.util.StringUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 11:06
**/
public class ProviderDaoImpl implements ProviderDao{
// 查询和分页
public List<Provider> getProviderList(Connection conn, String proName, String proCode) throws Exception {
PreparedStatement ps = null;
ResultSet re = null;
List<Provider> providerList = new ArrayList<>();
if(conn!=null){
// 编写查询
StringBuffer sql = new StringBuffer();
sql.append("select * from smbms_provider where 1=1 ");
List<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(proName)) {
sql.append(" and proName like ?");
list.add("%" + proName + "%");
}
if (!StringUtils.isNullOrEmpty(proCode)) {
sql.append(" and proCode like ?");
list.add("%" + proCode + "%");
}
Object[] params = list.toArray();
re = BaseDao.execute(conn, ps, re, sql.toString(), params);
//遍历查询结果
while(re.next()){
Provider provider = new Provider();
provider.setId(re.getInt("id"));
provider.setProCode(re.getString("proCode"));
provider.setProName(re.getString("proName"));
provider.setProDesc(re.getString("proDesc"));
provider.setProContact(re.getString("proContact"));
provider.setProPhone(re.getString("proPhone"));
provider.setProAddress(re.getString("proAddress"));
provider.setProFax(re.getString("proFax"));
provider.setCreationDate(re.getTimestamp("creationDate"));
// 添加到list中
providerList.add(provider);
}
// 释放资源
BaseDao.closeResource(null,ps,re);
}
return providerList;
}
// 添加供应商
public int add(Connection conn, Provider provider) throws Exception {
PreparedStatement ps = null;
int back = 0;
if(conn!=null){
String sql ="insert into smbms_provider (proCode,proName,proDesc," +
"proContact,proPhone,proAddress,proFax,createdBy,creationDate)" +
"values(?,?,?,?,?,?,?,?,?)";
Object[] para = {provider.getProCode(), provider.getProName(), provider.getProDesc(),
provider.getProContact(), provider.getProPhone(), provider.getProAddress(),
provider.getProFax(), provider.getCreatedBy(), provider.getCreationDate()};
// 添加
back = BaseDao.execute(conn,ps,sql,para);
// 释放资源
BaseDao.closeResource(null,ps,null);
}
return back;
}
// 删除供应商
public int deleteProviderById(Connection conn, String delId) throws Exception {
PreparedStatement ps = null;
int back = 0;
if(conn!=null){
String sql = "delete from smbms_provider where id = ? ";
Object[] para = {delId};
back = BaseDao.execute(conn,ps,sql,para);
// 释放资源
BaseDao.closeResource(null,ps,null);
}
return back;
}
// 通过id获取供应商
public Provider getProviderById(Connection conn, String id) throws Exception {
PreparedStatement ps = null;
ResultSet re = null;
Provider provider = null;
if(conn!=null){
String sql = "select * from smbms_provider where id=?";
Object[] para = {id};
// 查询
re = BaseDao.execute(conn,ps,re,sql,para);
while(re.next()){
provider = new Provider();
provider.setId(re.getInt("id"));
provider.setProCode(re.getString("proCode"));
provider.setProName(re.getString("proName"));
provider.setProDesc(re.getString("proDesc"));
provider.setProContact(re.getString("proContact"));
provider.setProPhone(re.getString("proPhone"));
provider.setProAddress(re.getString("proAddress"));
provider.setProFax(re.getString("proFax"));
provider.setCreatedBy(re.getInt("createdBy"));
provider.setCreationDate(re.getTimestamp("creationDate"));
provider.setModifyBy(re.getInt("modifyBy"));
provider.setModifyDate(re.getTimestamp("modifyDate"));
}
// 释放资源
BaseDao.closeResource(null,ps,re);
}
return provider;
}
// 修改供应商
public int modify(Connection conn, Provider provider) throws Exception {
PreparedStatement ps = null;
int back = 0;
if(conn!=null){
String sql = "update smbms_provider set proName=?,proDesc=?,proContact=?," +
"proPhone=?,proAddress=?,proFax=?,modifyBy=?,modifyDate=? where id = ?";
Object[] para = {provider.getProName(), provider.getProDesc(), provider.getProContact(), provider.getProPhone(), provider.getProAddress(),
provider.getProFax(), provider.getModifyBy(), provider.getModifyDate(), provider.getId()};
// 修改
back = BaseDao.execute(conn,ps,sql,para);
// 释放资源
BaseDao.closeResource(null,ps,null);
}
return back;
}
}ProviderService.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
26
27
28package com.jokerdig.service.provider;
import com.jokerdig.pojo.Provider;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 12:24
**/
public interface ProviderService {
// 供应商分页查询
public List<Provider> getProviderList(String proName, String proCode);
// 添加供应商
public boolean add(Provider provider);
// 删除供应商
public int deleteProviderById(String delId);
// 通过proId获取供应商
public Provider getProviderById(String id);
// 修改供应商
public boolean modify(Provider provider);
}ProviderServiceImpl.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160package com.jokerdig.service.provider;
import com.jokerdig.dao.BaseDao;
import com.jokerdig.dao.bill.BillDao;
import com.jokerdig.dao.bill.BillDaoImp;
import com.jokerdig.dao.provider.ProviderDao;
import com.jokerdig.dao.provider.ProviderDaoImpl;
import com.jokerdig.pojo.Provider;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 12:24
**/
public class ProviderServiceImpl implements ProviderService{
private ProviderDao providerDao;
private BillDao billDao;
public ProviderServiceImpl() {
providerDao = new ProviderDaoImpl();
billDao = new BillDaoImp();
}
// 查询
public List<Provider> getProviderList(String proName, String proCode) {
Connection conn = null;
List<Provider> list = null;
try {
conn = BaseDao.getConnection();
list = providerDao.getProviderList(conn,proName,proCode);
} catch (Exception e) {
e.printStackTrace();
}finally{
// 释放资源
BaseDao.closeResource(conn,null,null);
}
return list;
}
// 添加
public boolean add(Provider provider) {
boolean flag = false;
Connection conn = null;
try {
conn = BaseDao.getConnection();
conn.setAutoCommit(false);//开启事务
if (providerDao.add(conn, provider) > 0)
flag = true;
conn.commit(); // 提交
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
// 回滚
System.out.println("---------rollback----------");
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
//释放资源 这里关闭Connection
BaseDao.closeResource(conn, null, null);
}
return flag;
}
/* 删除
* 业务:根据ID删除供应商表的数据之前,需要先去订单表里进行查询操作
* 若订单表中无该供应商的订单数据,则可以删除
* 若有该供应商的订单数据,则不可以删除
* 返回值billCount
* 1> billCount == 0 删除---1 成功 (0) 2 不成功 (-1)
* 2> billCount > 0 不能删除 查询成功(0)查询不成功(-1)
* ---判断
* 如果billCount = -1 失败
* 若billCount >= 0 成功
*/
public int deleteProviderById(String delId) {
Connection conn = null;
int billCount = -1; // 默认-1
try {
conn = BaseDao.getConnection();
conn.setAutoCommit(false);// 开启事务
billCount = billDao.getBillCountByProviderId(conn, delId);
if (billCount == 0) {
providerDao.deleteProviderById(conn, delId);
}
conn.commit();// 提交
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
billCount = -1;
try {
// 回滚
System.out.println("---------rollback----------");
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
BaseDao.closeResource(conn,null,null);
}
}
return billCount;
}
// 通过id查询供应商
public Provider getProviderById(String id) {
Connection conn = null;
Provider provider = null;
try {
conn = BaseDao.getConnection();
provider = providerDao.getProviderById(conn,id);
} catch (Exception e) {
e.printStackTrace();
}finally {
BaseDao.closeResource(conn,null,null);
}
return provider;
}
// 修改
public boolean modify(Provider provider) {
boolean flag = false;
Connection conn = null;
try {
conn = BaseDao.getConnection();
conn.setAutoCommit(false);//关闭自动提交
int back = providerDao.modify(conn,provider);
if(back>0){
flag = true;
conn.commit();
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
} catch (Exception throwables) {
throwables.printStackTrace();
// 失败后数据回滚
System.out.println("数据回滚");
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}finally{
// 释放资源
BaseDao.closeResource(conn,null,null);
}
return flag;
}
}ProviderServlet.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170package com.jokerdig.servlet.provider;
import com.alibaba.fastjson.JSONArray;
import com.jokerdig.pojo.Provider;
import com.jokerdig.pojo.User;
import com.jokerdig.service.provider.ProviderService;
import com.jokerdig.service.provider.ProviderServiceImpl;
import com.jokerdig.until.Constants;
import com.mysql.cj.util.StringUtils;
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.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 13:00
**/
public class ProviderServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if (method != null && method.equals("query")) {
this.query(req, resp);
} else if (method != null && method.equals("add")) {
this.add(req, resp);
} else if (method != null && method.equals("view")) {
this.getProviderById(req, resp, "providerview.jsp");
} else if (method != null && method.equals("modify")) {
this.getProviderById(req, resp, "providermodify.jsp");
} else if (method != null && method.equals("modifysave")) {
this.modify(req, resp);
} else if (method != null && method.equals("delprovider")) {
this.delProvider(req, resp);
}
}
// 删除供应商
private void delProvider(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("proid");
HashMap<String, String> resultMap = new HashMap<String, String>();
if (!StringUtils.isNullOrEmpty(id)) {
ProviderService providerService = new ProviderServiceImpl();
int flag = providerService.deleteProviderById(id);
if (flag == 0) {
//删除成功
resultMap.put("delResult", "true");
} else if (flag == -1) {
//删除失败
resultMap.put("delResult", "false");
} else if (flag > 0) {
//该供应商下有订单,不能删除,返回订单数
resultMap.put("delResult", String.valueOf(flag));
}
} else {
resultMap.put("delResult", "notexit");
}
//把resultMap转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
// 修改供应商
private void modify(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String proName = request.getParameter("proName");
String proContact = request.getParameter("proContact");
String proPhone = request.getParameter("proPhone");
String proAddress = request.getParameter("proAddress");
String proFax = request.getParameter("proFax");
String proDesc = request.getParameter("proDesc");
String id = request.getParameter("id");
Provider provider = new Provider();
provider.setId(Integer.valueOf(id));
provider.setProName(proName);
provider.setProContact(proContact);
provider.setProPhone(proPhone);
provider.setProFax(proFax);
provider.setProAddress(proAddress);
provider.setProDesc(proDesc);
provider.setModifyBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
provider.setModifyDate(new Date());
boolean flag = false;
ProviderService providerService = new ProviderServiceImpl();
flag = providerService.modify(provider);
System.out.println(flag);
if (flag) {
response.sendRedirect(request.getContextPath() + "/jsp/provider.do?method=query");
} else {
request.getRequestDispatcher("providermodify.jsp").forward(request, response);
}
}
// 根据id获取所有
private void getProviderById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("proid");
if (!StringUtils.isNullOrEmpty(id)) {
ProviderService providerService = new ProviderServiceImpl();
Provider provider = null;
provider = providerService.getProviderById(id);
request.setAttribute("provider", provider);
request.getRequestDispatcher(url).forward(request, response);
}
}
// 添加供应商
private void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String proCode = request.getParameter("proCode");
String proName = request.getParameter("proName");
String proContact = request.getParameter("proContact");
String proPhone = request.getParameter("proPhone");
String proAddress = request.getParameter("proAddress");
String proFax = request.getParameter("proFax");
String proDesc = request.getParameter("proDesc");
Provider provider = new Provider();
provider.setProCode(proCode);
provider.setProName(proName);
provider.setProContact(proContact);
provider.setProPhone(proPhone);
provider.setProFax(proFax);
provider.setProAddress(proAddress);
provider.setProDesc(proDesc);
provider.setCreatedBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
provider.setCreationDate(new Date());
boolean flag = false;
ProviderService providerService = new ProviderServiceImpl();
flag = providerService.add(provider);
if (flag) {
response.sendRedirect(request.getContextPath() + "/jsp/provider.do?method=query");
} else {
request.getRequestDispatcher("provideradd.jsp").forward(request, response);
}
}
// 查询供应商并分页
private void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String queryProName = request.getParameter("queryProName");
String queryProCode = request.getParameter("queryProCode");
if (StringUtils.isNullOrEmpty(queryProName)) {
queryProName = "";
}
if (StringUtils.isNullOrEmpty(queryProCode)) {
queryProCode = "";
}
List<Provider> providerList = new ArrayList<Provider>();
ProviderService providerService = new ProviderServiceImpl();
providerList = providerService.getProviderList(queryProName, queryProCode);
request.setAttribute("providerList", providerList);
request.setAttribute("queryProName", queryProName);
request.setAttribute("queryProCode", queryProCode);
request.getRequestDispatcher("providerlist.jsp").forward(request, response);
}
}web.xml
1
2
3
4
5
6
7
8
9<!-- ProviderServlet-->
<servlet>
<servlet-name>ProvdierServlet</servlet-name>
<servlet-class>com.jokerdig.servlet.provider.ProviderServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProvdierServlet</servlet-name>
<url-pattern>/jsp/provider.do</url-pattern>
</servlet-mapping> -
实现供应商管理模块
smbms订单管理模块
实现步骤
-
编写订单增删改查相关功能
BillDao.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
26
27
28
29
30package com.jokerdig.dao.bill;
import com.jokerdig.pojo.Bill;
import java.sql.Connection;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 11:09
**/
public interface BillDao {
// 查询订单列表
List<Bill> getBillList(Connection connection, Bill bill) throws Exception;
// 添加订单
int add(Connection connection, Bill bill) throws Exception;
// 删除订单
int deleteBillById(Connection connection, String delId) throws Exception;
// 通过id获取订单
Bill getBillById(Connection connection, String id) throws Exception;
// 修改订单信息
int modify(Connection connection, Bill bill) throws Exception;
// 根据供应商id查询订单
int getBillCountByProviderId(Connection connection, String providerId) throws Exception;
}BillDaoImpl.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166package com.jokerdig.dao.bill;
import com.jokerdig.dao.BaseDao;
import com.jokerdig.pojo.Bill;
import com.mysql.cj.util.StringUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 11:11
**/
public class BillDaoImp implements BillDao{
// 查询订单列表
public List<Bill> getBillList(Connection conn, Bill bill) throws Exception {
PreparedStatement ps =null;
ResultSet re =null;
List<Bill> billList = new ArrayList<>();
if(conn!=null){
StringBuffer sql = new StringBuffer();
sql.append("select b.*,p.proName as providerName from smbms_bill b, smbms_provider p where b.providerId = p.id");
List<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(bill.getProductName())) {
sql.append(" and productName like ?");
list.add("%" + bill.getProductName() + "%");
}
if (bill.getProviderId() > 0) {
sql.append(" and providerId = ?");
list.add(bill.getProviderId());
}
if (bill.getIsPayment() > 0) {
sql.append(" and isPayment = ?");
list.add(bill.getIsPayment());
}
Object[] para = list.toArray();
re = BaseDao.execute(conn,ps,re,sql.toString(),para);
while(re.next()){
Bill _bill = new Bill();
_bill.setId(re.getInt("id"));
_bill.setBillCode(re.getString("billCode"));
_bill.setProductName(re.getString("productName"));
_bill.setProductDesc(re.getString("productDesc"));
_bill.setProductUnit(re.getString("productUnit"));
_bill.setProductCount(re.getBigDecimal("productCount"));
_bill.setTotalPrice(re.getBigDecimal("totalPrice"));
_bill.setIsPayment(re.getInt("isPayment"));
_bill.setProviderId(re.getInt("providerId"));
_bill.setProviderName(re.getString("providerName"));
_bill.setCreationDate(re.getTimestamp("creationDate"));
_bill.setCreatedBy(re.getInt("createdBy"));
// 添加到list中
billList.add(_bill);
}
// 释放资源
BaseDao.closeResource(null,ps,re);
}
return billList;
}
// 添加订单
public int add(Connection conn, Bill bill) throws Exception {
PreparedStatement ps = null;
int back = 0;
if(conn!=null){
String sql = "insert into smbms_bill (billCode,productName,productDesc," +
"productUnit,productCount,totalPrice,isPayment,providerId,createdBy,creationDate)" +
"values(?,?,?,?,?,?,?,?,?,?)";
Object[] para = {bill.getBillCode(), bill.getProductName(), bill.getProductDesc(),
bill.getProductUnit(), bill.getProductCount(), bill.getTotalPrice(), bill.getIsPayment(),
bill.getProviderId(), bill.getCreatedBy(), bill.getCreationDate()};
// 添加订单
back = BaseDao.execute(conn,ps,sql,para);
// 释放资源
BaseDao.closeResource(null,ps,null);
}
return back;
}
// 删除订单
public int deleteBillById(Connection conn, String delId) throws Exception {
PreparedStatement ps =null;
int back = 0;
if(conn!=null){
String sql = "delete from smbms_bill where id = ?";
Object[] para = {delId};
// 删除
back = BaseDao.execute(conn,ps,sql,para);
// 释放资源
BaseDao.closeResource(null,ps,null);
}
return back;
}
// 通过id获取订单
public Bill getBillById(Connection conn, String id) throws Exception {
PreparedStatement ps =null;
Bill bill = null;
ResultSet re = null;
if(conn!=null){
String sql ="select b.*,p.proName as providerName from smbms_bill b, smbms_provider p where b.id=? and b.providerId = p.id";
Object[] para ={id};
// 查询
re = BaseDao.execute(conn,ps,re,sql,para);
while(re.next()){
bill = new Bill();
bill.setId(re.getInt("id"));
bill.setBillCode(re.getString("billCode"));
bill.setProductName(re.getString("productName"));
bill.setProductDesc(re.getString("productDesc"));
bill.setProductUnit(re.getString("productUnit"));
bill.setProductCount(re.getBigDecimal("productCount"));
bill.setTotalPrice(re.getBigDecimal("totalPrice"));
bill.setIsPayment(re.getInt("isPayment"));
bill.setProviderId(re.getInt("providerId"));
bill.setProviderName(re.getString("providerName"));
bill.setModifyBy(re.getInt("modifyBy"));
bill.setModifyDate(re.getTimestamp("modifyDate"));
}
// 释放资源
BaseDao.closeResource(null,ps,re);
}
return bill;
}
// 修改订单信息
public int modify(Connection conn, Bill bill) throws Exception {
PreparedStatement ps =null;
int back = 0;
if(conn!=null){
String sql = "update smbms_bill set productName=?," +
"productDesc=?,productUnit=?,productCount=?,totalPrice=?," +
"isPayment=?,providerId=?,modifyBy=?,modifyDate=? where id = ? ";
Object[] para = {bill.getProductName(), bill.getProductDesc(),
bill.getProductUnit(), bill.getProductCount(), bill.getTotalPrice(), bill.getIsPayment(),
bill.getProviderId(), bill.getModifyBy(), bill.getModifyDate(), bill.getId()};
// 修改
back = BaseDao.execute(conn,ps,sql,para);
// 释放资源
BaseDao.closeResource(null,ps,null);
}
return back;
}
// 根据供应商id查询订单
public int getBillCountByProviderId(Connection conn, String providerId) throws Exception {
PreparedStatement ps =null;
int count = 0;
if(conn!=null){
String sql = "select count(1) as billCount from smbms_bill where providerId = ?";
Object[] para = {providerId};
// 查询
count = BaseDao.execute(conn,ps,sql,para);
// 释放资源
BaseDao.closeResource(null,ps,null);
}
return count;
}
}BillService.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
26
27package com.jokerdig.service.bill;
import com.jokerdig.pojo.Bill;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 12:25
**/
public interface BillService {
// 通过条件获取订单列表-模糊查询-billList
public List<Bill> getBillList(Bill bill);
// 添加订单
public boolean add(Bill bill);
// 通过billId删除Bill
public boolean deleteBillById(String delId);
// 通过billId获取Bill
public Bill getBillById(String id);
// 修改订单信息
public boolean modify(Bill bill);
}BillServiceImpl.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136package com.jokerdig.service.bill;
import com.jokerdig.dao.BaseDao;
import com.jokerdig.dao.bill.BillDao;
import com.jokerdig.dao.bill.BillDaoImp;
import com.jokerdig.pojo.Bill;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 12:25
**/
public class BillServiceImpl implements BillService{
// 引入dao
private BillDao billDao;
public BillServiceImpl() {
billDao = new BillDaoImp();
}
// 查询所有订单
public List<Bill> getBillList(Bill bill) {
Connection conn = null;
List<Bill> billList = null;
try {
conn = BaseDao.getConnection();
billList = billDao.getBillList(conn, bill);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(conn, null, null);
}
return billList;
}
// 添加
public boolean add(Bill bill) {
boolean flag = false;
Connection conn = null;
try {
conn = BaseDao.getConnection();
conn.setAutoCommit(false);//关闭自动提交
int back = billDao.add(conn,bill);
if(back>0){
flag = true;
conn.commit();
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
} catch (Exception throwables) {
throwables.printStackTrace();
// 回滚
System.out.println("---------rollback----------");
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}finally{
// 释放资源
BaseDao.closeResource(conn,null,null);
}
return flag;
}
// 删除
public boolean deleteBillById(String delId) {
Connection conn = null;
boolean flag = false;
try {
conn = BaseDao.getConnection();
if (billDao.deleteBillById(conn, delId) > 0)
flag = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(conn, null, null);
}
return flag;
}
// 通过id获取
public Bill getBillById(String id) {
Bill bill = null;
Connection conn = null;
try {
conn = BaseDao.getConnection();
bill = billDao.getBillById(conn, id);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
bill = null;
} finally {
BaseDao.closeResource(conn, null, null);
}
return bill;
}
// 修改
public boolean modify(Bill bill) {
boolean flag = false;
Connection conn = null;
try {
conn = BaseDao.getConnection();
conn.setAutoCommit(false);// 关闭自动提交
if(billDao.modify(conn,bill) > 0){
flag = true;
conn.commit();
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
} catch (Exception throwables) {
throwables.printStackTrace();
// 失败后数据回滚
System.out.println("数据回滚");
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}finally{
// 释放资源
BaseDao.closeResource(conn,null,null);
}
return flag;
}
}BillServlet.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218package com.jokerdig.servlet.bill;
import com.alibaba.fastjson.JSONArray;
import com.jokerdig.pojo.Bill;
import com.jokerdig.pojo.Provider;
import com.jokerdig.pojo.User;
import com.jokerdig.service.bill.BillService;
import com.jokerdig.service.bill.BillServiceImpl;
import com.jokerdig.service.provider.ProviderService;
import com.jokerdig.service.provider.ProviderServiceImpl;
import com.jokerdig.until.Constants;
import com.mysql.cj.util.StringUtils;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* @author Joker大雄
* @data 2022/4/20 - 13:00
**/
public class BillServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
BigDecimal totalPriceBigDecimal =
设置规则,小数点保留两位,多出部分,ROUND_DOWN 舍弃
ROUND_HALF_UP 四舍五入(5入) ROUND_UP 进位
OUND_HALF_DOWN 四舍五入(5不入)
new BigDecimal(totalPrice).setScale(2,BigDecimal.ROUND_DOWN);
*/
String method = req.getParameter("method");
if (method != null && method.equals("query")) {
this.query(req,resp);
} else if (method != null && method.equals("add")) {
this.add(req, resp);
} else if (method != null && method.equals("view")) {
this.getBillById(req, resp, "billview.jsp");
} else if (method != null && method.equals("modify")) {
this.getBillById(req, resp, "billmodify.jsp");
} else if (method != null && method.equals("modifysave")) {
this.modify(req, resp);
} else if (method != null && method.equals("delbill")) {
this.delBill(req, resp);
} else if (method != null && method.equals("getproviderlist")) {
this.getProviderlist(req, resp);
}
}
// 获取供应商列表
private void getProviderlist(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Provider> providerList = new ArrayList<Provider>();
ProviderService providerService = new ProviderServiceImpl();
providerList = providerService.getProviderList("", "");
//把providerList转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(providerList));
outPrintWriter.flush();
outPrintWriter.close();
}
// 根据id获取订单 用来修改
private void getBillById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("billid");
if (!StringUtils.isNullOrEmpty(id)) {
BillService billService = new BillServiceImpl();
Bill bill = null;
bill = billService.getBillById(id);
request.setAttribute("bill", bill);
request.getRequestDispatcher(url).forward(request, response);
}
}
// 修改
private void modify(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("modify===============");
String id = request.getParameter("id");
String productName = request.getParameter("productName");
String productDesc = request.getParameter("productDesc");
String productUnit = request.getParameter("productUnit");
String productCount = request.getParameter("productCount");
String totalPrice = request.getParameter("totalPrice");
String providerId = request.getParameter("providerId");
String isPayment = request.getParameter("isPayment");
Bill bill = new Bill();
bill.setId(Integer.valueOf(id));
bill.setProductName(productName);
bill.setProductDesc(productDesc);
bill.setProductUnit(productUnit);
bill.setProductCount(new BigDecimal(productCount).setScale(2, BigDecimal.ROUND_DOWN));
bill.setIsPayment(Integer.parseInt(isPayment));
bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN));
bill.setProviderId(Integer.parseInt(providerId));
bill.setModifyBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
bill.setModifyDate(new Date());
boolean flag = false;
BillService billService = new BillServiceImpl();
flag = billService.modify(bill);
if (flag) {
response.sendRedirect(request.getContextPath() + "/jsp/bill.do?method=query");
} else {
request.getRequestDispatcher("billmodify.jsp").forward(request, response);
}
}
// 删除订单
private void delBill(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("billid");
HashMap<String, String> resultMap = new HashMap<String, String>();
if (!StringUtils.isNullOrEmpty(id)) {
BillService billService = new BillServiceImpl();
boolean flag = billService.deleteBillById(id);
if (flag) {//删除成功
resultMap.put("delResult", "true");
} else {//删除失败
resultMap.put("delResult", "false");
}
} else {
resultMap.put("delResult", "notexit");
}
//把resultMap转换成json对象输出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
// 添加订单
private void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String billCode = request.getParameter("billCode");
String productName = request.getParameter("productName");
String productDesc = request.getParameter("productDesc");
String productUnit = request.getParameter("productUnit");
String productCount = request.getParameter("productCount");
String totalPrice = request.getParameter("totalPrice");
String providerId = request.getParameter("providerId");
String isPayment = request.getParameter("isPayment");
Bill bill = new Bill();
bill.setBillCode(billCode);
bill.setProductName(productName);
bill.setProductDesc(productDesc);
bill.setProductUnit(productUnit);
bill.setProductCount(new BigDecimal(productCount).setScale(2, BigDecimal.ROUND_DOWN));
bill.setIsPayment(Integer.parseInt(isPayment));
bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN));
bill.setProviderId(Integer.parseInt(providerId));
bill.setCreatedBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
bill.setCreationDate(new Date());
boolean flag = false;
BillService billService = new BillServiceImpl();
flag = billService.add(bill);
System.out.println("add flag -- > " + flag);
if (flag) {
response.sendRedirect(request.getContextPath() + "/jsp/bill.do?method=query");
} else {
request.getRequestDispatcher("billadd.jsp").forward(request, response);
}
}
// 查询订单
private void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Provider> providerList = new ArrayList<Provider>();
ProviderService providerService = new ProviderServiceImpl();
providerList = providerService.getProviderList("", "");
request.setAttribute("providerList", providerList);
String queryProductName = request.getParameter("queryProductName");
String queryProviderId = request.getParameter("queryProviderId");
String queryIsPayment = request.getParameter("queryIsPayment");
if (StringUtils.isNullOrEmpty(queryProductName)) {
queryProductName = "";
}
List<Bill> billList = new ArrayList<Bill>();
BillService billService = new BillServiceImpl();
Bill bill = new Bill();
if (StringUtils.isNullOrEmpty(queryIsPayment)) {
bill.setIsPayment(0);
} else {
bill.setIsPayment(Integer.parseInt(queryIsPayment));
}
if (StringUtils.isNullOrEmpty(queryProviderId)) {
bill.setProviderId(0);
} else {
bill.setProviderId(Integer.parseInt(queryProviderId));
}
bill.setProductName(queryProductName);
billList = billService.getBillList(bill);
request.setAttribute("billList", billList);
request.setAttribute("queryProductName", queryProductName);
request.setAttribute("queryProviderId", queryProviderId);
request.setAttribute("queryIsPayment", queryIsPayment);
request.getRequestDispatcher("billlist.jsp").forward(request, response);
}
}web.xml
1
2
3
4
5
6
7
8
9<!-- BillServlet-->
<servlet>
<servlet-name>BillServlet</servlet-name>
<servlet-class>com.jokerdig.servlet.bill.BillServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BillServlet</servlet-name>
<url-pattern>/jsp/bill.do</url-pattern>
</servlet-mapping> -
实现订单管理模块