全网最细:十万字详解订单超市管理系统

项目完善测试视频

SMBMS系统展示

一:项目前期准备工作

第一步 创建数据库、数据库表

全网最细:十万字详解订单超市管理系统_第1张图片

CREATE DATABASE `smbms`;

use `smbms`;

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

第二步 创建maven web项目

第三步 创建包

全网最细:十万字详解订单超市管理系统_第2张图片

此时项目搭建完毕

第四步 配置tomcat

配置以上完毕 启动服务器 看是否成功启动并显示index页面
全网最细:十万字详解订单超市管理系统_第3张图片

第五步 导依赖

  <dependencies>

    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>4.0.1version>
    dependency>

    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>javax.servlet.jsp-apiartifactId>
      <version>2.3.3version>
    dependency>

      <dependency>
          <groupId>mysqlgroupId>
          <artifactId>mysql-connector-javaartifactId>
          <version>8.0.24version>
      dependency>
      
      <dependency>
          <groupId>javax.servlet.jsp.jstlgroupId>
          <artifactId>jstl-apiartifactId>
          <version>1.2version>
      dependency>

      <dependency>
          <groupId>taglibsgroupId>
          <artifactId>standardartifactId>
          <version>1.1.2version>
      dependency>
  dependencies>

第六步 建立包结构

全网最细:十万字详解订单超市管理系统_第4张图片

第七步 建立实体类

就是ORM映射思想 将数据库表和实体类一 一对应
User类

import java.util.Date;

public class User {
    private Integer id;
    private String userCode;    //用户编码
    private String userName;
    private String userPassword;
    private Integer gender;
    private Date birthday;
    private String phone;
    private String address;
    private Integer userRole;
    private Integer createdBy;  //创建者
    private Date createDate;
    private Integer modifyBy;   //更新者
    private Date modifyDate;    //更新时间

    private Integer age;    //年龄
    private String userRoleName;    //用户角色名称

    public Integer getAge() {
        Date date = new Date();
        Integer age = date.getYear()-birthday.getYear();
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getUserRoleName() {
        return userRoleName;
    }

    public void setUserRoleName(String userRoleName) {
        this.userRoleName = userRoleName;
    }





    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserCode() {
        return userCode;
    }

    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getUserRole() {
        return userRole;
    }

    public void setUserRole(Integer userRole) {
        this.userRole = userRole;
    }

    public Integer getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Integer getModifyBy() {
        return modifyBy;
    }

    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
}

Role类

import java.util.Date;
public class Role {
    private Integer id;   //id
    private String roleCode; //角色编码
    private String roleName; //角色名称
    private Integer createdBy; //创建者
    private Date creationDate; //创建时间
    private Integer modifyBy; //更新者
    private Date modifyDate;//更新时间

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getRoleCode() {
        return roleCode;
    }
    public void setRoleCode(String roleCode) {
        this.roleCode = roleCode;
    }
    public String getRoleName() {
        return roleName;
    }
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
    public Integer getCreatedBy() {
        return createdBy;
    }
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    public Date getCreationDate() {
        return creationDate;
    }
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    public Integer getModifyBy() {
        return modifyBy;
    }
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
}

Provider类

import java.util.Date;
public class Provider {
    private Integer id;   //id
    private String proCode; //供应商编码
    private String proName; //供应商名称
    private String proDesc; //供应商描述
    private String proContact; //供应商联系人
    private String proPhone; //供应商电话
    private String proAddress; //供应商地址
    private String proFax; //供应商传真
    private Integer createdBy; //创建者
    private Date creationDate; //创建时间
    private Integer modifyBy; //更新者
    private Date modifyDate;//更新时间

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getProCode() {
        return proCode;
    }
    public void setProCode(String proCode) {
        this.proCode = proCode;
    }
    public String getProName() {
        return proName;
    }
    public void setProName(String proName) {
        this.proName = proName;
    }
    public String getProDesc() {
        return proDesc;
    }
    public void setProDesc(String proDesc) {
        this.proDesc = proDesc;
    }
    public String getProContact() {
        return proContact;
    }
    public void setProContact(String proContact) {
        this.proContact = proContact;
    }
    public String getProPhone() {
        return proPhone;
    }
    public void setProPhone(String proPhone) {
        this.proPhone = proPhone;
    }
    public String getProAddress() {
        return proAddress;
    }
    public void setProAddress(String proAddress) {
        this.proAddress = proAddress;
    }
    public String getProFax() {
        return proFax;
    }
    public void setProFax(String proFax) {
        this.proFax = proFax;
    }
    public Integer getCreatedBy() {
        return createdBy;
    }
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    public Date getCreationDate() {
        return creationDate;
    }
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    public Integer getModifyBy() {
        return modifyBy;
    }
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
}

Bill类

import java.math.BigDecimal;
import java.util.Date;
public class Bill {
    private Integer id;   //id
    private String billCode; //账单编码
    private String productName; //商品名称
    private String productDesc; //商品描述
    private String productUnit; //商品单位
    private BigDecimal productCount; //商品数量
    private BigDecimal totalPrice; //总金额
    private Integer isPayment; //是否支付
    private Integer providerId; //供应商ID
    private Integer createdBy; //创建者
    private Date creationDate; //创建时间
    private Integer modifyBy; //更新者
    private Date modifyDate;//更新时间

    private String providerName;//供应商名称


