前言:

本文内容:smbms管理系统项目实战

推荐免费JavaWeb入门到实战视频:【狂神说Java】JavaWeb入门到实战_哔哩哔哩_bilibili

smbms项目搭建

结构图

117

Smbms.sql

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
-- 创建smbms数据库
create database `smbms`;

USE `smbms`;

DROP TABLE IF EXISTS `smbms_address`;
-- 地址表
CREATE TABLE `smbms_address` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`contact` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '联系人姓名',
`addressDesc` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '收货地址明细',
`postCode` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '邮编',
`tel` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '联系人电话',
`createdBy` bigint(20) DEFAULT NULL COMMENT '创建者',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '修改者',
`modifyDate` datetime DEFAULT NULL COMMENT '修改时间',
`userId` bigint(20) DEFAULT NULL COMMENT '用户ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

insert into `smbms_address`(`id`,`contact`,`addressDesc`,`postCode`,`tel`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`userId`) values (1,'王丽','北京市东城区东交民巷44号','100010','13678789999',1,'2016-04-13 00:00:00',NULL,NULL,1),(2,'张红丽','北京市海淀区丹棱街3号','100000','18567672312',1,'2016-04-13 00:00:00',NULL,NULL,1),(3,'任志强','北京市东城区美术馆后街23号','100021','13387906742',1,'2016-04-13 00:00:00',NULL,NULL,1),(4,'曹颖','北京市朝阳区朝阳门南大街14号','100053','13568902323',1,'2016-04-13 00:00:00',NULL,NULL,2),(5,'李慧','北京市西城区三里河路南三巷3号','100032','18032356666',1,'2016-04-13 00:00:00',NULL,NULL,3),(6,'王国强','北京市顺义区高丽营镇金马工业区18号','100061','13787882222',1,'2016-04-13 00:00:00',NULL,NULL,3);

-- 账单表
DROP TABLE IF EXISTS `smbms_bill`;

CREATE TABLE `smbms_bill` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`billCode` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '账单编码',
`productName` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品名称',
`productDesc` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品描述',
`productUnit` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品单位',
`productCount` decimal(20,2) DEFAULT NULL COMMENT '商品数量',
`totalPrice` decimal(20,2) DEFAULT NULL COMMENT '商品总额',
`isPayment` int(10) DEFAULT NULL COMMENT '是否支付(1:未支付 2:已支付)',
`createdBy` bigint(20) DEFAULT NULL COMMENT '创建者(userId)',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者(userId)',
`modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
`providerId` bigint(20) DEFAULT NULL COMMENT '供应商ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

insert into `smbms_bill`(`id`,`billCode`,`productName`,`productDesc`,`productUnit`,`productCount`,`totalPrice`,`isPayment`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`providerId`) values (2,'BILL2016_002','香皂、肥皂、药皂','日用品-皂类','块','1000.00','10000.00',2,1,'2016-03-23 04:20:40',NULL,NULL,13),(3,'BILL2016_003','大豆油','食品-食用油','斤','300.00','5890.00',2,1,'2014-12-14 13:02:03',NULL,NULL,6),(4,'BILL2016_004','橄榄油','食品-进口食用油','斤','200.00','9800.00',2,1,'2013-10-10 03:12:13',NULL,NULL,7),(5,'BILL2016_005','洗洁精','日用品-厨房清洁','瓶','500.00','7000.00',2,1,'2014-12-14 13:02:03',NULL,NULL,9),(6,'BILL2016_006','美国大杏仁','食品-坚果','袋','300.00','5000.00',2,1,'2016-04-14 06:08:09',NULL,NULL,4),(7,'BILL2016_007','沐浴液、精油','日用品-沐浴类','瓶','500.00','23000.00',1,1,'2016-07-22 10:10:22',NULL,NULL,14),(8,'BILL2016_008','不锈钢盘碗','日用品-厨房用具','个','600.00','6000.00',2,1,'2016-04-14 05:12:13',NULL,NULL,14),(9,'BILL2016_009','塑料杯','日用品-杯子','个','350.00','1750.00',2,1,'2016-02-04 11:40:20',NULL,NULL,14),(10,'BILL2016_010','豆瓣酱','食品-调料','瓶','200.00','2000.00',2,1,'2013-10-29 05:07:03',NULL,NULL,8),(11,'BILL2016_011','海之蓝','饮料-国酒','瓶','50.00','10000.00',1,1,'2016-04-14 16:16:00',NULL,NULL,1),(12,'BILL2016_012','芝华士','饮料-洋酒','瓶','20.00','6000.00',1,1,'2016-09-09 17:00:00',NULL,NULL,1),(13,'BILL2016_013','长城红葡萄酒','饮料-红酒','瓶','60.00','800.00',2,1,'2016-11-14 15:23:00',NULL,NULL,1),(14,'BILL2016_014','泰国香米','食品-大米','斤','400.00','5000.00',2,1,'2016-10-09 15:20:00',NULL,NULL,3),(15,'BILL2016_015','东北大米','食品-大米','斤','600.00','4000.00',2,1,'2016-11-14 14:00:00',NULL,NULL,3),(16,'BILL2016_016','可口可乐','饮料','瓶','2000.00','6000.00',2,1,'2012-03-27 13:03:01',NULL,NULL,2),(17,'BILL2016_017','脉动','饮料','瓶','1500.00','4500.00',2,1,'2016-05-10 12:00:00',NULL,NULL,2),(18,'BILL2016_018','哇哈哈','饮料','瓶','2000.00','4000.00',2,1,'2015-11-24 15:12:03',NULL,NULL,2);

-- 供应商表
DROP TABLE IF EXISTS `smbms_provider`;

CREATE TABLE `smbms_provider` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`proCode` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商编码',
`proName` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商名称',
`proDesc` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商详细描述',
`proContact` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商联系人',
`proPhone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '联系电话',
`proAddress` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地址',
`proFax` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '传真',
`createdBy` bigint(20) DEFAULT NULL COMMENT '创建者(userId)',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者(userId)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

