Javaweb商城项目

news2024/12/23 23:47:51

smbms

视频教程:javaweb-30:smbms项目搭建_哔哩哔哩_bilibili

一.项目分析 

1.项目结构   

2.数据库表  

CREATE DATABASE `smbms`;

USE `smbms`;

DROP TABLE IF EXISTS `smbms_address`;

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


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


DROP TABLE IF EXISTS `smbms_bill`;

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


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

DROP TABLE IF EXISTS `smbms_provider`;

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


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


DROP TABLE IF EXISTS `smbms_role`;

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


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


DROP TABLE IF EXISTS `smbms_user`;

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

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

二.准备项目搭建 

1.创建maven项目

2.配置tomcat

3.测试项目是否能跑

4.导入架包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>java-web03</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <!--servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>

    <!--JSP依赖-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>

    <!--数据库连接依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.29</version>
    </dependency>

    <!--JSTL标签-->
    <dependency>
      <groupId>javax.servlet.jsp.jstl</groupId>
      <artifactId>jstl-api</artifactId>
      <version>1.2</version>
    </dependency>

    <!--JSTL标签的依赖-->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    
    <!--junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>

  </dependencies>

    <!--读入文件配置-->
  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>

</project>

5.创建项目结构 

  

  - com.smbms
      - dao 持久化层
      - filter 过滤层
      - pojo 实体层
      - service 业务层
      - servlet 调用业务层

6.编写实体类

  • ORM映射: 表 - 类
  • 数据库

  • 对应数据库 ,为了少写代码可以引入架包
    pom.xml
    
        <!--set,get架包-->
        <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.24</version>
          <scope>provided</scope>
        </dependency>

  • 开启注解 
  • 编写实体类

package com.smbms.pojo;

import lombok.Data;

import java.math.BigDecimal;
import java.util.Date;

@Data
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 int isPayment;  // 是否支付
	private Integer createdBy;  // 创建者
	private Date creationDate;  //创建时间
	private Integer modifyBy;   // 更新者
	private Date modifyDate;    // 更新时间
	private String providerName; // 供应商名称
	private Integer providerId; // 供应商ID 

}
package com.smbms.pojo;

import lombok.Data;

import java.util.Date;
@Data
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;//更新时间

	
}
package com.smbms.pojo;

import lombok.Data;

import java.util.Date;
@Data
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;//更新时间
	


	
}
package com.smbms.pojo;

import lombok.Data;

import java.util.Date;

/**
 * 使用Lombok的jar包,可以不用写get/set、toString等方法
 */
@Data
public class User {
	private Integer id; // 主键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 creationDate;  // 创建时间
	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;
	}
}

7.编写基础公共类 

  • 数据库配置文件 db.properties
driver=com.mysql.jc.jdbc.Driver
# 在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8
url=jdbc:mysql://localhost:3306/smbms?useSSL=true&useUnicode=true&characterEncoding=utf-8
user=root
password=123456
  • 编写数据库的公共类——BaseDao.java
    package com.smbms.dao;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.*;
    import java.util.Properties;
    
    /**
     * @Description: 操作数据库的公共类
     */
    public class BaseDao {
    	private static String driver;
    	private static String url;
    	private static String user;
    	private static String password;
    
    	// 静态代码块,类加载时就初始化了
    	static{
    		Properties properties = new Properties();
    		// 通过类加载器读取对应的资源
    		InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
    
    		try{
    			properties.load(is);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    
    		driver = properties.getProperty("driver");
    		url = properties.getProperty("url");
    		user = properties.getProperty("user");
    		password = properties.getProperty("password");
    
    	}
    	
    
    	// 获取数据库的链接
    	public static Connection getConnection(){
    		Connection connection = null;
    		try {
    			Class.forName(driver);
    			connection = DriverManager.getConnection(url, user, password);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return connection;
    	}
    
    	// 编写查询公共类
    	public static ResultSet execute(Connection connection,PreparedStatement preparedStatement , ResultSet rs, String sql, Object[] params) throws SQLException {
    		// 预编译的SQL,在后面直接执行就行了
    		preparedStatement = connection.prepareStatement(sql);
    
    		for (int i = 0; i < params.length; i++) {
    			// setObject,占位符从1开始,但是数组是从0开始
    			preparedStatement.setObject(i+1,params[i]);
    		}
    
    		rs = preparedStatement.executeQuery();
    		return rs;
    	}
    
    	// 编写查询公共类
    	public static int execute(Connection connection, PreparedStatement preparedStatement, String sql, Object[] params) throws SQLException {
    		preparedStatement = connection.prepareStatement(sql);
    
    		for (int i = 0; i < params.length; i++) {
    			// setObject,占位符从1开始,但是数组是从0开始
    			preparedStatement.setObject(i+1,params[i]);
    		}
    
    		int updateRows = preparedStatement.executeUpdate();
    		return updateRows;
    	}
    
    	// 释放资源
    	public static boolean closeResult(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
    		boolean flag = true;
    
    		if(resultSet != null){
    			try {
    				resultSet.close();
    				// GC回收
    				resultSet = null;
    			} catch (SQLException e) {
    				e.printStackTrace();
    				flag = false;
    			}
    		}
    
    		if(preparedStatement != null){
    			try {
    				preparedStatement.close();
    				// GC回收
    				preparedStatement = null;
    			} catch (SQLException e) {
    				e.printStackTrace();
    				flag = false;
    			}
    		}
    
    		if(connection != null){
    			try {
    				connection.close();
    				// GC回收
    				connection = null;
    			} catch (SQLException e) {
    				e.printStackTrace();
    				flag = false;
    			}
    		}
    
    		return flag;
    	}
    
    }
    

  • 编写字符编码过滤器 
package com.smbms.filter;

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

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

public class CharacterEncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
      

        chain.doFilter(request,response);
    }

    public void destroy() {}
}
XML

<!-- 注册编码过滤器 -->
  <filter>
    <filter-name>encoding</filter-name>
    <filter-class>com.smbms.filter.CharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

8.导入静态资源 

下载 - KuangStudy

三.登录 

1.编写登入页面,设置为首页

前端页面