    public String getProviderName() {
        return providerName;
    }
    public void setProviderName(String providerName) {
        this.providerName = providerName;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getBillCode() {
        return billCode;
    }
    public void setBillCode(String billCode) {
        this.billCode = billCode;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getProductDesc() {
        return productDesc;
    }
    public void setProductDesc(String productDesc) {
        this.productDesc = productDesc;
    }
    public String getProductUnit() {
        return productUnit;
    }
    public void setProductUnit(String productUnit) {
        this.productUnit = productUnit;
    }
    public BigDecimal getProductCount() {
        return productCount;
    }
    public void setProductCount(BigDecimal productCount) {
        this.productCount = productCount;
    }
    public BigDecimal getTotalPrice() {
        return totalPrice;
    }
    public void setTotalPrice(BigDecimal totalPrice) {
        this.totalPrice = totalPrice;
    }
    public Integer getIsPayment() {
        return isPayment;
    }
    public void setIsPayment(Integer isPayment) {
        this.isPayment = isPayment;
    }

    public Integer getProviderId() {
        return providerId;
    }
    public void setProviderId(Integer providerId) {
        this.providerId = providerId;
    }
    public Integer getCreatedBy() {
        return createdBy;
    }
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    public Date getCreationDate() {
        return creationDate;
    }
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    public Integer getModifyBy() {
        return modifyBy;
    }
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
}

第八步 编写基础公共类

1:数据库配置文件
在resources下面新建文件 db.properties
在这里插入图片描述

driver = com.mysql.cj.jdbc.Driver
url =jdbc:mysql://localhost:3306/smbms?\
  useUnicode=true&characterEncoding=UTF8&useSSL=false&\
  serverTimezone=UTC&rewriteBatchedStatements=true
username = 你的用户名
password = 你的密码

2:在Dao层编写操作数据库的公共类

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

public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    //静态代码块 类加载的时候初始化
    static {
        Properties properties = new Properties();
        //通过类加载器读取对应的资源
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        //  properties读取文件内容
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.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,String sql,PreparedStatement preparedStatement,Object[] params,ResultSet resultSet) throws SQLException {
        //预编译的sql在后面直接执行即可
        preparedStatement = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            //setObject 占位符从1开始 而数字从0开始
            preparedStatement.setObject(i+1,params[i]);
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }
    //编写增删改查公共方法
    public static int execute(Connection conn,String sql,PreparedStatement preparedStatement,Object[] params) throws SQLException {
        //预编译的sql在后面直接执行即可
        int updateRow;
        preparedStatement = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            //setObject 占位符从1开始 而数字从0开始
            preparedStatement.setObject(i+1,params[i]);
        }
        updateRow = preparedStatement.executeUpdate();
        return updateRow;
    }
    //释放资源
    public static boolean closeResource(Connection conn,PreparedStatement preparedStatement,ResultSet resultSet){
        boolean flag = true;
        if(conn!=null){
            try {
                conn.close();
                //GC回收
                conn = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if(preparedStatement!=null){
            try {
                preparedStatement.close();
                //GC回收
                preparedStatement = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if(resultSet!=null){
            try {
                resultSet.close();
                //GC回收
                resultSet = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }
}

3:编写字符过滤器
在Filter下面新建
在这里插入图片描述

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

public class CharacterEncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf8");
        servletResponse.setCharacterEncoding("utf8");
        filterChain.doFilter(servletRequest,servletResponse);
    }

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

    }

    @Override
    public void destroy() {

    }
}

写完过滤器记得在WEB.xml中进行注册


    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>com.csnz.filter.CharacterEncodingFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

4.导入静态资源

记得是在webapp下面
全网最细:十万字详解订单超市管理系统_第5张图片

二:登录模块

2.1.1思路图解

全网最细:十万字详解订单超市管理系统_第6张图片

2.1.2 编写登录页面

全网最细:十万字详解订单超市管理系统_第7张图片

2.1.3 编写dao层用户登录的接口UserDao

这一步的主要功能就是从首页获取用户 输入的名称和密码
与数据库中的数据进行对比

全网最细:十万字详解订单超市管理系统_第8张图片

import com.csnz.pojo.User;

import java.sql.Connection;
import java.sql.SQLException;

//登录 判断 的接口
public interface UserDao {
    //得到要登录的用户信息
    public User getLoginInfo(Connection conn,String userCode) throws SQLException;
}

2.1.4 编写dao接口的实现类

全网最细:十万字详解订单超市管理系统_第9张图片

import com.csnz.dao.BaseDao;
import com.csnz.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//登录 判断 的实现类
public class UserDaoImpl implements UserDao {
    @Override
    //得到要登录的用户信息
    public User getLoginInfo(Connection conn, String userCode) throws SQLException {
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        User user = null;

        //如果连数据库都没连接就无需判断了
        if(conn!=null){
            //编写sql语句
            String sql = "select * from smbms_user where userCode = ?";
            //存放参数
            Object[] params = {userCode};
            //使用预处理对象调用  操作数据库的公共类 的执行 sql查询语句
            rs = BaseDao.executeQuery(conn, sql, preparedStatement, params,rs);
            //遍历结果集  封装到一个用户中
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreateDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
            }
            //调用  操作数据库的公共类 的执行 释放资源
            BaseDao.closeResource(null,preparedStatement,rs);
        }
        //返回一个用户
        return user;
    }
}

2.1.5 编写业务层 接口

全网最细:十万字详解订单超市管理系统_第10张图片

import com.csnz.pojo.User;
public interface UserService {
    //用户登录
    public abstract User login(String userCode,String passWord);
}

2.1.6 编写业务层接口的实现类

全网最细:十万字详解订单超市管理系统_第11张图片

import com.csnz.dao.BaseDao;
import com.csnz.dao.User.UserDao;
import com.csnz.dao.User.UserDaoImpl;
import com.csnz.pojo.User;

import java.sql.Connection;
import java.sql.SQLException;

//用户登录的业务层实现类
public class UserServiceImpl implements UserService {
    //业务层肯定是调用dao层的
    private UserDao userDao;
    public UserServiceImpl(){
        userDao =new UserDaoImpl();
    }

    @Override
    //(String userCode, String passWord)两个参数对应是的首页传来的值
    public User login(String userCode, String passWord) {
        Connection conn = null;
        User user = null;

        try {
            //调用 dao层操作数据库的公共类方法 获取数据库的连接
            conn = BaseDao.getConnection();
            //得到连接后 开始查询 通过业务层调用具体的数据库操作
            user = userDao.getLoginInfo(conn, userCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            BaseDao.closeResource(conn,null,null);
        }
        return user;
    }
}

2.1.7 建包

全网最细:十万字详解订单超市管理系统_第12张图片

2.1.8 编写用户登录的Servlet

全网最细:十万字详解订单超市管理系统_第13张图片

import com.csnz.pojo.User;
import com.csnz.service.User.UserService;
import com.csnz.service.User.UserServiceImpl;
import com.csnz.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//处理登录请求的servlet
public class LoginServlet extends HttpServlet {
    //控制层 调用业务层代码 进行判断
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取登录页面传来的信息
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        //和数据库中的密码进行对比,调用业务层
        UserService userService = new UserServiceImpl();
        //把登录的人的信息查到
        User user = userService.login(userCode, userPassword);
        //判断
        if (user != null) { //查有此人
            //将用户的信息放在session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        }else{
            //查无此人
            //转发回登录页面 提示 用户名或密码错误
            req.setAttribute("error","用户名或密码错误");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

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

2.1.9 注册用户登录的Servlet


    <servlet>
        <servlet-name>LoginServletservlet-name>
        <servlet-class>com.csnz.servlet.User.LoginServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>LoginServletservlet-name>
        <url-pattern>/login.dourl-pattern>
    servlet-mapping>

三: 注销模块

移除session 返回登录界面

3.1新建Servlet

全网最细:十万字详解订单超市管理系统_第14张图片

import com.csnz.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

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(req.getContextPath()+"/login.jsp");
    }

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

3.2 注册 注销的servlet


    <servlet>
        <servlet-name>LogoutServletservlet-name>
        <servlet-class>com.csnz.servlet.User.LogoutServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>LogoutServletservlet-name>
        <url-pattern>/jsp/logout.dourl-pattern>
    servlet-mapping>

3.3 为了防止用户注销了 还继续访问"内部页面" 还需配置过滤器

全网最细:十万字详解订单超市管理系统_第15张图片

import com.csnz.pojo.User;
import com.csnz.util.Constants;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        //过滤器 从session中获取用户 判断是否登录
        if (user == null) {
            //证明未登录 或 已注销
            response.sendRedirect(request.getContextPath()+"/error.jsp");
        }else{
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}

3.4 注册 此 用户登录过滤器


    <filter>
        <filter-name>LoginFilterfilter-name>
        <filter-class>com.csnz.filter.LoginFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>LoginFilterfilter-name>
        <url-pattern>/jsp/*url-pattern>
    filter-mapping>

配置之后 当我们注销登录后 试图访问用户信息的界面 就会转向到 我们自定义——"找不到界面的 "页面

四: 修改密码模块

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

4.1 导入jsp 和js的素材

全网最细:十万字详解订单超市管理系统_第16张图片

4.2 编写修改密码的dao层

在UserDao.java 中新增

 //修改密码
    public abstract int updatePassword(Connection conn,int id,String newPsd)throws SQLException;

4.3 补全UserDao层对应的实现类

在UserDaoImpl.java中

 @Override
    public int updatePassword(Connection conn, int id, String newPsd) throws SQLException {
        PreparedStatement pstm = null;
        int result = 0;
        Object params[] = {newPsd,id};
        if (conn != null) {
            String sql = "update smbms_user set userPassword = ? where id = ?";
            result = BaseDao.execute(conn, sql, pstm, params);
        }
        return result;
    }

4.4 编写修改密码的service层

在UserService接口中添加方法

//根据用户ID修改密码
    public abstract boolean updatePassword(int id,String passWord);

4.5 补全 实现 UserServiceImpl 的修改密码的方法

//修改密码
    @Override
    public boolean updatePassword(int id, String passWord) {
        boolean flag = false;
        Connection conn = null;
        try {
            //获取连接
            conn = BaseDao.getConnection();
            //调用dao层 执行更新操作
            int i = userDao.updatePassword(conn, id, passWord);
            if (i > 0) {
                flag = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

4.6 编写修改密码的Servlet

全网最细:十万字详解订单超市管理系统_第17张图片

import com.csnz.pojo.User;
import com.csnz.service.User.UserServiceImpl;
import com.csnz.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//实现Servlet复用

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savePwd")){
            this.savePwd(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //用户修改密码方法
    public void savePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从Session中获取ID
        Object obj = req.getSession().getAttribute(Constants.USER_SESSION);
        //获取前端页面传来的旧密码
        String oldpassword = req.getParameter("oldpassword");
        //获取前端页面传来的新密码
        String newpassword = req.getParameter("newpassword");
        //先判断不为空 再比较密码是否相等
        if(obj != null && oldpassword != null && newpassword != null){
            User user = (User) obj;
            //如果用户本身的密码 与 前端传来的旧密码 不同
            if(!user.getUserPassword().equals(oldpassword)){
//                System.out.println("用户本来"+user.getUserPassword());
//                System.out.println("前端填写"+oldpassword);
                req.getSession().setAttribute("message","旧密码填写错误!");
                //如果旧密码输入正确
            }else{
                UserServiceImpl userService = new UserServiceImpl();
                //修改密码并返回结果
                boolean flag = userService.updatePassword(user.getId(), newpassword);
                //如果密码修改成功 移除当前session
                if(flag){
                    req.setAttribute("message","修改密码成功,请使用新密码登录!");
                    req.getSession().removeAttribute(Constants.USER_SESSION);
                }else{
                    req.setAttribute("message","密码修改失败 新密码不符合规范");
                }
            }

        }else{
            req.setAttribute("message","新密码不能为空!");
        }
        //修改完了 重定向到此修改页面
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);

    }
}

4.7 注册复用的Servlet


    <servlet>
        <servlet-name>UserServletservlet-name>
        <servlet-class>com.csnz.servlet.User.UserServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>UserServletservlet-name>
        <url-pattern>/jsp/user.dourl-pattern>
    servlet-mapping>

4.PLUS 优化修改密码模块

具体步骤:

4.1 导阿里巴巴的fastjson依赖


      <dependency>
          <groupId>com.alibabagroupId>
          <artifactId>fastjsonartifactId>
          <version>1.2.61version>
      dependency>

4.2 修改复用Servlet的代码

import com.alibaba.fastjson.JSONArray;
import com.csnz.pojo.User;
import com.csnz.service.User.UserServiceImpl;
import com.csnz.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
//实现Servlet复用

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savePwd")){
            this.savePwd(req,resp);
        }else if(method.equals("pwdmodify")){
            this.verifyPwd(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //用户修改密码方法
    public void savePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从Session中获取ID
        Object obj = req.getSession().getAttribute(Constants.USER_SESSION);
        //获取前端页面传来的新密码
        String newpassword = req.getParameter("newpassword");
        //先判断不为空 再比较密码是否相等
        if(obj != null && newpassword != null){
            User user = (User) obj;
            UserServiceImpl userService = new UserServiceImpl();
            //修改密码并返回结果
            boolean flag = userService.updatePassword(user.getId(), newpassword);
            //如果密码修改成功 移除当前session
            if(flag){
                req.setAttribute("message","修改密码成功,请使用新密码登录!");
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute("message","密码修改失败 新密码不符合规范");
            }
        }else{
            req.setAttribute("message","新密码不能为空!");
        }
        //修改完了 重定向到此修改页面
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);

    }
    //验证密码的方法
    public void verifyPwd(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        //依旧从session中取ID
        Object obj = req.getSession().getAttribute(Constants.USER_SESSION);
        //取 前端传来的旧密码
        String oldpassword = req.getParameter("oldpassword");
        //将结果存放在map集合中 让Ajax使用
        Map<String, String> resultMap = new HashMap<>();
        //下面开始判断 键都是用result 此处匹配js中的Ajax代码
        if(obj == null){
            //说明session被移除了 或未登录|已注销
            resultMap.put("result","sessionerror");
        }else if(oldpassword == null){
            //前端输入的密码为空
            resultMap.put("result","error");
        }else {
            //如果旧密码与前端传来的密码相同
            if(((User)obj).getUserPassword().equals(oldpassword)){
                resultMap.put("result","true");
            }else{
                //前端输入的密码和真实密码不相同
                resultMap.put("result","false");
            }
        }
        //上面已经封装好 现在需要传给Ajax 格式为json 所以我们得转换格式
        resp.setContentType("application/json");//将应用的类型变成json
        PrintWriter writer = resp.getWriter();
        //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();

    }
}

以上的代码 是根据这里修改的
全网最细:十万字详解订单超市管理系统_第18张图片

五:用户管理模块

思路图解
全网最细:十万字详解订单超市管理系统_第19张图片

5.1 新建分页的工具类 PageSupport

public class PageSupport {
    //当前页面 来自于用户输入
    private int currentPageNo = 1;
    //总数量(表)
    private int totalCount = 0;
    //页面容量
    private int pageSize = 0;
    //总共显示的页数 为总表数量/单页容量 +1
    private int totalPageCount =1;

    public int getCurrentPageNo() {
        return currentPageNo;
    }

    public void setCurrentPageNo(int currentPageNo) {
        if(currentPageNo>0){
            this.currentPageNo = currentPageNo;
        }
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        if(totalCount>0){
            this.totalCount = totalCount;
            this.setTotalPageCountByRs();
        }
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        if(pageSize>0){
            this.pageSize = pageSize;
        }
    }

    public int getTotalPageCount() {
        return totalPageCount;
    }

    public void setTotalPageCount(int totalPageCount) {
        this.totalPageCount = totalPageCount;
    }
    public void setTotalPageCountByRs(){
        if(this.totalCount % this.pageSize == 0){
            this.totalPageCount = this.totalCount / this.pageSize;
        }else if(this.totalCount % this.pageSize > 0){
            this.totalPageCount = this.totalCount / this.pageSize +1;
        }else{
            this.totalPageCount = 0;
        }
    }
}

5.2用户列表页面导入

全网最细:十万字详解订单超市管理系统_第20张图片

5.3 获取用户数量 涉及多表查询

5.3.1 编写UserDao层

//根据用户名 或 角色 查询用户总数
    public int getUserCounts(Connection conn,String username,int userRole)throws SQLException;

5.3.2 编写UserDaoImpl层

//根据用户名 或 角色 查询用户总数
    @Override
    public int getUserCounts(Connection conn, String username, int userRole) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        int count = 0;
        if(conn!=null){
            //SQL语句因为联合多表查询 所以需要拼接
            StringBuffer sql = new StringBuffer();
            //默认两表联合  查询总条数
            sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");

            //建一个集合来存储参数
            ArrayList<Object> list = new ArrayList<>();
            if(username!=null){
                sql.append(" and u.userName like ?");
                list.add("%"+username+"%");//默认下标为0
            }
            if(userRole>0 & userRole<4){
                sql.append(" and u.userRole = ?");
                list.add(userRole);//默认下标为1
            }
            //把list转换为数组
            Object[] arrays = list.toArray();
            System.out.println("拼接的sql语句:"+sql.toString());
            //执行sql语句
            rs = BaseDao.executeQuery(conn, sql.toString(), pstm, arrays, rs);
            //遍历结果集
            if(rs.next()){
                //从结果集中获取数量
                count = rs.getInt("count");
            }
            //最终关闭资源连接
            BaseDao.closeResource(null,pstm,rs);
        }
        return count;
    }

5.3.3 编写UserService层

//用户管理——查询记录数
    public abstract int getUserCounts(String username,int userRole);

5.3.4 编写UserServiceImpl层

//用户管理——查询记录数
    @Override
    public int getUserCounts(String username, int userRole) {
        Connection conn = null;
        int userCounts = 0;
        try {
            //获取连接
            conn = BaseDao.getConnection();
            //执行sql语句
            userCounts = userDao.getUserCounts(conn, username, userRole);

        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return userCounts;
        }
    }

5.4 获取用户列表

5.4.1 编写UserDao层

 //根据条件 查询 获取用户列表 userlist
    public abstract List<User> getUserList(Connection conn,String username,int userRole,int currentPageNo,int pageSize)throws SQLException;

5.4.2 编写UserDaoImpl层

//根据用户名 或 角色 查询用户总数
    @Override
    public int getUserCounts(Connection conn, String username, int userRole) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        int count = 0;
        if(conn!=null){
            //SQL语句因为联合多表查询 所以需要拼接
            StringBuffer sql = new StringBuffer();
            //默认两表联合  查询总条数
            sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");

            //建一个集合来存储参数
            ArrayList<Object> list = new ArrayList<>();
            if(username!=null){
                sql.append(" and u.userName like ?");
                list.add("%"+username+"%");//默认下标为0
            }
            if(userRole>0 & userRole<4){
                sql.append(" and u.userRole = ?");
                list.add(userRole);//默认下标为1
            }
            //把list转换为数组
            Object[] arrays = list.toArray();
            System.out.println("拼接的sql语句:"+sql.toString());
            //执行sql语句
            rs = BaseDao.executeQuery(conn, sql.toString(), pstm, arrays, rs);
            //遍历结果集
            if(rs.next()){
                //从结果集中获取数量
                count = rs.getInt("count");
            }
            //最终关闭资源连接
            BaseDao.closeResource(null,pstm,rs);
        }
        return count;
    }
    //根据条件 查询 获取用户列表 userlist
    @Override
    public List<User> getUserList(Connection conn, String username, int userRole, int currentPageNo, int pageSize) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<User>();
        if(conn!=null){
            //SQL语句因为联合多表查询 所以需要拼接
            StringBuffer sql = new StringBuffer();
            //默认两表联合  查询总条数
            sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");

            //建一个集合来存储参数
            List<Object> list = new ArrayList<>();
            if(username!=null){
                sql.append(" and u.userName like ?");
                list.add("%"+username+"%");//默认下标为0
            }
            if(userRole>0 & userRole<4){
                sql.append(" and u.userRole = ?");
                list.add(userRole);//默认下标为1
            }
            //在数据库中 分页使用limit startIndex,pageSize 总数
            //当前页 = (当前页-1)*页面大小
            sql.append(" order by u.creationDate DESC limit ?,?");
            currentPageNo = (currentPageNo-1)*pageSize;
            list.add(currentPageNo);
            list.add(pageSize);

            Object[] params = list.toArray();
        System.out.println("getUserList的语句"+sql.toString());
            //执行sql
            rs = BaseDao.executeQuery(conn, sql.toString(), pstm, params, rs);
            while (rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setUserRoleName(rs.getString("userRoleName"));
                user.setUserRole(rs.getInt("userRole"));
                userList.add(user);
            }
            BaseDao.closeResource(null,pstm,rs);
        }
            return userList;
        }

5.4.3 编写UserService层

//根据条件 查询用户列表
    public abstract List<User> getUserList(String QueryUserName,int QueryUserRole,int currentPageNo,int pageSize);

5.4.4 编写UserServiceImpl层

//根据条件 查询用户列表
    @Override
    public List<User> getUserList(String QueryUserName, int QueryUserRole, int currentPageNo, int pageSize) {
        Connection conn = null;
        List<User> userList = null;
        //获取数据库连接
        try {
            conn = BaseDao.getConnection();
            userList = userDao.getUserList(conn, QueryUserName, QueryUserRole, currentPageNo, pageSize);
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return userList;
        }
    }

5.5 获取 用户角色列表

为了职责统一,把角色的操作单独放在一个包中,和POJO相对应

5.5.1 编写RoleDao层

import com.csnz.pojo.Role;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public interface RoleDao {
    //获取角色列表
    public abstract List<Role> getRoleList(Connection conn)throws SQLException;
}

5.5.2 编写RoleDaoImple层

import com.csnz.dao.BaseDao;
import com.csnz.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;

public class RoleDaoImpl implements RoleDao {
    //获取角色列表
    @Override
    public List<Role> getRoleList(Connection conn) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs  = null;
        ArrayList<Role> roles = new ArrayList<>();
        if(conn != null){
            String sql  = "select * from smbms_role";
            Object[] params = {};
            rs = BaseDao.executeQuery(conn, sql, pstm, params, rs);
            while(rs.next()){
                Role role = new Role();
                role.setId(rs.getInt("id"));
                role.setRoleName(rs.getString("roleName"));
                role.setRoleCode(rs.getString("roleCode"));
                roles.add(role);
            }
        }
        BaseDao.closeResource(null,pstm,rs);
        return roles;
    }
}

5.5.3 编写RoleService层


import com.csnz.pojo.Role;
import java.util.List;

public interface RoleService {
    //获取角色列表
    public abstract List<Role> getRoleList();
}

5.5.4 编写RoleServiceImpl层

import com.csnz.dao.BaseDao;
import com.csnz.dao.Role.RoleDao;
import com.csnz.dao.Role.RoleDaoImpl;
import com.csnz.pojo.Role;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class RoleServiceImpl implements RoleService {
    //业务层调用持久层
    private RoleDao roleDao = null;
    public RoleServiceImpl(){
        this.roleDao =new RoleDaoImpl();
    }
    @Override
    public List<Role> getRoleList()  {
        Connection conn = null;
        List<Role> roleList = null;
        try {
            //获取数据库连接
            conn = BaseDao.getConnection();
            roleList = roleDao.getRoleList(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return roleList;
        }
    }
}

5.6 获取用户 显示的servlet

3.6.1 获取用户在前端输入的数据

3.6.2 根据参数的值 来判断请求是否执行

3.6.3 计算分页需要的条件(当前页面、总页面、页面容量大小)

3.6.4 用户列表展示

3.6.5 返回前端展示

在UserServlet中新添方法

//查询用户列表的方法
    public void query(HttpServletRequest req, HttpServletResponse resp){
        //查询用户列表
            //从前端获取数据
            String queryUserName = req.getParameter("queryName");
            String temp = req.getParameter("queryUserRole");//值为0 、1、2、3
            String pageIndex = req.getParameter("pageIndex");
            int queryUserRole = 0;

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

            int currentPageNo = 1;
            int pageSize = 5;

            if(queryUserName == null){
                queryUserName = "";
            }
            if(temp!=null && !temp.equals("")){
                queryUserRole = Integer.parseInt(temp);
            }
            if(pageIndex!=null){
                currentPageNo = Integer.parseInt(pageIndex);
            }
            //获取用户总数 分页:上一页 下一页
            int totalCount = userService.getUserCounts(queryUserName, queryUserRole);
            //总页数支持
            PageSupport pageSupport = new PageSupport();
                System.out.println("当前页:"+currentPageNo);
            pageSupport.setCurrentPageNo(currentPageNo);
            pageSupport.setPageSize(pageSize);
                System.out.println("获取用户总数"+totalCount);
            pageSupport.setTotalCount(totalCount);
            //总共的页数
            int totalPageCount = pageSupport.getTotalPageCount();
            //控制首页和尾页
            //如果页数小于1,就显示第一页  页数大于 最后一页就 显示最后一页
            if(currentPageNo<1){
                currentPageNo =1;
            }else if(currentPageNo>totalPageCount){
                currentPageNo = totalPageCount;
            }
        System.out.println("返回UserList的数据测试"+queryUserName+":"+queryUserRole+":"+currentPageNo+":"+pageSize);
        //获取用户列表展示
            userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
            //将数据传给前端
        System.out.println(userList);
//        for (User user : userList) {
//            System.out.println(user.toString());
//        }
            req.setAttribute("userList",userList);

        RoleServiceImpl roleService = new RoleServiceImpl();
        //所有角色
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

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

并修改doGet方法

 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savePwd")){
            this.savePwd(req,resp);
        }else if(method.equals("pwdmodify")){
            this.verifyPwd(req,resp);
        }else if(method.equals("query")){
            this.query(req,resp);
        }
    }

5.7 用户管理模块 子模块—添加用户功能

5.7.1 :查看userlist.jsp

全网最细:十万字详解订单超市管理系统_第21张图片

5.7.2 :根据路径新建(导入)jsp文件 js文件

5.7.3 :思路

具体实现步骤
从底层开始写
dao层

 //用户管理模块中的 子模块—— 添加用户
    public abstract int addUser(Connection conn,User user)throws SQLException;

dao层实现类

 //用户管理模块中的 子模块—— 添加用户
    public  int addUser(Connection conn,User user)throws SQLException{
        PreparedStatement pstm = null;
        int updateRows = 0;
        if(conn != null){
            String sql = "insert into smbms_user (userCode,userName,userPassword,gender,birthday,phone,address,userRole,createdBy,creationDate)values(?,?,?,?,?,?,?,?,?,?)";
            Object[] params ={user.getUserRole(),user.getUserName(),user.getUserPassword(),user.getGender(),user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole(),user.getCreatedBy(),user.getCreateDate()};
            //执行sql 返回执行结果(成功的语句数量)
            updateRows= BaseDao.execute(conn,sql,pstm,params);
            //释放资源
            BaseDao.closeResource(null,pstm,null);
        }
        return updateRows;
    }

service层

//用户管理模块中的 子模块—— 添加用户
    public abstract int addUser(User user);

serviceImpl层 控制事务

 @Override
    public boolean addUser(User user) {
        Connection conn = null;
        boolean flag = false;
        try {
            //获取数据库连接
            conn = BaseDao.getConnection();
            //开启JDBC事务管理
            conn.setAutoCommit(false);
            //Service层调用dao层的方法添加用户
            int updateRows = userDao.addUser(conn, user);
            conn.commit();
            if(updateRows > 0){
                flag = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
        }finally {
            //释放连接
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

在可重用Servlet类中添加判断用户编码是否存在的方法

 //用户管理模块 子模块(验证用户编码是否已经存在)
    public void ifExist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取前端输入 的用户编码
        String userCode = req.getParameter("userCode");
        UserServiceImpl userService = new UserServiceImpl();
        User isNullUser = userService.login(userCode, "");
        //将结果存放在map集合中 让Ajax使用
        Map<String, String> resultMap = new HashMap<>();
        //判断是否已经存在这个用户编码
        boolean flag = isNullUser != null ? true : false;
        if(flag){
            //用户编码存在
            //将信息存入map中
             resultMap.put("userCode","exist");
        }
        //上面已经封装好 现在需要传给Ajax 格式为json 所以我们得转换格式
        resp.setContentType("application/json");//将应用的类型变成json
        PrintWriter writer = resp.getWriter();
        //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();

    }

并在doGet方法中判断是否调用执行 ifExist 方法

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savePwd")){
            this.savePwd(req,resp);
        }else if(method.equals("pwdmodify")){
            this.verifyPwd(req,resp);
        }else if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }else if(method.equals("getRoleList")){
            this.getRoleList(req,resp);
        }else if(method.equals("ifExist")){
            this.ifExist(req,resp);
        }
    }

5.8 用户管理模块 子模块—删除用户功能

5.8.1 查看userlist.jsp

<span><a class="deleteUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a></span>					

5.8.2 查看userlist.js

//用户管理页面上点击删除按钮弹出删除框(userlist.jsp)
function deleteUser(obj){
	$.ajax({
		type:"GET",
		url:path+"/jsp/user.do",
		data:{method:"deluser",uid:obj.attr("userid")},
		dataType:"json",
		success:function(data){
			if(data.delResult == "true"){//删除成功:移除删除行
				cancleBtn();
				obj.parents("tr").remove();
			}else if(data.delResult == "false"){//删除失败
				//alert("对不起,删除用户【"+obj.attr("username")+"】失败");
				changeDLGContent("对不起,删除用户【"+obj.attr("username")+"】失败");
			}else if(data.delResult == "notexist"){
				//alert("对不起,用户【"+obj.attr("username")+"】不存在");
				changeDLGContent("对不起,用户【"+obj.attr("username")+"】不存在");
			}
		},
		error:function(data){
			//alert("对不起,删除失败");
			changeDLGContent("对不起,删除失败");
		}
	});
}

思路 JSP调用 Ajax 调用 Servlet 调用 Service 调用 Dao 调用 jdbc
那么就从底层往上写

5.8.3 Dao层

 //用户管理模块中的子模块 —— 删除用户
    public abstract boolean deleteUser(Connection conn,int userId)throws SQLException;

5.8.4 Dao层实现类

 //用户管理模块中的子模块 —— 删除用户
    @Override
    public boolean deleteUser(Connection conn, int userCode)throws SQLException {
        PreparedStatement pstm = null;
        boolean flag = false;
        if(conn != null){
            String sql = "delete from smbms_user where id = ?";
            Object[] params = {userCode};
            //执行sql 返回执行结果(成功的语句数量)
            int updateRows= BaseDao.execute(conn,sql,pstm,params);
            if(updateRows>0){
                flag = true;
            }
            //释放资源
            BaseDao.closeResource(null,pstm,null);
        }
            return flag;
    }

5.8.5 Service层

//用户管理模块中的子模块 —— 删除用户
    public abstract boolean deleteUser(int userId);

5.8.6 Service层实现类 应开启事务

 //用户管理模块中的子模块 —— 删除用户
    @Override
    public boolean deleteUser(int userId) {
        boolean flag = false;
        Connection conn = null;
        try {
            //获取数据库连接
            conn = BaseDao.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            flag = userDao.deleteUser(conn, userId);
            //提交事务
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            //事务回滚
            conn.rollback();
        }finally {
            //释放连接
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

5.8.7 编写Servlet类的 删除用户功能

doGet方法添加

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savePwd")){
            this.savePwd(req,resp);
        }else if(method.equals("pwdmodify")){
            this.verifyPwd(req,resp);
        }else if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }else if(method.equals("getRoleList")){
            this.getRoleList(req,resp);
        }else if(method.equals("ifExist")){
            this.ifExist(req,resp);
        }else if(method.equals("delUser")){
            this.deleteUser(req,resp);
        }
    }

添加删除方法

//用户管理模块中的子模块 —— 删除用户
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //从前端获取 要删除的用户 的信息
        String userid = req.getParameter("uid");
        int delId = 0;
        //先转换
        try {
            delId= Integer.parseInt(userid);
        }catch (Exception e){
            e.printStackTrace();
            delId = 0;
        }
        //将结果存放在map集合中 让Ajax使用
        Map<String, String> resultMap = new HashMap<>();
        if(delId<=0){
            resultMap.put("delResult","notexist");
        }else {
            UserServiceImpl userService = new UserServiceImpl();
            if(userService.deleteUser(delId)){
                resultMap.put("delResult","true");
            }else {
                resultMap.put("delResult", "false");
            }
        }
        //上面已经封装好 现在需要传给Ajax 格式为json 所以我们得转换格式
        resp.setContentType("application/json");//将应用的类型变成json
        PrintWriter writer = resp.getWriter();
        //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

5.9 用户管理模块 子模块—修改用户信息功能

点击按钮 观察页面url地址

http://localhost:8080/smbms_war_exploded/jsp/user.do?method=modify&uid=20

查看js相关代码

$(".modifyUser").on("click",function(){
		var obj = $(this);
		window.location.href=path+"/jsp/user.do?method=modify&uid="+ obj.attr("userid");
	});

还是那一句话 : 功能从底层实现

5.9.1:Dao层

这里增加一个findById方法来查询 旧数据 并显示在修改的页面中

//根据用户id 查询用户信息
    public abstract User findById(Connection conn,int userId)throws SQLException;
    //用户管理模块中的子模块 —— 更改用户信息
    public abstract boolean modify(Connection conn,int id,User user)throws SQLException;

5.9.2:Dao层实现类

//根据用户 id查询用户信息
    @Override
    public User findById(Connection conn, int userId) throws SQLException {
        User user = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        if(conn != null){
            String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id = ? and u.userRole = r.id";
            Object[] params ={userId};
            rs = BaseDao.executeQuery(conn, sql, pstm, params, rs);
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                 user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreateDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
                user.setUserRoleName(rs.getString("userRoleName"));
            }
            //释放资源
            BaseDao.closeResource(null,pstm,rs);
        }
            return user;
    }

    //用户管理模块中的子模块 —— 更改用户信息
    @Override
    public boolean modify(Connection conn, int id,User user) throws SQLException {
        boolean flag = false;
        PreparedStatement pstm = null;
        if(conn != null){
            //编写sql语句
            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(),id};
            //执行sql语句
            int updateRows = BaseDao.execute(conn, sql, pstm, params);
            if(updateRows>0){
                flag = true;
            }
            //释放连接
            BaseDao.closeResource(null,pstm,null);
        }
            return flag;
    }

5.9.3:Service层

 //根据id查询用户信息
    public abstract User findById(int userId);
    //用户管理模块中的子模块 —— 更改用户信息
    public abstract boolean modify(int id,User user);

5.9.4:Service层实现类

 //根据id查询用户信息
    @Override
    public User findById(int userId) {
        User user = null;
        Connection conn = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            user = userDao.findById(conn, userId);
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }

        }finally {
            BaseDao.closeResource(conn,null,null);
            return user;
        }
    }

    //用户管理模块中的子模块 —— 更改用户信息
    @Override
    public boolean modify(int id,User user) {
        Connection conn = null;
        boolean flag = false;
        try {
            conn = BaseDao.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            flag = userDao.modify(conn, id,user);
            //提交事务
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            //事务回滚
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            //释放资源
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

5.9.5:Servlet层

//用户管理模块中的功能 —— 根据id查询用户信息
    public void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取 要修改的用户 的id
        String uId = req.getParameter("uid");
        int userId = 0;
        try {
            userId = Integer.parseInt(uId);
        }catch (Exception e){
            e.printStackTrace();
        }
        UserServiceImpl userService = new UserServiceImpl();
        //查询要更改的用户信息
        User user = userService.findById(userId);
        //将用户信息保存至 request中 让usermodify.jsp显示
        req.setAttribute("user",user);
        req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
    }
    //用户管理模块中的子模块 —— 更改用户信息 
    public void modify(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //从前端获取 要修改的用户 的id
        String uId = req.getParameter("uid");
        int userId = 0;
        try {
            userId = Integer.parseInt(uId);
        }catch (Exception e){
            e.printStackTrace();
        }
        //从修改信息的表单中封装信息
        User user = new User();
        user.setUserName(req.getParameter("userName"));
        user.setGender(Integer.parseInt(req.getParameter("gender")));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("birthday")));
        }catch (ParseException e){
            e.printStackTrace();
        }
        user.setPhone(req.getParameter("phone"));
        user.setAddress(req.getParameter("address"));
        user.setUserRole(Integer.parseInt(req.getParameter("userRole")));
        //注意这两个参数不在表单的填写范围内
        user.setModifyDate(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.ModifyDate(new Date());

        UserServiceImpl userService = new UserServiceImpl();
        if(userService.modify(userId,user)){
            //如果执行成功了 网页重定向到 用户管理页面(即 查询全部用户列表)
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else{
            //说明 添加失败 转发到此 添加页面
            req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
        }
    }

同时doGet方法新增全网最细:十万字详解订单超市管理系统_第22张图片

6.0 用户管理模块 子模块—查看用户信息功能

点击查看 用户信息按钮 观察URL 他还是走的Servlet请求
思路 根据id查询用户信息 再发送到前端页面展示
在这里插入图片描述

编写Servlet

//用户管理模块中的子模块 —— 查询用户信息
    public void viewUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取 要查询用户 的id
        String id = req.getParameter("uid");
        int userId = 0;
        try {
            userId = Integer.parseInt(id);
        }catch (Exception e){
            e.printStackTrace();
            userId = 0;
        }
        //调用 根据id查询用户信息的方法
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.findById(userId);
        //将此user发送到展示前端 的页面进行展示
        req.setAttribute("user",user);
        //跳转到前端 的展示页面
        req.getRequestDispatcher("userview.jsp").forward(req,resp);
    }

并修改doGet方法
全网最细:十万字详解订单超市管理系统_第23张图片

六:供应商管理

6.1建立供应商Servlet

在Servlet包下新建Provider包 并在包中新建ProviderServlet
全网最细:十万字详解订单超市管理系统_第24张图片

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ProviderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

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

还是那句话 : 有Servlet就得先注册 以防待会忘记注册(在web.xml中)


    <servlet>
        <servlet-name>ProviderServletservlet-name>
        <servlet-class>com.csnz.servlet.Provider.ProviderServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>ProviderServletservlet-name>
        <url-pattern>/jsp/provider.dourl-pattern>
    servlet-mapping>

我们可以根据 URL 来看看供应商管理页面长啥样

http://localhost:8080/smbms_war_exploded/jsp/provider.do?method=query

根据参数修改ProviderServlet

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ProviderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //查询 供应商 列表的方法
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //返回前端页面展示
        req.getRequestDispatcher("providerlist.jsp").forward(req,resp);
    }
}

全网最细:十万字详解订单超市管理系统_第25张图片
可以看到目前 页面的框架 只是还没有值显示
接下来就和用户管理页面差不多的操作啦!

6.2 建相关的包

6.2.1 新建ProviderDao层 及 ProviderDao的实现类

全网最细:十万字详解订单超市管理系统_第26张图片
ProviderDao接口

public interface ProviderDao {
}

ProviderDaoImpl实现类

public class ProviderDaoImpl implements ProviderDao {
}

6.2.2 新建Service层 及实现类

全网最细:十万字详解订单超市管理系统_第27张图片
ProviderService接口

public interface ProviderService {
}

ProviderServiceImpl实现类

public class ProviderServiceImpl implements ProviderService {
}

6.3 把数据展示在页面上 先实现 查询供应商列表数据功能

还是那句话:从底层往上写
因为涉及到分页 所以我们还需编写一个
根据供应商编码 或 供应商名称 查询供应商总数的方法

6.3.1 ProviderDao层

 //根据供应商编码 或 供应商名称 查询供应商总数
    public abstract int getProviderCounts(Connection conn,String queryProCode,String queryProName)throws SQLException;

    //查询供应商数据列表
    public abstract List<Provider> getProviderList(Connection conn,String ProCode,String ProName,int currentPageNo, int pageSize)throws SQLException;

6.3.2 ProviderDaoImpl层

 @Override
    public int getProviderCounts(Connection conn, String queryProCode, String queryProName) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        int ProviderCounts = 0;
        if(conn != null){
            //使用字符拼接的方式生成sql语句
            StringBuffer sql = new StringBuffer();
            sql.append("select count(1) as ProviderCount from smbms_provider");

            //参数列表
            ArrayList<Object> paramsList = new ArrayList<>();

            //判断是否有2个参数 如果有就得加and
            if(queryProCode != "" && queryProName != ""){
                sql.append(" where ProCode = ? and ProName like ?");
                paramsList.add(queryProCode);
                paramsList.add("%"+queryProName+"%");
            }else if(queryProCode !="" || queryProName != ""){
                sql.append(" where");
                if(queryProCode != ""){
                    sql.append(" ProCode = ?");
                    paramsList.add(queryProCode);
                }
                if(queryProName != ""){
                    sql.append(" ProName like ?");
                    paramsList.add("%"+queryProName+"%");
                }
            }
            //sql拼接完成
            System.out.println("Test ProviderDaoImpl -> "+sql.toString());
            //参数列表转换
            Object[] params = paramsList.toArray();
            //执行sql
            rs = BaseDao.executeQuery(conn, sql.toString(), pstm, params,rs);
            //遍历结果集
            while (rs.next()){
                ProviderCounts = rs.getInt("ProviderCount");
            }
            //释放资源
            BaseDao.closeResource(null,pstm,rs);
        }
        System.out.println("ProviderDaoImpl-> ProviderCounts:"+ProviderCounts);
            return ProviderCounts;
    }

    @Override
    public List<Provider> getProviderList(Connection conn, String ProCode, String ProName,int currentPageNo, int pageSize) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs  = null;
        List<Provider> providers = new ArrayList<Provider>();
        if(conn != null){
            //供应商无需连表查询 sql需拼接参数
            StringBuffer sql = new StringBuffer();
            sql.append("select * from smbms_provider");
            //建一个参数列表 注意这里泛型使用Object
            List<Object> paramsList = new ArrayList<>();
            //SQL语句拼接  参数赋值
            // 如果两个都不为空 sql需要拼接and
            if(ProCode != "" && ProName != ""){
                sql.append(" where ProCode = ? and ProName like ?");
                paramsList.add(ProCode);
                paramsList.add("%"+ProName+"%");
            }else if(ProCode != "" || ProName != ""){
                sql.append(" where");
                if(ProCode != ""){
                    sql.append(" ProCode = ?");
                    paramsList.add(ProCode);
                }
                if(ProName != ""){
                    sql.append(" ProName like ?");
                    paramsList.add("%"+ProName+"%");
                }
            }
            //在数据库中 分页使用limit startIndex,pageSize 总数
            //当前页 = (当前页-1)*页面大小
            sql.append(" order by creationDate DESC limit ?,?");
            currentPageNo = (currentPageNo-1)*pageSize;
            paramsList.add(currentPageNo);
            paramsList.add(pageSize);

            //将参数列表进行转换
            Object[] params = paramsList.toArray();
        System.out.println("Test getProviderList ->  "+sql);
            //执行sql
            rs = BaseDao.executeQuery(conn, sql.toString(), pstm, params,rs);
            //遍历结果集 封装到一个供应商中
            while (rs.next()){
                Provider provider = new Provider();
                provider.setId(rs.getInt("id"));
                provider.setProCode(rs.getString("proCode"));
                provider.setProName(rs.getString("proName"));
                provider.setProDesc(rs.getString("proDesc"));
                provider.setProContact(rs.getString("proContact"));
                provider.setProPhone(rs.getString("proPhone"));
                provider.setProAddress(rs.getString("proAddress"));
                provider.setProFax(rs.getString("proFax"));
                provider.setCreatedBy(rs.getInt("createdBy"));
                provider.setCreationDate(rs.getTimestamp("creationDate"));
                provider.setModifyDate(rs.getTimestamp("modifyDate"));
                provider.setModifyBy(rs.getInt("modifyBy"));
                //将此供应商信息添加至 列表
                providers.add(provider);
            }
            //释放资源
            BaseDao.closeResource(null,pstm,rs);

        }
            return providers;
    }

6.3.3 ProviderService层

//根据供应商编码 或 供应商名称 查询供应商总数
    public abstract int getProviderCounts(String queryProCode,String queryProName)throws SQLException;

    //查询供应商数据列表
    public abstract List<Provider> getProviderList(String ProCode, String ProName, int currentPageNo, int pageSize)throws SQLException;

6.3.4 ProviderServiceImpl层

import com.csnz.dao.BaseDao;
import com.csnz.dao.Provider.ProviderDao;
import com.csnz.dao.Provider.ProviderDaoImpl;
import com.csnz.pojo.Provider;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class ProviderServiceImpl implements ProviderService {
    //Service层调用dao层
    private ProviderDao providerDao;
    public ProviderServiceImpl(){
        providerDao = new ProviderDaoImpl();
    }

    //根据供应商编码 或 供应商名称 查询供应商总数
    @Override
    public int getProviderCounts(String queryProCode, String queryProName) throws SQLException {
        Connection conn = null;
        int providerCounts = 0;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            providerCounts = providerDao.getProviderCounts(conn, queryProCode, queryProName);
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return providerCounts;
        }
    }

    @Override
    public List<Provider> getProviderList(String ProCode, String ProName, int currentPageNo, int pageSize) throws SQLException {
        List<Provider> providerList = null;
        Connection conn = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            providerList = providerDao.getProviderList(conn, ProCode, ProName, currentPageNo, pageSize);
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return providerList;
        }
    }
}

6.3.5 完善ProviderServlet层 的query方法

//查询 供应商 列表的方法
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        //从providerlist.jsp中获取传来的数据
        String queryProCode = req.getParameter("queryProCode");
        String queryProName = req.getParameter("queryProName");
        String pageIndex = req.getParameter("pageIndex");
        List<Provider> providerList = null;
        int currentPageNo = 1;
        int pageSize = 5;
        //还需判断前端传来的数据是否为空
        if (queryProCode == null) {
            queryProCode = "";
        }
        if (queryProName == null ){
            queryProName = "";
        }
        if(pageIndex!=null){
            currentPageNo = Integer.parseInt(pageIndex);
        }
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        //获取符合条件的 信息数量
        int providerCounts = providerService.getProviderCounts(queryProCode, queryProName);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
    System.out.println("currentPageNo:"+currentPageNo);
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
    System.out.println("providerCounts:"+providerCounts);
        pageSupport.setTotalCount(providerCounts);
        //总共的页数
        int totalPageCount = pageSupport.getTotalPageCount();
        //总记录数
        int totalCount = pageSupport.getTotalCount();
        //控制首页和尾页
        //如果页数小于1,就显示第一页  页数大于 最后一页就 显示最后一页
        if(currentPageNo<1){
            currentPageNo =1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo = totalPageCount;
        }

        //获取符合条件的 信息
        providerList= providerService.getProviderList(queryProCode, queryProName, currentPageNo, pageSize);
        //将信息存入requset 使得在前端展示
        req.setAttribute("providerList",providerList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryProCode",queryProCode);
        req.setAttribute("queryProName",queryProName);
        //返回前端页面展示
        req.getRequestDispatcher("providerlist.jsp").forward(req,resp);
    }

如果你已经写到这里 那么恭喜你 你又完成了一大步 运行服务器展示页面
全网最细:十万字详解订单超市管理系统_第28张图片

6.4 实现添加供应商功能

查看providerlist.jsp
全网最细:十万字详解订单超市管理系统_第29张图片
发现此功能进入provideradd.jsp 于是乎
嘿嘿嘿~ 我们直接进入这个JSP文件查看
发现表单提交的路径

  <form id="providerForm" name="providerForm" method="post" action="${pageContext.request.contextPath }/jsp/provider.do">
			<input type="hidden" name="method" value="add">

接下来 还是那句老话…功能(add)从底层开始实现

6.4.1 编写Dao层

 //添加供应商的方法
    public abstract boolean addProvider(Connection conn,Provider provider)throws SQLException;

6.4.2编写Dao层实现类

 //添加供应商的方法
    @Override
    public boolean addProvider(Connection conn, Provider provider) throws SQLException {
        PreparedStatement pstm = null;
        boolean flag = false;
        if(conn != null){
            //如果连接数据库成功 编写sql语句
          String sql = "insert into smbms_provider (proCode,proName,proContact,proPhone,proAddress,proFax,proDesc,createdBy,creationDate)values(?,?,?,?,?,?,?,?,?)";
            Object[] params ={provider.getProCode(),provider.getProName(),provider.getProContact(),provider.getProPhone(),provider.getProAddress(),provider.getProFax(),provider.getProDesc(),provider.getCreatedBy(),provider.getCreationDate()};
            
            //执行sql语句
            if(BaseDao.execute(conn, sql, pstm, params)>0){
                flag = true;
            }
            //释放资源
            BaseDao.closeResource(null,pstm,null);
        }
            return flag;
    }

6.4.3 编写Service层

//添加供应商的方法
    public abstract boolean addProvider(Provider provider)throws SQLException;

6.4.4 编写ServiceImpl层

//添加供应商的方法
    @Override
    public boolean addProvider(Provider provider) {
        Connection conn = null;
        boolean flag = false;
        try {
            //获取数据库连接
            conn = BaseDao.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            //执行方法
            flag = providerDao.addProvider(conn, provider);
            //提交事务
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            //事务回滚
            conn.rollback();
        }finally {
            //释放资源
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

6.4.5 编写Servlet类 的add方法

//添加 供应商方法
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //从前端 获取供应商的信息
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");
		 //下面的参数自己获取
        int createdBy = ((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId();

        //将信息封装成一个供应商对象
        Provider provider = new Provider();
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProAddress(proAddress);
        provider.setProFax(proFax);
        provider.setProDesc(proDesc);
        provider.setCreatedBy(createdBy);
        provider.setCreationDate(new Date());
        //调用service层方法
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        boolean flag = providerService.addProvider(provider);
        //如果成功 则重定向到providerlist.jsp页面
        if(flag){
            resp.sendRedirect(req.getContextPath()+"/jsp/provider.do?method=query");
        }else{
            //失败 跳转到添加页面
            req.getRequestDispatcher("provideradd.jsp").forward(req,resp);
        }

    }

记得在doGet方法调用

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }
    }

6.5 实现 供应商管理 — 删除功能

Dao层

	//删除供应商的方法
    public abstract boolean deleteProvider(Connection conn,int providerId)throws SQLException;

Dao层实现类

 //删除供应商的方法
    @Override
    public boolean deleteProvider(Connection conn, int providerId) throws SQLException {
        PreparedStatement pstm = null;
        boolean flag = false;
        //如果连接不为空
        if(conn != null){
            //写sql
            String sql = "delete from smbms_provider where id = ?";
            //参数列表
            Object[] params = {providerId};
            //执行sql
            int updateRows = BaseDao.execute(conn, sql, pstm, params);
            if(updateRows > 0){
                flag = true;
            }
            //释放资源
            BaseDao.closeResource(null,pstm,null);
        }
            return flag;
    }

Service层

//删除供应商的方法
    public abstract boolean deleteProvider(int providerId)throws SQLException;

Service层实现类

//删除供应商的方法
    @Override
    public boolean deleteProvider(int providerId) {
        Connection conn = null;
        boolean flag = false;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            flag = providerDao.deleteProvider(conn, providerId);
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

添加Servlet类的删除供应商方法

//删除供应商的方法
    public void deleteProvider(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //从前端获取 要删除的供应商 的id
        String proid = req.getParameter("proid");
        int id = 0;
        try {
            id = Integer.parseInt(proid);
        }catch (Exception e){
            e.printStackTrace();
            id = 0;
        }
        //将信息存入一个map集合中 传给ajax
        HashMap<Object, Object> resultMap = new HashMap<>();
        if(id<=0){
            resultMap.put("delResult","notexist");
        }else{
            ProviderServiceImpl providerService = new ProviderServiceImpl();
            if(providerService.deleteProvider(id)){
                //如果删除成功
                resultMap.put("delResult","true");
            }else{
                resultMap.put("delResult","false");
            }
        }
        //将此map集合转换成json格式传递
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式
        out.write(JSONArray.toJSONString(resultMap));
        out.flush();
        out.close();
    }

修改doGet方法

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }else if(method.equals("delprovider")){
            this.deleteProvider(req,resp);
        }
    }

6.6 实现 供应商管理 — 修改功能

点击按钮 观察URL变化

http://localhost:8080/smbms_war_exploded/jsp/provider.do?method=modify&proid=17

查看js对应的代码

$(".modifyProvider").on("click",function(){
		var obj = $(this);
		window.location.href=path+"/jsp/provider.do?method=modify&proid="+ obj.attr("proid");
	});

思路 : 我们点击修改按钮 跳转到修改信息页面 并显示旧信息
所以我们需先定义一个根据id查询用户信息的方法
当点击修改按钮时先调用 根据id查询供应商信息的方法
将信息在页面中展示出来
点击修改信息页面的保存按钮 再对信息进行修改
总结一句话:先查询展示 再修改保存

Dao层

//根据供应商id查询供应商信息的方法
    public abstract Provider findById(Connection conn,int providerId)throws SQLException;

Dao层实现类

 //根据供应商id查询供应商信息的方法
    @Override
    public Provider findById(Connection conn, int providerId) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        Provider provider = null;
        //如果连接不为空
        if(conn != null){
            //编写sql语句
            String sql = "select * from smbms_provider where id = ?";
            //参数列表
            Object[] params = {providerId};
            //执行sql
            rs = BaseDao.executeQuery(conn, sql, pstm, params, rs);
            //遍历结果集 封装
            if(rs.next()){
                provider = new Provider();
                provider.setProCode(rs.getString("proCode"));;
                provider.setProName(rs.getString("proName"));
                provider.setProDesc(rs.getString("proDesc"));
                provider.setProContact(rs.getString("proContact"));
                provider.setProPhone(rs.getString("proPhone"));
                provider.setProAddress(rs.getString("proAddress"));
                provider.setProFax(rs.getString("proFax"));
                provider.setCreatedBy(rs.getInt("createdBy"));
                provider.setCreationDate(rs.getTimestamp("creationDate"));
                provider.setModifyDate(rs.getTimestamp("modifyDate"));
                provider.setModifyBy(rs.getInt("modifyBy"));
            }
            //释放资源
            BaseDao.closeResource(null,pstm,rs);
        }
            return provider;
    }

Service层

//根据供应商id查询供应商信息的方法
    public abstract Provider findById(int providerId)throws SQLException;

Service层实现类

//根据供应商id查询供应商信息的方法
    @Override
    public Provider findById(int providerId)  {
        Connection conn = null;
        Provider provider = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            provider = providerDao.findById(conn, providerId);
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return provider;
        }
    }

Servlet层 findById方法

//根据id查询供应商信息的方法
    public void findById(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取id
        String proid = req.getParameter("proid");
        int id = 0;
        try {
            id = Integer.parseInt(proid);
        }catch (Exception e){
            e.printStackTrace();
            id = 0;
        }
       if(id>0){
           ProviderServiceImpl providerService = new ProviderServiceImpl();
           Provider provider = providerService.findById(id);
           //设置id 让修改提交时可获取
           provider.setId(id);
           //将供应商信息存至 req
           req.setAttribute("provider",provider);
           //返回至前端展示页面
           req.getRequestDispatcher("providermodify.jsp").forward(req,resp);
       }
    }

记得修改doGet方法

	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }else if(method.equals("delprovider")){
            this.deleteProvider(req,resp);
        }else if(method.equals("modify")){
            this.findById(req,resp);
        }
    }

点击修改页面 正常显示 旧数据
全网最细:十万字详解订单超市管理系统_第30张图片
接下来实现保存修改的方法

Dao层

 //修改供应商信息方法
    public abstract boolean modifyProvider(Connection conn,int id,Provider provider)throws SQLException;

Dao层实现类

//修改供应商信息方法
    @Override
    public boolean modifyProvider(Connection conn, int id,Provider provider) throws SQLException {
        PreparedStatement pstm = null;
        boolean flag = false;
        if(conn != null){
            //编写sql语句
            String sql = "update smbms_provider set proCode = ?,proName = ?,proDesc = ?,proContact = ?,proPhone = ?,proAddress = ?,proFax = ?,modifyDate = ?,modifyBy = ? where id = ?";
            Object[] params = {provider.getProCode(),provider.getProName(),provider.getProDesc(),provider.getProContact(),provider.getProPhone(),provider.getProAddress(),provider.getProFax(),provider.getModifyDate(),provider.getModifyBy(),id};
            
            int updateRows = BaseDao.execute(conn, sql, pstm, params);
            if(updateRows > 0){
                flag = true;
            }
            BaseDao.closeResource(null,pstm,null);
        }
            return flag;
    }

Service层

  //修改供应商信息方法
    public abstract boolean modifyProvider(int id,Provider provider)throws SQLException;

Service层实现类

//修改供应商信息方法
    @Override
    public boolean modifyProvider(int id, Provider provider)  {
        Connection conn  =  null;
        boolean flag = false;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            flag = providerDao.modifyProvider(conn, id, provider);
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

Servlet类添加 修改方法

//修改供应商信息方法
    public void modify(HttpServletRequest req,HttpServletResponse resp) throws  IOException, ServletException {
        System.out.println("enter modify ...");
        //从前端获取 要修改的供应商的id信息
        String proId =  req.getParameter("proid");
        System.out.println("proId : ->"+proId.toString());
        int id = 0;
        try {
            id = Integer.parseInt(proId);
        }catch (Exception e){
            e.printStackTrace();
            id = 0;
        }
        //从前端获取供应商信息
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");
        //封装成一个对象
        Provider provider = new Provider();
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProAddress(proAddress);
        provider.setProFax(proFax);
        provider.setProDesc(proDesc);
        //下面的参数不是由前端传来的
        provider.setModifyDate(new Date());
        provider.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        if(id>0){
            //执行更改
            ProviderServiceImpl providerService = new ProviderServiceImpl();
            if(providerService.modifyProvider(id, provider)){
                //如果修改成功 重定向到展示供应商列表页面
                resp.sendRedirect(req.getContextPath()+"/jsp/provider.do?method=query");
            }else{
                //修改失败 转发到此修改页面
                req.getRequestDispatcher("providermodify.jsp").forward(req,resp);
            }
        }
    }

并修改doGet方法

 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }else if(method.equals("delprovider")){
            this.deleteProvider(req,resp);
        }else if(method.equals("modify")){
            this.findById(req,resp);
        }else if(method.equals("modifyexe")){
            this.modify(req,resp);
        }
    }

至此 供应商管理 — 修改功能 完成!!!

6.7 实现 供应商管理 — 查看功能

先查看js代码

$(".viewProvider").on("click",function(){
		//将被绑定的元素(a)转换成jquery对象,可以使用jquery方法
		var obj = $(this);
		window.location.href=path+"/jsp/provider.do?method=view&proid="+ obj.attr("proid");
	});

查看providerview.jsp页面 发现我们需要传入一个provider对象给他
所以我们可以 获取id 并查找此供应商的信息 并传入数据展示页面

//查看 供应商信息方法
    public void view(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取供应商的id
        String proid = req.getParameter("proid");
        int id = 0;
        try {
            id = Integer.parseInt(proid);
        }catch (Exception e){
            e.printStackTrace();
            id = 0 ;
        }
        //根据id查询
        if(id >0){
            ProviderServiceImpl providerService = new ProviderServiceImpl();
            Provider provider = providerService.findById(id);
            //将此对象传到providerview.jsp进行展示
            req.setAttribute("provider",provider);
            //重定向到展示页
            req.getRequestDispatcher("providerview.jsp").forward(req,resp);
        }
    }

并修改 doGet方法

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }else if(method.equals("delprovider")){
            this.deleteProvider(req,resp);
        }else if(method.equals("modify")){
            this.findById(req,resp);
        }else if(method.equals("modifyexe")){
            this.modify(req,resp);
        }else if(method.equals("view")){
            this.view(req,resp);
        }
    }

7 订单管理

查看head.jsp

<li ><a href="${pageContext.request.contextPath}/jsp/bill.do?method=query">订单管理</a></li>

思路:
先写一个订单的Servlet 对应的映射路径为/jsp/bill.do
全网最细:十万字详解订单超市管理系统_第31张图片
BillServlet

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class BillServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //查询订单管理列表
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("enter BillList query method...");
        //返回前端页面查看
        req.getRequestDispatcher("billlist.jsp").forward(req,resp);
    }
}

写完BillServlet类记得注册


    <servlet>
        <servlet-name>BillServletservlet-name>
        <servlet-class>com.csnz.servlet.Bill.BillServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>BillServletservlet-name>
        <url-pattern>/jsp/bill.dourl-pattern>
    servlet-mapping>

ok 先尝试访问此页面

全网最细:十万字详解订单超市管理系统_第32张图片
页面成功显示 接下来 实现 查询订单管理的列表
从底层往上写

7.1 建相关的包结构

全网最细:十万字详解订单超市管理系统_第33张图片

7.2.1 Dao层

//根据 商品名称、供应商id、是否付款 查询订单总数
    public abstract int getBillCount(Connection conn,String queryProductName,int queryProviderId,int queryIsPayment)throws  SQLException;
    //根据 商品名称、供应商id、是否付款 查询订单列表
    public abstract List<Bill> getBillList(Connection conn,String queryProductName,int queryProviderId,int queryIsPayment, int currentPageNo, int pageSize) throws SQLException;

7.2.2 Dao层实现类

//根据 商品名称、供应商id、是否付款 查询订单总数
    @Override
    public int getBillCount(Connection conn, String queryProductName, int queryProviderId, int queryIsPayment) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet  rs = null;
        int count = 0;
        if(conn != null){
            StringBuffer sql = new StringBuffer();
            sql.append("select count(1) as count from smbms_bill b,smbms_provider p where b.providerId = p.id");
            List<Object> paramsList = new ArrayList<>();
            if(queryProductName != "") {
                sql.append(" and productName like ?");
                paramsList.add("%"+queryProductName+"%");
            }
            if(queryProviderId != 0){
                sql.append(" and providerId = ?");
                paramsList.add(queryProviderId);
            }
            if(queryIsPayment != 0){
                sql.append(" and isPayment = ?");
                paramsList.add(queryIsPayment);
            }
            Object[] params = paramsList.toArray();
            rs = BaseDao.executeQuery(conn, sql.toString(), pstm, params, rs);
            //遍历结果集 从结果集中取出数量count
            if (rs.next()){
                count = rs.getInt("count");
            }
            //关闭资源
            BaseDao.closeResource(null,pstm,rs);
        }
            return count;
        }


    //根据 商品名称、供应商id、是否付款 查询订单列表
    @Override
    public List<Bill> getBillList(Connection conn, String queryProductName, int queryProviderId, int queryIsPayment, int currentPageNo, int pageSize) throws SQLException {
        PreparedStatement pstm  = null;
        ResultSet rs = null;
        List<Bill> bills = new ArrayList<>();
        if(conn != null){
            System.out.println("enter BillDaoImpl...");
            //动态拼接字符串
            StringBuffer sql = new StringBuffer();
            //参数列表
            ArrayList<Object> paramsList = new ArrayList<>();
            sql.append("select b.*,p.proName as proName from smbms_bill b,smbms_provider p where b.providerId = p.id");
            if(queryProductName != "" && queryProviderId != 0 && queryIsPayment != 0){
                //说明三个参数都不为空
                sql.append(" and productName like ? and providerId = ? and isPayment = ?");
                paramsList.add("%"+queryProductName+"%");
                try {
                    paramsList.add(queryProviderId);
                    paramsList.add(queryIsPayment);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else if(queryProductName != "" || queryProviderId != 0 || queryIsPayment != 0){
                //说明三个参数有些不为空
                if(queryProductName != ""){
                    sql.append(" and productName like ?");
                    paramsList.add("%"+queryProductName+"%");
                }
                if(queryProviderId != 0){
                    sql.append(" and providerId = ?");
                    paramsList.add(queryProviderId);
                }
                if(queryIsPayment != 0){
                    sql.append(" and isPayment = ?");
                    paramsList.add(queryIsPayment);
                }

            }
            //在数据库中 分页使用limit startIndex,pageSize 总数
            //当前页 = (当前页-1)*页面大小
            sql.append(" order by b.creationDate DESC limit ?,?");
            currentPageNo = (currentPageNo-1)*pageSize;
            paramsList.add(currentPageNo);
            paramsList.add(pageSize);
            //sql拼接完成 参数列表也正确
            System.out.println("Test SQL --> "+sql.toString());
            //将参数列表进行转换
            Object[] params = paramsList.toArray();
            //执行sql
            rs = BaseDao.executeQuery(conn, sql.toString(), pstm, params, rs);
            //遍历结果集 封装对象 添加到列表
            while (rs.next()){
                Bill bill = new Bill();
                bill.setId(rs.getInt("id"));
                bill.setBillCode(rs.getString("billCode"));
                bill.setProductName(rs.getString("productName"));
                bill.setProductDesc(rs.getString("productDesc"));
                bill.setProductUnit(rs.getString("productUnit"));
                bill.setProductCount(rs.getBigDecimal("productCount"));
                bill.setTotalPrice(rs.getBigDecimal("totalPrice"));
                bill.setIsPayment(rs.getInt("isPayment"));
                bill.setCreatedBy(rs.getInt("createdBy"));
                bill.setCreationDate(rs.getTimestamp("creationDate"));
                bill.setModifyBy(rs.getInt("modifyBy"));
                bill.setModifyDate(rs.getTimestamp("modifyDate"));
                bill.setProviderId(rs.getInt("providerId"));
                bill.setProviderName(rs.getString("proName"));
                bills.add(bill);
            }
                    //关闭资源
                    BaseDao.closeResource(null,pstm,rs);
        }
                    //返回列表
                    return bills;
    }

7.2.3 Service层

//根据 商品名称、供应商id、是否付款 查询订单总数
    public abstract int getBillCount(String queryProductName, int queryProviderId, int queryIsPayment) throws SQLException;
    //根据 商品名称、供应商id、是否付款 查询订单列表
    public abstract List<Bill> getBillList(String queryProductName, int queryProviderId, int queryIsPayment, int currentPageNo, int pageSize) throws SQLException;

7.2.4 Service层实现类

import com.csnz.dao.BaseDao;
import com.csnz.dao.Bill.BillDaoImpl;
import com.csnz.pojo.Bill;
import java.sql.Connection;
import java.util.List;

public class BillServiceImpl implements BillService {
    private BillDaoImpl billDao;
    public BillServiceImpl(){
        this.billDao = new BillDaoImpl();
    }

    //根据 商品名称、供应商id、是否付款 查询订单总数
    @Override
    public int getBillCount(String queryProductName, int queryProviderId, int queryIsPayment) {
        Connection conn = null;
        int billCount = 0;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            billCount = billDao.getBillCount(conn, queryProductName, queryProviderId, queryIsPayment);
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return billCount;
        }
    }

    //根据 商品名称、供应商id、是否付款 查询订单列表
    @Override
    public List<Bill> getBillList(String queryProductName, int queryProviderId, int queryIsPayment, int currentPageNo, int pageSize) {
        Connection conn = null;
        List<Bill> billList = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            System.out.println("enter getBillList...");
            billList = billDao.getBillList(conn, queryProductName, queryProviderId, queryIsPayment,currentPageNo,pageSize);
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return billList;
        }
    }
}

7.2.5 Servlet层

import com.csnz.pojo.Bill;
import com.csnz.pojo.Provider;
import com.csnz.service.Bill.BillServiceImpl;
import com.csnz.service.Provider.ProviderServiceImpl;
import com.csnz.util.PageSupport;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class BillServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //查询订单管理列表
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("enter BillList query method...");
        //从前端获取搜素信息
        String queryProductName = req.getParameter("queryProductName");
        String queryProviderId = req.getParameter("queryProviderId");
        String queryIsPayment = req.getParameter("queryIsPayment");

        int proId = 0;
        int isPayment = 0;
        //此属性在搜素按钮那
        String pageIndex = req.getParameter("pageIndex");
        //设置当前页 以及 每页显示的数目
        int currentPageNo = 1;
        int pageSize = 5;

        /*测试*/
        System.out.println("queryProductName - > "+queryProductName);
        System.out.println("queryProviderId - > "+queryProviderId);
        System.out.println("queryIsPayment - > "+queryIsPayment);
        //对前端传来的属性进行判断 如果为空(没输入) 则将值赋空字符串 dao层实现类判断的时候 也得根据空字符串判断
        if (queryProductName == null){
            queryProductName = "";
        }
        if(queryProviderId != null ){
            proId = Integer.parseInt(queryProviderId);
        }
        if(queryIsPayment != null ){
            isPayment = Integer.parseInt(queryIsPayment);
        }
        if(pageIndex!=null){
            currentPageNo = Integer.parseInt(pageIndex);
        }
        //Servlet层调用service层
        BillServiceImpl billService = new BillServiceImpl();
        //获取订单总数 分页:上一页 下一页
        int totalCount = billService.getBillCount(queryProductName,proId,isPayment);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        System.out.println("当前页:"+currentPageNo);
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        System.out.println("获取订单总数"+totalCount);
        pageSupport.setTotalCount(totalCount);
        //总共的页数
        int totalPageCount = pageSupport.getTotalPageCount();
        //控制首页和尾页
        //如果页数小于1,就显示第一页  页数大于 最后一页就 显示最后一页
        if(currentPageNo<1){
            currentPageNo =1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo = totalPageCount;
        }

        //根据前端搜索框信息 查询订单列表
        List<Bill> billList = billService.getBillList(queryProductName, proId, isPayment,currentPageNo,pageSize);
        System.out.println("Test billList -> "+billList);
        //将此列表存入req中 供前端展示
        req.setAttribute("billList",billList);
        //查询供应商列表
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        int totalNum = providerService.getProviderCounts("","");
        List<Provider> providerList = providerService.getProviderList("", "", 1, totalNum);
        //将此供应商列表存入req中 为了使我们搜索框搜素内容不清空
        req.setAttribute("providerList",providerList);
        req.setAttribute("queryProductName",queryProductName);
        req.setAttribute("queryProviderId",proId);
        req.setAttribute("queryIsPayment",isPayment);
        //分页显示数据
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        //返回前端页面查看
        req.getRequestDispatcher("billlist.jsp").forward(req,resp);
    }
}

大功告成
全网最细:十万字详解订单超市管理系统_第34张图片

7.3实现添加订单功能

查看billadd.jsp

 <form id="billForm" name="billForm" method="post" action="${pageContext.request.contextPath }/jsp/bill.do">
<input type="hidden" name="method" value="add">

所以我们知道他走的是add方法
还是从底层往上写

7.3.1 Dao层

    //添加订单
    public abstract boolean addBill(Connection conn,Bill bill)throws SQLException;

7.3.2 Dao层实现类

 //添加订单
    @Override
    public boolean addBill(Connection conn, Bill bill) throws SQLException {
        PreparedStatement pstm = null;
        boolean flag  = false;
        if (conn != null){
            String sql = "insert into smbms_bill (billCode,productName,productDesc,productUnit,productCount,totalPrice,isPayment,createdBy,creationDate,providerId)values(?,?,?,?,?,?,?,?,?,?)" ;
            Object[] params = {bill.getBillCode(),bill.getProductName(),bill.getProductDesc(),bill.getProductUnit(),bill.getProductCount(),bill.getTotalPrice(),bill.getIsPayment(),bill.getCreatedBy(),bill.getCreationDate(),bill.getProviderId()};
            int updateRows = BaseDao.execute(conn, sql, pstm, params);
            if(updateRows > 0){
                flag = true;
            }
            BaseDao.closeResource(null,pstm,null);
        }
            return flag;
    }

7.3.3 Service层

    //添加订单
    public abstract boolean addBill(Bill bill)throws SQLException;

7.3.4 Service层实现类

//添加订单
    @Override
    public boolean addBill(Bill bill) {
        boolean flag = false;
        Connection conn = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            flag = billDao.addBill(conn, bill);
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

7.3.5 Servlet层

//查询供应商 billadd.jsp页面中的下拉框调用
    public void getproviderlist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        int providerCounts = providerService.getProviderCounts("", "");
        List<Provider> providerList = providerService.getProviderList("", "", 1, providerCounts);
        //将信息 发送给ajax 将此集合转换为json格式传递
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式
        out.write(JSONArray.toJSONString(providerList));
        out.flush();
        out.close();
    }
    //添加订单
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取数据 并封装
        Bill bill = new Bill();
        bill.setBillCode(req.getParameter("billCode"));
        bill.setProductName(req.getParameter("productName"));
        bill.setProductUnit(req.getParameter("productUnit"));
        bill.setProductCount(BigDecimal.valueOf(Long.parseLong(req.getParameter("productCount"))));
        bill.setTotalPrice(BigDecimal.valueOf(Long.parseLong(req.getParameter("totalPrice"))));
        bill.setProviderId(Integer.parseInt(req.getParameter("providerId")));
        bill.setIsPayment(Integer.parseInt(req.getParameter("isPayment")));
        //下面是表单没有的
        bill.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setCreationDate(new Date());
        bill.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setModifyDate(new Date());

        BillServiceImpl billService = new BillServiceImpl();
        if(billService.addBill(bill)){
            //如果添加成功 重定向跳转到展示订单页面
            resp.sendRedirect(req.getContextPath()+"/jsp/bill.do?method=query");
        }else{
            //添加失败 转发到此添加页面
            req.getRequestDispatcher("billadd.jsp").forward(req,resp);
        }
    }

并修改doGet方法

 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("getproviderlist")){
            this.getproviderlist(req,resp);
        }
        else if(method.equals("add")){
            this.add(req,resp);
        }
    }