insert into `smbms_provider`(`id`,`proCode`,`proName`,`proDesc`,`proContact`,`proPhone`,`proAddress`,`proFax`,`createdBy`,`creationDate`,`modifyDate`,`modifyBy`) values (1,'BJ_GYS001','北京三木堂商贸有限公司','长期合作伙伴,主营产品:茅台、五粮液、郎酒、酒鬼酒、泸州老窖、赖茅酒、法国红酒等','张国强','13566667777','北京市丰台区育芳园北路','010-58858787',1,'2013-03-21 16:52:07',NULL,NULL),(2,'HB_GYS001','石家庄帅益食品贸易有限公司','长期合作伙伴,主营产品:饮料、水饮料、植物蛋白饮料、休闲食品、果汁饮料、功能饮料等','王军','13309094212','河北省石家庄新华区','0311-67738876',1,'2016-04-13 04:20:40',NULL,NULL),(3,'GZ_GYS001','深圳市泰香米业有限公司','初次合作伙伴,主营产品:良记金轮米,龙轮香米等','郑程瀚','13402013312','广东省深圳市福田区深南大道6006华丰大厦','0755-67776212',1,'2014-03-21 16:56:07',NULL,NULL),(4,'GZ_GYS002','深圳市喜来客商贸有限公司','长期合作伙伴,主营产品:坚果炒货.果脯蜜饯.天然花茶.营养豆豆.特色美食.进口食品.海味零食.肉脯肉','林妮','18599897645','广东省深圳市福龙工业区B2栋3楼西','0755-67772341',1,'2013-03-22 16:52:07',NULL,NULL),(5,'JS_GYS001','兴化佳美调味品厂','长期合作伙伴,主营产品:天然香辛料、鸡精、复合调味料','徐国洋','13754444221','江苏省兴化市林湖工业区','0523-21299098',1,'2015-11-22 16:52:07',NULL,NULL),(6,'BJ_GYS002','北京纳福尔食用油有限公司','长期合作伙伴,主营产品:山茶油、大豆油、花生油、橄榄油等','马莺','13422235678','北京市朝阳区珠江帝景1号楼','010-588634233',1,'2012-03-21 17:52:07',NULL,NULL),(7,'BJ_GYS003','北京国粮食用油有限公司','初次合作伙伴,主营产品:花生油、大豆油、小磨油等','王驰','13344441135','北京大兴青云店开发区','010-588134111',1,'2016-04-13 00:00:00',NULL,NULL),(8,'ZJ_GYS001','慈溪市广和绿色食品厂','长期合作伙伴,主营产品:豆瓣酱、黄豆酱、甜面酱,辣椒,大蒜等农产品','薛圣丹','18099953223','浙江省宁波市慈溪周巷小安村','0574-34449090',1,'2013-11-21 06:02:07',NULL,NULL),(9,'GX_GYS001','优百商贸有限公司','长期合作伙伴,主营产品:日化产品','李立国','13323566543','广西南宁市秀厢大道42-1号','0771-98861134',1,'2013-03-21 19:52:07',NULL,NULL),(10,'JS_GYS002','南京火头军信息技术有限公司','长期合作伙伴,主营产品:不锈钢厨具等','陈女士','13098992113','江苏省南京市浦口区浦口大道1号新城总部大厦A座903室','025-86223345',1,'2013-03-25 16:52:07',NULL,NULL),(11,'GZ_GYS003','广州市白云区美星五金制品厂','长期合作伙伴,主营产品:海绵床垫、坐垫、靠垫、海绵枕头、头枕等','梁天','13562276775','广州市白云区钟落潭镇福龙路20号','020-85542231',1,'2016-12-21 06:12:17',NULL,NULL),(12,'BJ_GYS004','北京隆盛日化科技','长期合作伙伴,主营产品:日化环保清洗剂,家居洗涤专卖、洗涤用品网、墙体除霉剂、墙面霉菌清除剂等','孙欣','13689865678','北京市大兴区旧宫','010-35576786',1,'2014-11-21 12:51:11',NULL,NULL),(13,'SD_GYS001','山东豪克华光联合发展有限公司','长期合作伙伴,主营产品:洗衣皂、洗衣粉、洗衣液、洗洁精、消杀类、香皂等','吴洪转','13245468787','山东济阳济北工业区仁和街21号','0531-53362445',1,'2015-01-28 10:52:07',NULL,NULL),(14,'JS_GYS003','无锡喜源坤商行','长期合作伙伴,主营产品:日化品批销','周一清','18567674532','江苏无锡盛岸西路','0510-32274422',1,'2016-04-23 11:11:11',NULL,NULL),(15,'ZJ_GYS002','乐摆日用品厂','长期合作伙伴,主营产品:各种中、高档塑料杯,塑料乐扣水杯(密封杯)、保鲜杯(保鲜盒)、广告杯、礼品杯','王世杰','13212331567','浙江省金华市义乌市义东路','0579-34452321',1,'2016-08-22 10:01:30',NULL,NULL);