<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>系统登录 - 超市订单管理系统</title>
    <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/css/style.css" />
    <script type="text/javascript">
        /* if(top.location!=self.location){
              top.location=self.location;
         } */
    </script>
</head>
<body class="login_bg">
<section class="loginBox">
    <header class="loginHeader">
        <h1>超市订单管理系统</h1>
    </header>
    <section class="loginCont">
        <form class="loginForm" action="${pageContext.request.contextPath }/login.do"  name="actionForm" id="actionForm"  method="post" >
            <div class="info">${error }</div>
            <div class="inputbox">
                <label for="userCode">用户名:</label>
                <input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/>
            </div>
            <div class="inputbox">
                <label for="userPassword">密码:</label>
                <input type="password" id="userPassword" name="userPassword" placeholder="请输入密码" required/>
            </div>
            <div class="subBtn">

                <input type="submit" value="登录"/>
                <input type="reset" value="重置"/>
            </div>
        </form>
    </section>
</section>
</body>
</html>

设置首页——web.xml

XML

  <!-- 设置login.jsp为欢迎(首页)页面 -->
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

2.dao层接口与实现类

package com.smbms.dao.user;

import com.smbms.pojo.User;

import java.sql.Connection;

public interface UserDao {
	// 得到要登录的用户
	public User getLoginUser(Connection connection,String userCode) throws Exception;
}
package com.smbms.dao.user;

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

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDaoImpl implements UserDao{

    public User getLoginUser(Connection connection, String userCode) throws Exception {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;

        if(connection != null) {
            String sql = "select * from smbms_user where userCode=?";
            Object[] params = {userCode};

            rs = BaseDao.execute(connection, pstm, rs, sql, params);

            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.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
            }
            BaseDao.closeResult(null,pstm,rs);
        }

        return user;
    }
}

3.业务层接口与实现类

package com.smbms.dao.user;

import com.smbms.pojo.User;

import java.sql.Connection;

public interface UserDao {
	// 得到要登录的用户
	public User getLoginUser(Connection connection,String userCode) throws Exception;
}
package com.smbms.service.user;

import com.smbms.dao.BaseDao;
import com.smbms.dao.user.UserDao;
import com.smbms.dao.user.UserDaoImpl;
import com.smbms.pojo.User;

import java.sql.Connection;

public class UserServiceImpl implements UserService {

    // 业务层都会调用dao层,所以需要引入Dao层
    private UserDao userDao;

    public UserServiceImpl() {
       userDao = new UserDaoImpl();
    }

    public User login(String userCode, String password) {
        // 要调用getLoginUser()方法,进行数据传输,把要用到的参数先拿出来
        Connection connection = null;
        User user = null;

        try {
            // 获取数据库链接
            connection = BaseDao.getConnection();
            // 通过业务层调用对应的具体的数据库操作
            user = userDao.getLoginUser(connection,userCode);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            BaseDao.closeResult(connection,null,null);
        }


        // 密码判断
        if (user != null) {
            if (!user.getUserPassword().equals(password)){
                user = null;
            }
        }

        return user;
    }

}

4.编写Servlet,注册Servlet

 

1.导入资源jsp页面资源:在上面的链接里有 

2.编写LoginServlet类 

提出常量 

package com.smbms.util;

public class Const {
    public final static String USER_SESSION = "USER_SESSION ";
}

package com.smbms.servlet.user;