至此 添加订单功能实现!

7.4 实现订单 删除功能

点击删除按钮触发的js

//订单管理页面上点击删除按钮弹出删除框(billlist.jsp)
function deleteBill(obj){
	$.ajax({
		type:"GET",
		url:path+"/jsp/bill.do",
		data:{method:"delbill",billid:obj.attr("billid")},
		dataType:"json",
		success:function(data){
			if(data.delResult == "true"){//删除成功:移除删除行
				cancleBtn();
				obj.parents("tr").remove();
			}else if(data.delResult == "false"){//删除失败
				//alert("对不起,删除订单【"+obj.attr("billcc")+"】失败");
				changeDLGContent("对不起,删除订单【"+obj.attr("billcc")+"】失败");
			}else if(data.delResult == "notexist"){
				//alert("对不起,订单【"+obj.attr("billcc")+"】不存在");
				changeDLGContent("对不起,订单【"+obj.attr("billcc")+"】不存在");
			}
		},
		error:function(data){
			alert("对不起,删除失败");
		}
	});
}

7.4.1 Dao层

//删除订单
    public abstract boolean deleteBill(Connection conn,int billId)throws SQLException;

7.4.2 Dao层实现类

//删除订单
    @Override
    public boolean deleteBill(Connection conn, int billId) throws SQLException {
        PreparedStatement pstm = null;
        boolean flag = false;
        if(conn != null){
            String sql = "delete from smbms_bill where id = ?";
            Object[] params = {billId};
            int updateRows = BaseDao.execute(conn, sql, pstm, params);
            if(updateRows > 0){
                flag = true;
            }
            BaseDao.closeResource(null,pstm,null);
        }
            return flag;
    }