-- 角色表
DROP TABLE IF EXISTS `smbms_role`;

CREATE TABLE `smbms_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`roleCode` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '角色编码',
`roleName` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '角色名称',
`createdBy` bigint(20) DEFAULT NULL COMMENT '创建者',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '修改者',
`modifyDate` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

insert into `smbms_role`(`id`,`roleCode`,`roleName`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) values (1,'SMBMS_ADMIN','系统管理员',1,'2016-04-13 00:00:00',NULL,NULL),(2,'SMBMS_MANAGER','经理',1,'2016-04-13 00:00:00',NULL,NULL),(3,'SMBMS_EMPLOYEE','普通员工',1,'2016-04-13 00:00:00',NULL,NULL);

-- 用户表
DROP TABLE IF EXISTS `smbms_user`;

CREATE TABLE `smbms_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`userCode` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户编码',
`userName` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户名称',
`userPassword` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户密码',
`gender` int(10) DEFAULT NULL COMMENT '性别(1:女、 2:男)',
`birthday` date DEFAULT NULL COMMENT '出生日期',
`phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '手机',
`address` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地址',
`userRole` bigint(20) DEFAULT NULL COMMENT '用户角色(取自角色表-角色id)',
`createdBy` bigint(20) DEFAULT NULL COMMENT '创建者(userId)',
`creationDate` datetime DEFAULT NULL COMMENT '创建时间',
`modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者(userId)',
`modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

insert into `smbms_user`(`id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) values (1,'admin','系统管理员','1234567',1,'1983-10-10','13688889999','北京市海淀区成府路207号',1,1,'2013-03-21 16:52:07',NULL,NULL),(2,'liming','李明','0000000',2,'1983-12-10','13688884457','北京市东城区前门东大街9号',2,1,'2014-12-31 19:52:09',NULL,NULL),(5,'hanlubiao','韩路彪','0000000',2,'1984-06-05','18567542321','北京市朝阳区北辰中心12号',2,1,'2014-12-31 19:52:09',NULL,NULL),(6,'zhanghua','张华','0000000',1,'1983-06-15','13544561111','北京市海淀区学院路61号',3,1,'2013-02-11 10:51:17',NULL,NULL),(7,'wangyang','王洋','0000000',2,'1982-12-31','13444561124','北京市海淀区西二旗辉煌国际16层',3,1,'2014-06-11 19:09:07',NULL,NULL),(8,'zhaoyan','赵燕','0000000',1,'1986-03-07','18098764545','北京市海淀区回龙观小区10号楼',3,1,'2016-04-21 13:54:07',NULL,NULL),(10,'sunlei','孙磊','0000000',2,'1981-01-04','13387676765','北京市朝阳区管庄新月小区12楼',3,1,'2015-05-06 10:52:07',NULL,NULL),(11,'sunxing','孙兴','0000000',2,'1978-03-12','13367890900','北京市朝阳区建国门南大街10号',3,1,'2016-11-09 16:51:17',NULL,NULL),(12,'zhangchen','张晨','0000000',1,'1986-03-28','18098765434','朝阳区管庄路口北柏林爱乐三期13号楼',3,1,'2016-08-09 05:52:37',1,'2016-04-14 14:15:36'),(13,'dengchao','邓超','0000000',2,'1981-11-04','13689674534','北京市海淀区北航家属院10号楼',3,1,'2016-07-11 08:02:47',NULL,NULL),(14,'yangguo','杨过','0000000',2,'1980-01-01','13388886623','北京市朝阳区北苑家园茉莉园20号楼',3,1,'2015-02-01 03:52:07',NULL,NULL),(15,'zhaomin','赵敏','0000000',1,'1987-12-04','18099897657','北京市昌平区天通苑3区12号楼',2,1,'2015-09-12 12:02:12',NULL,NULL);