import com.smbms.pojo.User;
import com.smbms.service.user.UserServiceImpl;
import com.smbms.util.Const;

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 LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取前端参数,用户名与密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        // 验证用户名与密码,调用UserServiceImpl类
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.login(userCode,userPassword);

        // 页面转跳
        if ( user != null) {
            // 登入成功,将用户信息放入session中
            req.getSession().setAttribute(Const.USER_SESSION,user);
            // 重定向页面
            resp.sendRedirect("/jsp/frame.jsp");
        } else {
            // 登入失败,将错误信息发送到前端
            // 与前端<div class="info">${error }</div>对应
            req.setAttribute("error","用户名或密码错误!");
            // 并转跳页面
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
XML 
 <!-- 配置登入服务的servlet-->
    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.smbms.servlet.user.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login.do</url-pattern>
    </servlet-mapping>

四.注销及权限过滤 

1.注销功能

移除session,返回登录页面。 

  • 编写Servlet类
    package com.smbms.servlet.user;
    
    import com.smbms.pojo.User;
    import com.smbms.util.Const;
    
    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 {
    
            // 获取session3,并销毁
            req.getSession().removeAttribute(Const.USER_SESSION);
            // 返回首页,req.getContextPath()获取首页地址
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
         <!-- 注销 -->
        <servlet>
            <servlet-name>LogoutServlet</servlet-name>
            <servlet-class>com.smbms.servlet.user.LogoutServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>LogoutServlet</servlet-name>
            <url-pattern>/jsp/logout.do</url-pattern>
        </servlet-mapping>

    2.登录拦截优化

  • 实现类编写

    ​
    package com.smbms.filter;
    
    import com.smbms.pojo.User;
    import com.smbms.util.Const;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class SysFilter implements Filter {
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain Chain) throws IOException, ServletException {
    
            // 类型转换,帮助拿到参数
            HttpServletRequest req = (HttpServletRequest) servletRequest;
            HttpServletResponse resp = (HttpServletResponse) servletResponse;
    
            // 获取session
            User user = (User) req.getSession().getAttribute(Const.USER_SESSION);
    
            // 判断
            if (user == null) {
                // 返回错误页面
                resp.sendRedirect("/error.jsp");
            } else {
                Chain.doFilter(servletRequest,servletResponse);
            }
        }
    
        public void destroy() {
    
        }
    }
    
    ​

  • 错误页面

    <%@ page contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
    <h1>请登录后再访问该页面!</h1>
    <a href="login.jsp">返回</a>
    </body>
    </html>
    
  • 注册filter
     <!--  用户登录过滤器  -->
        <filter>
            <filter-name>SysFilter</filter-name>
            <filter-class>com.smbms.filter.SysFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>SysFilter</filter-name>
            <url-pattern>/jsp/*</url-pattern>
        </filter-mapping>

 五.密码实现修改

 1.导入前端素材

  • /jsp/pwdmodify.jsp

2.思路框架

3.编写Dao层接口与实现类

package com.smbms.dao.user;

import com.smbms.pojo.User;

import java.sql.Connection;

public interface UserDao {
	// 得到要登录的用户
	public User getLoginUser(Connection connection, String userCode) throws Exception;

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

}
package com.smbms.dao.user;

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

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDaoImpl implements UserDao{

    public User getLoginUser(Connection connection, String userCode) throws Exception {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;

        if(connection != null) {
            String sql = "select * from smbms_user where userCode=?";
            Object[] params = {userCode};

            rs = BaseDao.execute(connection, pstm, rs, sql, params);

            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.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
            }
            BaseDao.closeResult(null,pstm,rs);
        }

        return user;
    }

    public int updatePwd(Connection connection, int id, String pwd) throws Exception {

        
        PreparedStatement pstm = null;
        int execute = 0;

        // 判断是否连接
        if (connection != null) {
            String sql = "update smbms_user set userPassword= ? where id = ?";
            Object[] params = {pwd,id};
       
            execute = BaseDao.execute(connection,pstm,sql,params);
            // 关闭连接
            BaseDao.closeResult(null,pstm,null);
        }
        return execute;
    }
}

4.编写service层接口与实现类

package com.smbms.service.user;

import com.smbms.pojo.User;

public interface UserService {

    // 用户登入
    public User login(String userCode, String password);

    // 密码更新
    public boolean updatePwd(int id, String pwd);
}
package com.smbms.service.user;

import com.smbms.dao.BaseDao;
import com.smbms.dao.user.UserDao;
import com.smbms.dao.user.UserDaoImpl;
import com.smbms.pojo.User;

import java.sql.Connection;

public class UserServiceImpl implements UserService {

    // 业务层都会调用dao层,所以需要引入Dao层
    private UserDao userDao;

    public UserServiceImpl() {
       userDao = new UserDaoImpl();
    }

    public User login(String userCode, String password) {
        // 要调用getLoginUser()方法,进行数据传输,把要用到的参数先拿出来
        Connection connection = null;
        User user = null;

        try {
            // 获取数据库链接
            connection = BaseDao.getConnection();
            // 通过业务层调用对应的具体的数据库操作
            user = userDao.getLoginUser(connection,userCode);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            BaseDao.closeResult(connection,null,null);
        }


        // 密码判断
        if (user != null) {
            if (!user.getUserPassword().equals(password)){
                user = null;
            }
        }

        return user;
    }

    public boolean updatePwd(int id, String pwd) {

        // 用返回值判断密码是否修改
        boolean flag = false;
        // 获取数据库连接
        Connection connection = null;
        connection = BaseDao.getConnection();
        // 判断是否修改成功
        try {
            if(userDao.updatePwd(connection,id,pwd) > 0) {
                // 修改成功flag等于true
                flag = true;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭连接
            BaseDao.closeResult(connection,null,null);
        }
        return flag;
    }
}

5.编写servlet层与注册

 这里要实现复用 

package com.smbms.servlet.user;

import com.smbms.pojo.User;
import com.smbms.service.user.UserService;
import com.smbms.service.user.UserServiceImpl;
import com.smbms.util.Const;

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 UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

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

        // 实现复用
        // 获取前端隐藏表单name
        String method = req.getParameter("method");
        if(method != null && method.equals("savepwd")){
            this.updatePwd(req, resp);
        }
    }

    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        boolean flag = false;

        // 获取session与前端密码
        User user = (User) req.getSession().getAttribute(Const.USER_SESSION);
        String pwd = req.getParameter("newpassword");

        // 判断用户修改
        if (user != null && pwd != null && pwd.length() != 0) {
           
            // 调用service层
            UserServiceImpl userService = new UserServiceImpl();
            flag = userService.updatePwd(user.getId(),pwd);
            // 判断是否修改成功
            if (flag) {
                // 修改成功,注销session
            req.getSession().removeAttribute(Const.USER_SESSION);
            }else {
                // 修改失败,反馈前端
                //  <div class="info">${message}</div>
                req.setAttribute("message","修改密码失败!");
            }
        }else {
            req.setAttribute("message","密码为空或长度有问题!");
        }
        // 两个失败的结构,返回此页面
        req.getRequestDispatcher("/sys/pwdmodify.jsp").forward(req,resp);

    }
}
   <!-- 配置修改密码服务的servlet -->
    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.smbms.servlet.user.UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/jsp/user.do</url-pattern>
    </servlet-mapping>

6.Ajax验证旧密码 

(1).使用阿里巴巴的fastjson

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.76</version>
</dependency>
  • 注意:在导入maven的同时,请将相应的jar包放入Tomcat的lib目录下

(2).添加修改旧密码的servlet类

package com.smbms.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.mysql.cj.xdevapi.JsonArray;
import com.smbms.pojo.User;
import com.smbms.service.user.UserService;
import com.smbms.service.user.UserServiceImpl;
import com.smbms.util.Const;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 实现复用
        // 获取前端隐藏表单name
        String method = req.getParameter("method");
        if(method.equals("savepwd") && method != null ){
            this.updatePwd(req,resp);
        }else if (method.equals("pwdmodify") && method != null){
            this.pwdModify(req,resp);
        }
    }

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

        // 实现复用
        // 获取前端隐藏表单name
        String method = req.getParameter("method");
        if(method.equals("savepwd") && method != null ){
            this.updatePwd(req,resp);
        }else if (method.equals("pwdmodify") && method != null){
            this.pwdModify(req,resp);
        }
    }

    // 修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        boolean flag = false;

        // 获取session与前端密码
        User user = (User) req.getSession().getAttribute(Const.USER_SESSION);
        String pwd = req.getParameter("newpassword");

        // 判断用户修改
        if (user != null && pwd != null && pwd.length() != 0) {

            // 调用service层
            System.out.println(user.getId());
            UserServiceImpl userService = new UserServiceImpl();
            flag = userService.updatePwd(user.getId(),pwd);
            // 判断是否修改成功
            if (flag) {
                // 修改成功,先注销session
                req.getSession().removeAttribute(Const.USER_SESSION);
            }else {
                // 修改失败,反馈前端
                //  <div class="info">${message}</div>
                req.setAttribute("message","修改密码失败!");
            }
        }else {
            req.setAttribute("message","密码为空或长度有问题!");
        }
        // 两个失败的结构,返回此页面
        req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);




}


    // 验证旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) throws IOException{

        // 从Session中取ID
        Object o = req.getSession().getAttribute(Const.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        Map<String, String> resultMap = new HashMap<String, String>();

        // session过期
        if(null == o ){
            resultMap.put("result", "sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){
            // 旧密码输入为空
            resultMap.put("result", "error");
        }else{
            String sessionPwd = ((User)o).getUserPassword();
            if(oldpassword.equals(sessionPwd)){
                resultMap.put("result", "true");
            }else{
                // 旧密码输入不正确
                resultMap.put("result", "false");
            }
        }

        resp.setContentType("application/json");
        PrintWriter outWriter = resp.getWriter();
        // JSONArray 阿里巴巴的JSON工具类
        outWriter.write(JSONArray.toJSONString(resultMap));
        outWriter.flush();
        outWriter.close();
    }

}

(3).添加默认Session过期时间

<!--  默认Session过期时间:真实业务请求  -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

六.用户管理实现 

1.思路框架

2.导入资源

(1).导入分页的工具类:PageSupport.java 

package com.smbms.util;

import lombok.Data;

@Data
public class PageSupport {
	//当前页码-来自于用户输入
	private int currentPageNo = 1;

	//总数量(表)
	private int totalCount = 0;

	//页面容量
	private int pageSize = 0;

	//总页数-totalCount/pageSize(+1)
	private int totalPageCount = 1;



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

	public void setTotalCount(int totalCount) {
		if(totalCount > 0){
			this.totalCount = totalCount;
			//设置总页数
			this.setTotalPageCountByRs();
		}
	}

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

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

}

 (2).导入jsp页面

 

3.获取用户数量

(1).dao层接口与实现类
package com.smbms.dao.user;

import com.smbms.pojo.User;

import java.sql.Connection;

public interface UserDao {
	// 得到要登录的用户
	public User getLoginUser(Connection connection, String userCode) throws Exception;

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

	// 查询用户总数
	public int getUserCount(Connection connection, String userName, int userRole)throws Exception;

}

为了实现用户名与用户角色的查询,所以我们要使用拼接sql 

 public int getUserCount(Connection connection, String userName, int userRole) throws Exception {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        int count = 0;

        // 判断是否接连
        if (connection != null) {
            // 使用StringBuffer或StringBuilder拼接sql;
            StringBuffer sql = new StringBuffer();
            sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");

            // PreparedStatement只能识别?,我们需要用ArrayList来存储迷糊查询的%
            ArrayList<Object> list = new ArrayList<Object>();

            // 判断userName,拼接sql要空一格
            if (!StringUtils.isNullOrEmpty(userName)) {
                sql.append(" and u.userName like ?");
                // index 0
                list.add("%"+userName+"%");
            }

            // 判断userRole,拼接sql要空一格
            if (userRole> 0) {
                sql.append(" and u.userRole = ?");
                // index 1
                list.add(userRole);
            }

            // 把list转成数组
            Object[] params = list.toArray();

            // 放入执行语句中,使用 toString() 方法将其sql转换为字符串
             rs = BaseDao.execute(connection,pstm,rs,sql.toString(),params);
            // 输出sql,看看是否完整
            System.out.println(sql.toString());


            // 从结果集中获取最后的数量
            if (rs.next()) {
                count = rs.getInt("count");
            }

            // 关闭
            BaseDao.closeResult(null,pstm,rs);

        }
        // 放回总数
            return count;
}
   // 测试

    @Test
    public void test() throws Exception {

        UserDaoImpl userDao = new UserDaoImpl();
        Connection connection = BaseDao.getConnection();
        int a = userDao.getUserCount(connection,null,0);
        System.out.println(a);// 12

    }

(2).业务层接口与实现类 
package com.smbms.service.user;

import com.smbms.pojo.User;

public interface UserService {

    // 用户登入
    public User login(String userCode, String password);

    // 密码更新
    public boolean updatePwd(int id, String pwd);

    // 根据条件查询出用户表记录数
    public int getUserCount(String userName, int userRole);

}

    public int getUserCount(String userName, int userRole) {
        Connection connection = null;
        int count = 0;

        try {
            connection = BaseDao.getConnection();
            count = userDao.getUserCount(connection,userName,userRole);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭
            BaseDao.closeResult(connection,null,null);
        }

        // 返回总数
        return count;
    }

 
   // 测试
    @Test
    public void test() {
        UserServiceImpl userService = new UserServiceImpl();
        int a = userService.getUserCount(null,0);
        System.out.println(a);// 12
    }

4.获取用户列表 

(1).dao层接口与实现类 
package com.smbms.dao.user;

import com.smbms.pojo.User;

import java.sql.Connection;
import java.util.List;

public interface UserDao {
	// 得到要登录的用户
	public User getLoginUser(Connection connection, String userCode) throws Exception;

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

	// 查询用户总数
	public int getUserCount(Connection connection, String userName, int userRole)throws Exception;

	// 通过条件查询-userList
	public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)throws Exception;

}
    public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<User>();
        if (connection != null) {
            StringBuffer sql = new StringBuffer();
            sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");
            List<Object> list = new ArrayList<Object>();
            if (!StringUtils.isNullOrEmpty(userName)) {
                sql.append(" and u.userName like ?");
                list.add("%" + userName + "%");
            }
            if (userRole > 0) {
                sql.append(" and u.userRole = ?");
                list.add(userRole);
            }

            // 实现分页
            sql.append(" order by creationDate DESC limit ?,?");
            // 1-5页对应sql语句01234,6-10对应sql语句56789,等等
            currentPageNo = (currentPageNo - 1) * pageSize;
            list.add(currentPageNo);
            list.add(pageSize);

            Object[] params = list.toArray();
            System.out.println("sql ----> " + sql.toString());
            rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);

            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.setUserRole(rs.getInt("userRole"));
                _user.setUserRoleName(rs.getString("userRoleName"));
                userList.add(_user);
            }
            BaseDao.closeResult(null, pstm, rs);
        }
        return userList;

    }

(2).业务层接口与实现类  
package com.smbms.service.user;

import com.smbms.pojo.User;

import java.util.List;

public interface UserService {

    // 用户登入
    public User login(String userCode, String password);

    // 密码更新
    public boolean updatePwd(int id, String pwd);

    // 根据条件查询出用户表记录数
    public int getUserCount(String userName, int userRole);

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


}
    public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
        Connection connection = null;
        List<User> userList = null;
        System.out.println("queryUserName ---- > " + queryUserName);
        System.out.println("queryUserRole ---- > " + queryUserRole);
        System.out.println("currentPageNo ---- > " + currentPageNo);
        System.out.println("pageSize ---- > " + pageSize);
        try {
            connection = BaseDao.getConnection();
            userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            BaseDao.closeResult(connection, null, null);
        }
        return userList;
    }
   @Test
    public void test() {
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList;
        userList = userService.getUserList(null,0,1,5);
        for (User list: userList) {
            System.out.println(list.getId());// 11 12 13 8 15
        }
    }

5.获取角色列表 

为了职责统一,可以把角色的操作单独放在一个包中,与pojo类对应! 

(1).dao层接口与实现类 
package com.smbms.dao.role;

import com.smbms.pojo.Role;

import java.sql.Connection;
import java.util.List;

public interface RoleDao {
    // 获取角色列表
    public List<Role> getRoleList(Connection connection) throws Exception;
}
package com.smbms.dao.role;

import com.smbms.dao.BaseDao;
import com.smbms.pojo.Role;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class RoleDaoImpl implements RoleDao {

    public List<Role> getRoleList(Connection connection) throws Exception {
        PreparedStatement prsm = null;
        ResultSet rs = null;
        List<Role> roleList = new ArrayList<Role>();

        if (connection != null) {
            String sql = "select * from smbms_role";
            Object[] params = {};

            rs = BaseDao.execute(connection,prsm,rs,sql,params);

            while (rs.next()) {
                Role _role = new Role();
                _role.setId(rs.getInt("id"));
                _role.setRoleName(rs.getString("roleName"));
                _role.setRoleCode(rs.getString("roleCode"));
                roleList.add(_role);
            }
            BaseDao.closeResult(null,prsm,rs);
        }
        return roleList;

    }
}

(2).业务层接口与实现类   
package com.smbms.service.role;

import com.smbms.pojo.Role;

import java.util.List;

public interface RoleService {

    // 获取用户角色
    public List<Role>getRoleList();
}
package com.smbms.service.role;

import com.smbms.dao.BaseDao;
import com.smbms.dao.role.RoleDao;
import com.smbms.dao.role.RoleDaoImpl;
import com.smbms.pojo.Role;

import java.sql.Connection;
import java.util.List;

public class RoleServiceImpl implements RoleService{
    private RoleDao roleDao;

    public RoleServiceImpl() {
        roleDao = new RoleDaoImpl();
    }

    public List<Role> getRoleList() {
        Connection connection = null;
        List<Role> roles = null;

        try {
            connection = BaseDao.getConnection();
            roles = roleDao.getRoleList(connection);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            BaseDao.closeResult(connection,null,null);
        }

        return roles;

    }
}
    @Test
    public void test() {
        RoleServiceImpl service = new RoleServiceImpl();
        List<Role>  list = service.getRoleList();
        for (Role a: list) {
            System.out.println(a.getRoleName());// 系统管理员 经理   普通员工
                  
        }
    }

6.用户显示的Servlet 

head.jsp    method=query 

 等等只要是路径后面有method=query 就走query方法

package com.smbms.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.mysql.cj.xdevapi.JsonArray;
import com.smbms.pojo.Role;
import com.smbms.pojo.User;
import com.smbms.service.role.RoleServiceImpl;
import com.smbms.service.user.UserService;
import com.smbms.service.user.UserServiceImpl;
import com.smbms.util.Const;
import com.smbms.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.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 实现复用
        String method = req.getParameter("method");
        if(method.equals("savepwd") && method != null ){
            this.updatePwd(req,resp);
        }else if (method.equals("pwdmodify") && method != null){
            this.pwdModify(req,resp);
        }else if (method.equals("query") && method != null) {
            this.query(req,resp);
        }
    }

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


    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.提前要准备好要使用的参数
        UserServiceImpl userService = new UserServiceImpl();
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<User> userList = null;
        List<Role> roleList = null;


        // 2.获取前端参数
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        // 下拉框前端返回的是字符串,而后端返回的是数字,我们自定义一个
        int queryUserRole = 0;

        // 3.页面的基础设置
        // 设置页面容量,这里的5应该提到常量表中
        int pageSize = 5;

        // 当前页码
        int currentPageNo = 1;

        // 4.判断前端参数与解析
        // 判断是否输入用户名
        if (queryUserName == null) {
            queryUserName = "";
        }

        // 判断是否选择角色
        if (temp != null && !temp.equals("")) {
            // 如果不为空,我们就解析前端参数,转换为数字
            queryUserRole = Integer.parseInt(temp);
        }

        // 判断输入页码
        if (pageIndex != null) {
            try {
                // 输入正确页码,解析前端参数,转换为数字
                currentPageNo = Integer.parseInt(pageIndex);
            } catch (NumberFormatException e) {
                // 如果报错,转跳错误页面
                resp.sendRedirect("/error.jsp");
            }
        }

        // 5.调用UserServiceImpl取用户总数
        int totalCount = userService.getUserCount(queryUserName,queryUserRole);

        // 6.调用PageSupport类设置页面的基本属性
        PageSupport pages = new PageSupport();
        // 将前面的参数放进去
        pages.setPageSize(pageSize);
        pages.setCurrentPageNo(currentPageNo);
        pages.setTotalPageCount(totalCount);

        // 7.限制页数
        // 获取最大页数
        int totalPageCount = ((int) totalCount/pageSize) + 1;
        // 控制首页和尾页
        if (currentPageNo < 1) {
            currentPageNo = 1;
        }else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        // 8.页面效果设置完毕,该设置页面内容了
        // 调用UserServiceImpl取用户信息
        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
        // 反馈给前端 <c:forEach var="user" items="${userList }" varStatus="status">
        req.setAttribute("userList",userList);

        // 调用RoleServiceImpl取角色信息
        roleList = roleService.getRoleList();
        // 反馈给前端<c:if test="${roleList != null }">
        req.setAttribute("roleList",roleList);

        // 补齐其它前端反馈,看前端 ${} 这个标签补齐
        req.setAttribute("roleList", roleList);
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryUserRole);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.getRequestDispatcher("userlist.jsp").forward(req, resp);



    }

    // 修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        boolean flag = false;

        // 获取session与前端密码
        User user = (User) req.getSession().getAttribute(Const.USER_SESSION);
        String pwd = req.getParameter("newpassword");

        // 判断用户修改
        if (user != null && pwd != null && pwd.length() != 0) {

            // 调用service层
            System.out.println(user.getId());
            UserServiceImpl userService = new UserServiceImpl();
            flag = userService.updatePwd(user.getId(),pwd);
            // 判断是否修改成功
            if (flag) {
                // 修改成功,先注销session
                req.getSession().removeAttribute(Const.USER_SESSION);
            }else {
                // 修改失败,反馈前端
                //  <div class="info">${message}</div>
                req.setAttribute("message","修改密码失败!");
            }
        }else {
            req.setAttribute("message","密码为空或长度有问题!");
        }
        // 两个失败的结构,返回此页面
        req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);




}


    // 验证旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) throws IOException{

        // 从Session中取ID
        Object o = req.getSession().getAttribute(Const.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        Map<String, String> resultMap = new HashMap<String, String>();

        // session过期
        if(null == o ){
            resultMap.put("result", "sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){
            // 旧密码输入为空
            resultMap.put("result", "error");
        }else{
            String sessionPwd = ((User)o).getUserPassword();
            if(oldpassword.equals(sessionPwd)){
                resultMap.put("result", "true");
            }else{
                // 旧密码输入不正确
                resultMap.put("result", "false");
            }
        }

        resp.setContentType("application/json");
        PrintWriter outWriter = resp.getWriter();
        // JSONArray 阿里巴巴的JSON工具类
        outWriter.write(JSONArray.toJSONString(resultMap));
        outWriter.flush();
        outWriter.close();
    }

}



7.实现增删改  

(1).dao层接口与实现类
package com.smbms.dao.user;

import com.smbms.pojo.User;

import java.sql.Connection;
import java.util.List;

public interface UserDao {
	// 得到要登录的用户
	public User getLoginUser(Connection connection, String userCode) throws Exception;

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

	// 查询用户总数
	public int getUserCount(Connection connection, String userName, int userRole)throws Exception;

	// 通过条件查询-userList
	public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)throws Exception;

	// 增加用户信息
	public int add(Connection connection, User user)throws Exception;

	// 通过userId删除user
	public int deleteUserById(Connection connection, Integer delId)throws Exception;

	// 修改用户信息
	public int modify(Connection connection, User user)throws Exception;

	// 通过userId查询user
	public User getUserById(Connection connection, String id)throws Exception;

}
    // 增加用户信息
    public int add(Connection connection, User user) throws Exception {
        PreparedStatement pstm = null;
        int updateRows = 0;
        if(null != connection){
            String sql = "insert into smbms_user (userCode,userName,userPassword," +
                    "userRole,gender,birthday,phone,address,creationDate,createdBy) " +
                    "values(?,?,?,?,?,?,?,?,?,?)";
            Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(),
                    user.getUserRole(),user.getGender(),user.getBirthday(),
                    user.getPhone(),user.getAddress(),user.getCreationDate(),user.getCreatedBy()};
            updateRows = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResult(null, pstm, null);
        }
        return updateRows;
    }

    // 通过userId删除user
    public int deleteUserById(Connection connection, Integer delId) throws Exception {
        PreparedStatement pstm = null;
        int flag = 0;
        if(null != connection){
            String sql = "delete from smbms_user where id=?";
            Object[] params = {delId};
            flag = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResult(null, pstm, null);
        }
        return flag;
    }

    // 修改用户信息
    public int modify(Connection connection, User user) throws Exception {
        int flag = 0;
        PreparedStatement pstm = null;
        if(null != connection){
            String sql = "update smbms_user set userName=?,"+
                    "gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
            Object[] params = {user.getUserName(),user.getGender(),user.getBirthday(),
                    user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(),
                    user.getModifyDate(),user.getId()};
            flag = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResult(null, pstm, null);
        }
        return flag;
    }

    // 通过userId查询user
    public User getUserById(Connection connection, String id) throws Exception {
        User user = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        if(null != connection){
            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 = {id};
            rs = BaseDao.execute(connection, pstm, rs, sql, params);
            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.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
                user.setUserRoleName(rs.getString("userRoleName"));
            }
            BaseDao.closeResult(null, pstm, rs);
        }
        return user;
    }
 (2).业务层接口与实现类   
package com.smbms.service.user;

import com.smbms.pojo.User;

import java.util.List;

public interface UserService {

    // 用户登入
    public User login(String userCode, String password);

    // 密码更新
    public boolean updatePwd(int id, String pwd);

    // 根据条件查询出用户表记录数
    public int getUserCount(String userName, int userRole);

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


    // 增加用户信息
    public boolean add(User user);

    // 通过userId删除user
    public boolean deleteUserById(Integer delId);

    // 修改用户信息
    public boolean modify(User user);

    // 通过userId查询user
    public User getUserById(String id);

    // 根据userCode查询出User
    public User selectUserCodeExist(String userCode);

}
    // 增加用户信息
    public boolean add(User user) {
        boolean flag = false;
        Connection connection = null;
        try {
            connection = BaseDao.getConnection();
            // 开启JDBC事务管理
            connection.setAutoCommit(false);
            int updateRows = userDao.add(connection,user);
            connection.commit();
            if(updateRows > 0){
                flag = true;
                System.out.println("add success!");
            }else{
                System.out.println("add failed!");
            }

        } catch (Exception e) {
            e.printStackTrace();
            try {
                System.out.println("rollback==================");
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally{
            // 在service层进行connection连接的关闭
            BaseDao.closeResult(connection, null, null);
        }
        return flag;
    }

    // 通过userId删除user
    public boolean deleteUserById(Integer delId) {
        Connection connection = null;
        boolean flag = false;
        try {
            connection = BaseDao.getConnection();
            if(userDao.deleteUserById(connection,delId) > 0) {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            BaseDao.closeResult(connection, null, null);
        }
        return flag;
    }

    // 修改用户信息
    public boolean modify(User user) {
        Connection connection = null;
        boolean flag = false;
        try {
            connection = BaseDao.getConnection();
            if(userDao.modify(connection,user) > 0) {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            BaseDao.closeResult(connection, null, null);
        }
        return flag;
    }

    // 通过userId查询user
    public User getUserById(String id) {
        User user = null;
        Connection connection = null;
        try{
            connection = BaseDao.getConnection();
            user = userDao.getUserById(connection,id);
        }catch (Exception e) {
            e.printStackTrace();
            user = null;
        }finally{
            BaseDao.closeResult(connection, null, null);
        }
        return user;
    }

    // 根据userCode查询出User
    public User selectUserCodeExist(String userCode) {
        Connection connection = null;
        User user = null;
        try {
            connection = BaseDao.getConnection();
            user = userDao.getLoginUser(connection, userCode);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            BaseDao.closeResult(connection, null, null);
        }
        return user;
    }

(3).Servlet层 
package com.smbms.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.Constants;
import com.mysql.cj.util.StringUtils;
import com.mysql.cj.xdevapi.JsonArray;
import com.smbms.pojo.Role;
import com.smbms.pojo.User;
import com.smbms.service.role.RoleService;
import com.smbms.service.role.RoleServiceImpl;
import com.smbms.service.user.UserService;
import com.smbms.service.user.UserServiceImpl;
import com.smbms.util.Const;
import com.smbms.util.PageSupport;

import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 实现复用
        String method = req.getParameter("method");
        if(method.equals("savepwd") && method != null ){
            this.updatePwd(req,resp);
        }else if (method.equals("pwdmodify") && method != null){
            this.pwdModify(req,resp);
        }else if (method.equals("query") && method != null) {
            this.query(req,resp);
        }else if(method != null && method.equals("add")){
            this.add(req,resp);
        } else if(method != null && method.equals("getrolelist")){
            this.getRoleList(req,resp);
        } else if(method != null && method.equals("ucexist")){
            this.userCodeExist(req,resp);
        } else if(method != null && method.equals("deluser")){
            this.delUser(req,resp);
        } else if(method != null && method.equals("view")){
            this.getUserById(req,resp,"userview.jsp");
        } else if(method != null && method.equals("modify")){
            this.getUserById(req,resp,"usermodify.jsp");
        } else if(method != null && method.equals("modifyexe")){
            this.modify(req,resp);
        }
    }

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


    // 查询用户
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}

    // 修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}


    // 验证旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) throws IOException{}

    // 删除用户
    public void delUser(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String id = request.getParameter("uid");
        Integer delId = 0;
        try{
            delId = Integer.parseInt(id);
        }catch (Exception e) {
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(delId <= 0){
            resultMap.put("delResult", "notexist");
        }else{
            UserService userService = new UserServiceImpl();
            if(userService.deleteUserById(delId)){
                resultMap.put("delResult", "true");
            }else{
                resultMap.put("delResult", "false");
            }
        }

        // 把resultMap转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    // 修改用户信息
    public void modify(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        String userName = request.getParameter("userName");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User)request.getSession().getAttribute(Const.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        if(userService.modify(user)){
            response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
        }else{
            request.getRequestDispatcher("usermodify.jsp").forward(request, response);
        }

    }

    // 通过userId查询user
    public void getUserById(HttpServletRequest request, HttpServletResponse response,String url)
            throws ServletException, IOException {

        String id = request.getParameter("uid");
        if(!StringUtils.isNullOrEmpty(id)){
            // 调用后台方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserById(id);
            request.setAttribute("user", user);
            request.getRequestDispatcher(url).forward(request, response);
        }

    }

    // 根据userCode查询出User
    private void userCodeExist(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 判断用户账号是否可用
        String userCode = request.getParameter("userCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            // userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        }else{
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode);
            if(null != user){
                resultMap.put("userCode","exist");
            }else{
                resultMap.put("userCode", "notexist");
            }
        }

        // 把resultMap转为json字符串以json的形式输出
        // 配置上下文的输出类型
        response.setContentType("application/json");
        // 从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = response.getWriter();
        // 把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush(); // 刷新
        outPrintWriter.close(); // 关闭流
    }

    private void getRoleList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        // 把roleList转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
}

七.其它功能实现

请看 SMBMS项目(完整版从0到1) - subeiLY - 博客园 (cnblogs.com)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2183374.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

计算机毕业设计 家校互联管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解

博主介绍&#xff1a;✌从事软件开发10年之余&#xff0c;专注于Java技术领域、Python人工智能及数据挖掘、小程序项目开发和Android项目开发等。CSDN、掘金、华为云、InfoQ、阿里云等平台优质作者✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精…

2024年录屏软件排行榜:班迪录屏等四款软件实测!

不论是学习、娱乐还是工作&#xff0c;都有可能需要用到屏幕录制功能。在这篇文章中&#xff0c;我们将从不同的使用场景出发&#xff0c;为大家推荐几款实用的录屏工具——福昕录屏大师、转转大师录屏、爱拍录屏以及班迪录屏。 Foxit REC 直达链接&#xff08;复制到浏览器打…

Flexible组件的用法

文章目录 1. 概念介绍2. 使用方法3. 示例代码我们在上一章回中介绍了扩展内容相关的知识,本章回中将介绍Flexible组件.闲话休提,让我们一起Talk Flutter吧。 1. 概念介绍 我们在前面章回中介绍了扩展列表相关的内容,当页面中其它组件和扩展列表一起使用时,扩展列表有可能会…

SpringBoot——基础配置

但是还需要删除pom.xml中的标签——模板的文件也同样操作 banner的选项——关闭 控制台 日志 banner图片的位置——还会分辨颜色 在 Java 的日志框架&#xff08;如 Logback、Log4j2 等&#xff09;中&#xff0c;logging.level.root主要用于设置根日志记录器的日志级别…

【Redis】如何在 Ubuntu 上安装 Redis 5

&#x1f970;&#x1f970;&#x1f970;来都来了&#xff0c;不妨点个关注叭&#xff01; &#x1f449;博客主页&#xff1a;欢迎各位大佬!&#x1f448; 本期内容主要介绍如何在 Ubuntu 上安装 Redis5 一些碎碎念&#xff1a; 本来这期内容介绍如何在 Centos 安装 Redis …

常用的Java安全框架

Spring Security&#xff1a; 就像Java安全领域的“瑞士军刀”&#xff0c;功能全面且强大。 支持认证、授权、加密、会话管理等安全功能。 与Spring框架无缝集成&#xff0c;使用起来特别方便。 社区活跃&#xff0c;文档丰富&#xff0c;遇到问题容易找到解决方案。 Apach…

SigmaStudio控件Cross Mixer\Signal Merger算法效果分析

衰减与叠加混音算法验证分析一 CH2:输入源为-20dB正弦波1khz CH1叠加混音&#xff1a;参考混音算法https://blog.csdn.net/weixin_48408892/article/details/129878036?spm1001.2014.3001.5502 Ch0衰减混音&#xff1a;外部多个输入源做混音时&#xff0c;建议参考该算法控件&…

网络通信——OSPF协议(基础篇)

这里基础是因为没有讲解OSPF中的具体算法过程&#xff0c;以及其中很多小细节。后续会更新。 目录 一.OSPF的基础信息 二.认识OSPF中的Router ID 三.OSPF中的三张表 四.OSPF中的度量方法&#xff08;计算开销值&#xff09; 五. OSPF选举DR和BDR&#xff08;就是这个区域…

简单vue指令实现 el-table 可拖拽表格功能

安装 SortableJS sorttableJs 相关优点如下&#xff1a; 相关配置项 参考 &#x1f449; SortableJS中文官网 pnpm i sortablejs封装成指令 不多逼逼&#xff0c;直接上才艺 &#x1f92a;&#x1f92a;&#x1f92a; 先安装一个 nanoid 插件 用于生成随机id&#xff0c;注…

图神经网络:处理复杂关系结构与图分类任务的强大工具

创作不易&#xff0c;您的打赏、关注、点赞、收藏和转发是我坚持下去的动力&#xff01; 图神经网络&#xff08;Graph Neural Network, GNN&#xff09;是针对图数据的一类神经网络模型。图数据具有节点&#xff08;节点代表实体&#xff09;和边&#xff08;边代表节点之间的…

LeetCode[中等] 55.跳跃游戏

给你一个非负整数数组 nums &#xff0c;你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个下标&#xff0c;如果可以&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 思路 贪心算法 可达位置…

html5 + css3(下)

目录 CSS基础体验cssCSS引入方式选择器选择器-标签选择器-类选择器-id选择器-通配符 文字基本样式1.1 字体大小1.2 字体粗细1.3 字体样式&#xff08;是否倾斜&#xff09; 文字-字体1.4 常见字体系列&#xff08;了解&#xff09;1.5 字体系列 拓展-层叠性font复合属性文本缩进…

erlang学习:Linux命令学习8

shell脚本案例学习 循环求 1-100 的每一步和 —案例 j0 i1 while((i<100)) do j$((ji)) echo $j ((i)) done每 30 s循环判断一次 user 用户是否登录系统 —案例 设置了一个次数&#xff0c;如果循环了五次在user文件中添加user用户&#xff0c;表示用户登录 USERS"u…

嵌入式 ADC基础知识

在现实世界中&#xff0c;常见的信号大都是模拟量&#xff0c;像温度、声音、气压等&#xff0c;但在信号的处理与传输中&#xff0c;为了减少噪声的干扰&#xff0c;较多使用的是数字量。因此我们经常会将现实中的模拟信号&#xff0c;通过 ADC 转换为数字信号进行运算、传输、…

Java | Leetcode Java题解之第442题数组中重复的数据

题目&#xff1a; 题解&#xff1a; class Solution {public List<Integer> findDuplicates(int[] nums) {int n nums.length;List<Integer> ans new ArrayList<Integer>();for (int i 0; i < n; i) {int x Math.abs(nums[i]);if (nums[x - 1] > …

端到端如火如荼, 传统规划控制还有前途吗?

近些年自动驾驶领域一定绕不开端到端, 伴随着各大车企纷纷转向拥抱端到端, 传统PnC的处境似乎愈发尴尬了起来. 但是端到端真的如水中月镜中花般美好吗? 不可否认深度学习给诸多领域带来了天翻地覆的变化, 但是自动驾驶直接关系到交通安全. 自动驾驶系统的输出, 必须具备足够的…

YOLO11改进|注意力机制篇|引入MLCA轻量级注意力机制

目录 一、MLCA注意力机制1.1MLCA注意力介绍1.2MLCA核心代码 五、添加MLCA注意力机制5.1STEP15.2STEP25.3STEP35.4STEP4 六、yaml文件与运行6.1yaml文件6.2运行成功截图 一、MLCA注意力机制 1.1MLCA注意力介绍 MLCA&#xff08;Multi-Level Channel Attention&#xff0c;多级通…

简单的微信小程序登录 注册 页面及逻辑

一、示例 二、示例代码 1.wxml <!--pages/login.wxml--> <!-- 登录注册文字 --> <view class"title">{{TitleText}}</view> <!-- 登录框 --> <view class"inputBox"><input type"text" placeholder&qu…

Nature Machine Intelligence 基于强化学习的扑翼无人机机翼应变飞行控制

尽管无人机技术发展迅速&#xff0c;但复制生物飞行的动态控制和风力感应能力&#xff0c;仍然遥不可及。生物学研究表明&#xff0c;昆虫翅膀上有机械感受器&#xff0c;即钟形感受器campaniform sensilla&#xff0c;探测飞行敏捷性至关重要的复杂气动载荷。 近日&#xff0…

国庆普及模拟赛-1 赛后总结

题目链接&#xff1a; file:///D:/C/%E9%9B%86%E8%AE%AD%E6%B5%8B%E8%AF%95/1001/2022%20-%20J2.pdf T1&#xff1a;隔离 题意如图。需要求所有时间的最短。 思路&#xff1a; 不需要进行一次次枚举&#xff0c;先算出总共要办事的总时间sum&#xff0c;如果某一次时间超过2…