7.4.3 Service层

//删除订单
    public abstract boolean deleteBill(int billId);

7.4.4 Service层实现类

//删除订单
    @Override
    public boolean deleteBill(int billId) {
        boolean flag = false;
        Connection conn = null;
        try {
            conn  = BaseDao.getConnection();
            conn.setAutoCommit(false);
            flag = billDao.deleteBill(conn, billId);
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

7.4.5 Servlet层

 //删除订单
    public void deleteBill(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //从前端获取要删除的订单id
        String billid = req.getParameter("billid");
        int id = 0;
        //转换
        try {
            id = Integer.parseInt(billid);
        }catch (Exception e){
            e.printStackTrace();
            id = 0;
        }
        BillServiceImpl billService = new BillServiceImpl();
        //创建一个map集合 存储 删除成功和失败的信息 传递给ajax
        Map<Object, Object> resultMap = new HashMap<>();
        if(id <= 0){
            resultMap.put("delResult","notexist");
        }else{
            if(billService.deleteBill(id)){
                System.out.println("删除订单成功...");
                //删除订单成功
                resultMap.put("delResult","true");
            }else{
                System.out.println("删除订单失败...");
                resultMap.put("delResult","false");
            }
        }
        //将此map集合 转换为json格式
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式
        out.write(JSONArray.toJSONString(resultMap));
        out.flush();
        out.close();
    }

以及修改doGet方法

 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("getproviderlist")){
            this.getproviderlist(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }else if(method.equals("delbill")){
            this.deleteBill(req,resp);
        }
    }

至此 删除订单功能完成

7.5 实现订单修改功能

查看对应js代码

$(".modifyBill").on("click",function(){
		var obj = $(this);
		window.location.href=path+"/jsp/bill.do?method=modify&billid="+ obj.attr("billid");
	});

思路:我们从前端获取要修改的订单id
查询此订单信息 并在修改订单的页面展示出来,最后在执行提交订单表单的方法

7.5.1 Dao层

//根据订单id 获取订单信息
    public abstract Bill findByBillId(Connection conn,int billId)throws SQLException;
    //修改订单信息
    public abstract boolean modifyBill(Connection conn,int billId,Bill bill)throws SQLException;

7.5.2 Dao层实现类

//根据订单id 获取订单信息
    @Override
    public Bill findByBillId(Connection conn, int billId) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        Bill bill = new Bill();
        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[] params = {billId};
            rs = BaseDao.executeQuery(conn, sql, pstm, params, rs);
            //遍历此结果集 并存入bill对象
            if(rs.next()){
                bill.setBillCode(rs.getString("billCode"));
                bill.setProductName(rs.getString("productName"));
                bill.setProductDesc(rs.getString("productDesc"));
                bill.setProductUnit(rs.getString("productUnit"));
                bill.setProductCount(rs.getBigDecimal("productCount"));
                bill.setTotalPrice(rs.getBigDecimal("totalPrice"));
                bill.setIsPayment(rs.getInt("isPayment"));
                bill.setCreatedBy(rs.getInt("createdBy"));
                bill.setCreationDate(rs.getTimestamp("creationDate"));
                bill.setModifyBy(rs.getInt("modifyBy"));
                bill.setModifyDate(rs.getTimestamp("modifyDate"));
                bill.setProviderId(rs.getInt("providerId"));
                bill.setProviderName(rs.getString("providerName"));
            }
            BaseDao.closeResource(null,pstm,rs);
        }
        return bill;
    }
    //修改订单信息
    @Override
    public boolean modifyBill(Connection conn, int billId, Bill bill) throws SQLException {
        PreparedStatement pstm = null;
        boolean flag = false;
        if(conn != null){
            String sql = "update smbms_bill set billCode = ?,productName =?,productDesc = ?,productUnit = ?,productCount = ? ,totalPrice = ?,isPayment = ?,modifyBy = ?,modifyDate = ?,providerId = ? where id = ?";
            Object[] params = {bill.getBillCode(),bill.getProductName(),bill.getProductDesc(),bill.getProductUnit(),bill.getProductCount(),bill.getTotalPrice(),bill.getIsPayment(),bill.getModifyBy(),bill.getModifyDate(),bill.getProviderId(),billId};
            int updateRows = BaseDao.execute(conn, sql, pstm, params);
            if (updateRows > 0) {
                flag = true;
            }
            BaseDao.closeResource(null,pstm,null);
            }
            return flag;
        }