表结构

116

项目如何搭建,是否使用Maven?依赖:jar包

项目搭建

  1. 搭建一个Maven项目

  2. 创建Tomcat创建的项目可以运行

  3. 导入需要的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>
  4. 创建项目包结构

    115

  5. 编写实体类

    ORM映射:表—类映射

    114

  6. 编写基础公共类

    数据库配置文件

    db.properties

    1
    2
    3
    4
    driver=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
    100
    package 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
    31
    package com.jokerdig.filter;

    import javax.servlet.*;
    import java.io.IOException;

    /**
    * @author Joker大雄
    * @data 2022/4/13 - 21:24
    **/
    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 {
    // 编码过滤器
    servletRequest.setCharacterEncoding("utf-8");
    servletResponse.setCharacterEncoding("utf-8");
    servletResponse.setContentType("text/html; charset=utf-8");
    // Chain
    filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    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>
  7. 导入静态资源

    静态资源下载 访问密码:joker

    113

  8. 项目基本架构搭建完成

smbms登录流程实现

实现流程图

112

  1. 导入前端页面

  2. 设置首页

    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>
  3. 编写Dao层用户登录的接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    package 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);

    }
  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
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    package 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{

    // 用户登录
    @Override
    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;
    }
    }
  5. 业务层接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    package 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);
    }
  6. 业务层实现类

    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
    package 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;
    }

    // 登录业务实现层
    @Override
    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;
    }
    }
  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
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    package 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层



    // 登录
    @Override
    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);
    }

    }

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

    创建一个常量工具类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    package com.jokerdig.until;

    /**
    * @author Joker大雄
    * @data 2022/4/14 - 17:24
    **/
    // 常量工具列
    public class Constants {
    public final static String USER_SESSION = "userSession";
    }
  8. 在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>
  9. 登录功能实现

smbms注销及权限过滤

注销功能

实现思路:移除Session,返回登录页面

LogoutServlet.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
package com.jokerdig.servlet.user;

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/15 - 13:27
**/
public class LogoutServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 移除Session
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect("../login.jsp");

}

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

web.xml配置

1
2
3
4
5
6
7
8
9
<!--    注销登录 -->
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.jokerdig.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>

登录拦截优化

通过编写滤器器,并注册以实现未登录拦截

SysFilter.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
package com.jokerdig.filter;

import com.jokerdig.pojo.User;
import com.jokerdig.until.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @author Joker大雄
* @data 2022/4/15 - 13:42
**/
public class SysFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)servletRequest;
HttpServletResponse resp = (HttpServletResponse)servletResponse;
// 获取session中的用户
User user = (User)req.getSession().getAttribute(Constants.USER_SESSION);
if(user == null){
//System.out.println("用户未登录");
// 用户未登录
resp.sendRedirect("/smbms/error.jsp");
}else {
// 用户已经登录
// chain 链
filterChain.doFilter(servletRequest,servletResponse);
}

}

@Override
public void destroy() {

}
}

web.xml配置

1
2
3
4
5
6
7
8
9
<!--    登录拦截过滤器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.jokerdig.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>

smbms密码修改实现

  1. 导入前端素材

  2. 写项目建议从底层开始写

    111

  3. 编写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
    // 修改密码
    @Override
    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;
    }
  4. 编写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
    // 修改用户面膜业务实现层
    @Override
    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;
    }
  5. 编写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
    61
    package 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 {
    @Override
    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);
    }
    }

    @Override
    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>
  6. 密码修改完成(通过Ajax验证旧密码在下节课实现)

smbms通过Ajax验证旧密码

  1. 阿里巴巴的fastjson

    1
    2
    3
    4
    5
    6
    <!--    fastjson-->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
    </dependency>
  2. 编写验证的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
        @Override
    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);
    }

    }
    @Override
    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();
    }
    }
  3. 实现旧密码验证

    108

smbms用户管理查询分页

实现流程图

110

实现步骤

  1. 导入分页的工具类

    工具类下载 密码:joker

    109

  2. 用户列表页面导入

  3. 编写用户显示、分页及查询相关功能

    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
       // 查询用户总人数
    @Override
    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;
    }
    // 查询用户列表
    @Override
    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
    // 查询用户人数
    @Override
    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;
    }
    // 获取用户列表
    @Override
    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);
    }
  4. 编写角色相关功能、

    RoleDao.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    package 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
    47
    package 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{

    // 获取角色列表
    @Override
    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
    16
    package 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
    36
    package 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();
    }

    // 获取角色信息
    @Override
    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;
    }
    }
  5. 用户管理模块实现

    107

smbms用户管理增删改

增删改实现思路

106

实现步骤

  1. 编写用户增删改相关功能

    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
    // 添加用户
    @Override
    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;
    }

    // 删除用户
    @Override
    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;
    }
    // 获取修改用户
    @Override
    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;
    }
    // 修改用户
    @Override
    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
    // 添加用户
    @Override
    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;
    }
    // 删除用户
    @Override
    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;
    }
    // 获取要修改的用户
    @Override
    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;
    }
    //修改用户
    @Override
    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;
    }
    // 获取用户编码
    @Override
    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
    363
    package 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 {
    @Override
    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);
    }


    }

    @Override
    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();//关闭流
    }
    }
  2. 实现用户管理模块

    105

smbms供应商管理模块

实现步骤

  1. 编写供应商增删改查相关功能

    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
    28
    package 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
    146
    package 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{


    // 查询和分页
    @Override
    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;
    }

    // 添加供应商
    @Override
    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;
    }
    // 删除供应商
    @Override
    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获取供应商
    @Override
    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;
    }
    // 修改供应商
    @Override
    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
    28
    package 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
    160
    package 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();
    }
    // 查询
    @Override
    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;
    }

    // 添加
    @Override
    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 成功
    */
    @Override
    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查询供应商
    @Override
    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;
    }
    // 修改
    @Override
    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
    170
    package 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 {


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

    @Override
    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>
  2. 实现供应商管理模块

    104

smbms订单管理模块

实现步骤

  1. 编写订单增删改查相关功能

    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
    30
    package 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
    166
    package 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{

    // 查询订单列表
    @Override
    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;
    }
    // 添加订单
    @Override
    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;
    }
    // 删除订单
    @Override
    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获取订单
    @Override
    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;
    }
    // 修改订单信息
    @Override
    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查询订单
    @Override
    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
    27
    package 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
    136
    package 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();
    }

    // 查询所有订单
    @Override
    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;
    }
    // 添加
    @Override
    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;
    }
    // 删除
    @Override
    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获取
    @Override
    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;
    }
    // 修改
    @Override
    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
    218
    package 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 {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req,resp);
    }

    @Override
    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>
  2. 实现订单管理模块

    103