7.5.3 Service层

//根据订单id 获取订单信息
    public abstract Bill findByBillId(int billId)throws SQLException;
    //修改订单信息
    public abstract boolean modifyBill(int billId, Bill bill)throws SQLException;

7.5.4 Service层实现类

//根据订单id 获取订单信息
    @Override
    public Bill findByBillId(int billId){
        Connection conn = null;
        Bill bill = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            bill = billDao.findByBillId(conn, billId);
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return bill;
        }
    }

    //修改订单信息
    @Override
    public boolean modifyBill(int billId, Bill bill) {
        boolean flag = false;
        Connection conn = null;
        try {
            conn = BaseDao.getConnection();
            conn.setAutoCommit(false);
            flag = billDao.modifyBill(conn, billId, bill);
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            BaseDao.closeResource(conn,null,null);
            return flag;
        }
    }

7.5.5 Servlet层

// 要修改的订单信息 展示
    public void modify(HttpServletRequest req, HttpServletResponse resp) throws  ServletException, IOException {
        //从前端获取要修改的订单id
        String billid = req.getParameter("billid");
        int id = 0;
        try {
            id = Integer.parseInt(billid);
        }catch (Exception e){
            e.printStackTrace();
            id = 0;
        }
        //根据此id查询订单的信息并在修改页面展示
        BillServiceImpl billService = new BillServiceImpl();
        Bill bill = billService.findByBillId(id);
        bill.setId(id);
        //将此bill存入req 并转发到 billmodify.jsp页面
        req.setAttribute("bill",bill);
        req.getRequestDispatcher("billmodify.jsp").forward(req,resp);
    }
    //修改订单信息方法
    public void modifysave(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //从前端获取要修改的订单id
        String billid = req.getParameter("billid");
        System.out.println("从前端获取的订单id:"+billid);
        int id = 0;
        try {
            id = Integer.parseInt(billid);
        }catch (Exception e){
            e.printStackTrace();
            id = 0;
        }
        //根据id查询旧订单信息
        BillServiceImpl billService = new BillServiceImpl();
        Bill bill = billService.findByBillId(id);
        //根据修改的信息 修改对应的订单
        bill.setBillCode(req.getParameter("billCode"));
        bill.setProductName(req.getParameter("productName"));
        bill.setProductUnit(req.getParameter("productUnit"));
        bill.setProductCount(BigDecimal.valueOf(Double.parseDouble(req.getParameter("productCount"))));
        bill.setTotalPrice(BigDecimal.valueOf(Double.parseDouble(req.getParameter("totalPrice"))));
        bill.setProviderId(Integer.parseInt(req.getParameter("providerId")));
        bill.setIsPayment(Integer.parseInt(req.getParameter("isPayment")));
        //下面是表单未显示的
        bill.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setModifyDate(new Date());
        //执行修改语句
        boolean flag = billService.modifyBill(id, bill);
        if(flag){
            //如果修改成功 重定向到订单展示页面
            resp.sendRedirect(req.getContextPath()+"/jsp/bill.do?method=query");
        }else{
            //修改失败 转发到此修改页面
            req.getRequestDispatcher("billmodify.jsp").forward(req,resp);
        }
    }

并修改doGet方法

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("getproviderlist")){
            this.getproviderlist(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }else if(method.equals("delbill")){
            this.deleteBill(req,resp);
        }else if(method.equals("modify")){
            this.modify(req,resp);
        }else if(method.equals("modifysave")){
            this.modifysave(req,resp);
        }
    }

7.6 实现订单 查看功能

查看对应js代码

$(".viewBill").on("click",function(){
		//将被绑定的元素(a)转换成jquery对象,可以使用jquery方法
		var obj = $(this);
		window.location.href=path+"/jsp/bill.do?method=view&billid="+ obj.attr("billid");
	});

思路:根据id查找订单信息并传给前端展示

Servlet层

//查看 订单信息
    public void viewBill(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取要查看订单信息的id
        String BillId = req.getParameter("billid");
        int id = 0;
        try {
            id = Integer.parseInt(BillId);
        }catch (ClassCastException e){
            e.printStackTrace();
            id = 0;
        }
        //根据id查询订单信息
        BillServiceImpl billService = new BillServiceImpl();
        Bill bill = billService.findByBillId(id);
        //将信息存入req
        req.setAttribute("bill",bill);
        //转发到billview.jsp页面
        req.getRequestDispatcher("billview.jsp").forward(req,resp);
    }

并修改doGet方法

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("getproviderlist")){
            this.getproviderlist(req,resp);
        }else if(method.equals("add")){
            this.add(req,resp);
        }else if(method.equals("delbill")){
            this.deleteBill(req,resp);
        }else if(method.equals("modify")){
            this.modify(req,resp);
        }else if(method.equals("modifysave")){
            this.modifysave(req,resp);
        }else if(method.equals("view")){
            this.viewBill(req,resp);
        }
    }

至此 全部功能实现 可测试

思路图解

你可能感兴趣的:(JavaWeb,JAVA,MySQL,mysql,java,intellij,idea,javascript,css)