SMBMS 超市订单管理系统
前言
狂神说
SMBMS 超市订单管理系统
git地址:https://gitee.com/juyss/smbms.git
idea将javaweb项目部署到tomcat
https://blog.csdn.net/zhuralll112/article/details/86238882
项目搭建准备工作
1. smbms项目搭建
0、数据库:
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);
address表
bill表
provider表
role表
user表
项目如何搭建?
考虑使不使用Maven?依赖、jar
1、搭建一个mavenWeb项目
设置
pom.xml
将无用的代码删掉
<?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>com.qia</groupId>
<artifactId>smbms</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
</project>
从tomcat文件夹下,webapps下,root下,web-inf下,的web.xml复制文本内容,到本项目的web.xml,修改为web.xml4.0版本
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
</web-app>
2、配置Tomcat
3、测试项目是否能够跑起来
成功
4、导入项目中会遇到的jar包
pom.xml
<?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>com.qia</groupId>
<artifactId>smbms</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<!--连接mysql数据库依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--JSTL表达式依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--jdbc -->
<dependency>
<groupId>org.clojure</groupId>
<artifactId>java.jdbc</artifactId>
<version>0.7.11</version>
</dependency>
<!--fastjson依赖-处理json字符串-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies>
</project>
jsp、servlet、mysql驱动、jstl、standard…
5、创建项目包结构
连接数据库
通过数据库快捷生成方式(没必要)
6、编写实体类
ORM映射:表-类映射
ORM全称Object Relational Mapping,即对象关系映射,是在pymysq之上又进行了一层封装,对于数据的操作,我们无需再去编写原生sql,取代代之的是基于面向对象的思想去编写类、对象、调用相应的方法等,ORM会将其转换/映射成原生SQL然后交给pymysql执行
简单说,ORM 就是通过实例对象的语法,完成关系型数据库的操作的技术,是"对象-关系映射"(Object/Relational Mapping) 的缩写。ORM 把数据库映射成对象。
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 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 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 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;//供应商名称
}
7、编写基础公共类
(资源resource)
1、数据库配置文件 db.properties
2、编写数据的公共类 baseDao
把baseDao放在dao层,而不是util层,因为baseDao(也叫dbutil)主要在与数据库交互
package com.qia.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* 操作数据库的基类(公共类)--静态类
* @author Administrator
*
*/
public class BaseDao {
//静态代码块,在类加载的时候执行
static{
init();
}
private static String driver;
private static String url;
private static String user;
private static String password;
//初始化连接参数,从配置文件里获得
public static void init(){
Properties params=new Properties();
String configFile = "database.properties";
// 通过类加载器读取对应的资源
InputStream is= BaseDao.class.getClassLoader().getResourceAsStream(configFile);
try {
params.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver=params.getProperty("driver");
url=params.getProperty("url");
user=params.getProperty("user");
password=params.getProperty("password");
}
/**
* 获取数据库连接
* @return
*/
public static Connection getConnection(){
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
/**
* 查询操作:编写查询公共类
* @param connection
* @param pstm
* @param rs
* @param sql
* @param params
* @return
*/
public static ResultSet execute(Connection connection,PreparedStatement pstm,ResultSet rs,
String sql,Object[] params) throws Exception{
pstm = connection.prepareStatement(sql);
for(int i = 0; i < params.length; i++){
//setObject,占位符从1开始,但是我们的数组是从0开始的!
pstm.setObject(i+1, params[i]);
}
rs = pstm.executeQuery();
return rs;
}
/**
* 更新操作:编写增删改公共方法
* @param connection
* @param pstm
* @param sql
* @param params
* @return
* @throws Exception
*/
public static int execute(Connection connection,PreparedStatement pstm,
String sql,Object[] params) throws Exception{
pstm = connection.prepareStatement(sql);//预编译
for(int i = 0; i < params.length; i++){//传参
//setObject,占位符从1开始,但是我们的数组是从0开始的!
pstm.setObject(i+1, params[i]);
}
int updateRows = pstm.executeUpdate();//返回更新条数
return updateRows;
}
/**
* 释放资源
* @param connection
* @param pstm
* @param rs
* @return
*/
public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet rs){
boolean flag = true;
if(rs != null){
try {
rs.close();
rs = null;//GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
}
if(pstm != null){
try {
pstm.close();
pstm = null;//GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
}
if(connection != null){
try {
connection.close();
connection = null;//GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
}
return flag;
}
}
3、编写字符编码过滤器
package com.qia.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncoding implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
web.xml配置
<filter>
<filter-name>CharacterEncoding</filter-name>
<filter-class>com.qia.filter.CharacterEncoding</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
8、导入静态资源
登录功能实现
2. smbms登陆流程实现
1、编写前端页面
<%@ page language="java" 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 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>
< !DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd” >
上面这个是HTML 中的 DOCTYPE 声明,作用是告知浏览器当前文档所使用的是哪种 HTML (< !DOCTYPE html >)或 XHTML 规范,正规的网站都会带这个声明,网站打不开,你可以换一种规范
2、web.xml中设置首页
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
3、编写dao层登录用户的登录的接口
/**
* 通过userCode获取User
* @param connection
* @param userCode
* @return
* @throws Exception
*/
public User getLoginUser(Connection connection, String userCode)throws Exception; //得到要登录的用户
4、编写dao接口的实现类
//得到要登录的用户
@Override
public User getLoginUser(Connection connection, String userCode)
throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
ResultSet rs = null;
User user = null;
if(null != connection){
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.closeResource(null, pstm, rs);
}
return user;
}
注意,dao层使用基础类后,只需要关闭pr,不要关闭连接c
5、业务层接口
/**
* 用户登录
* @param userCode
* @param userPassword
* @return
*/
public User login(String userCode, String userPassword);
6、业务层实现类
@Override
public User login(String userCode, String userPassword) {
// TODO Auto-generated method stub
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
//通过业务层调用对应的具体的数据库操作(没有直接操作数据库,解耦)
user = userDao.getLoginUser(connection, userCode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
//匹配密码
if(null != user){
if(!user.getUserPassword().equals(userPassword))
user = null;
}
return user;
}
测试代码
@Test
public void test(){//建议写在test目录下
UserServiceImpl userService = new UserServiceImpl();
User admin = userService.login("admin","666");
System.out.println(admin);// null 密码错了 ; 能找到该userCode用户 ,但是密码不正确,业务逻辑就把user设为null,来返回,以表示登录不成功
System.out.println(admin.getUserPassword());
}
@Test
public void test2() throws Exception {//建议写在test目录下
Connection connection = BaseDao.getConnection();
UserDaoImpl userDao = new UserDaoImpl();
User admin = userDao.getLoginUser(connection,"admin");
System.out.println(admin.getUserPassword());
}
业务逻辑:判断能否登录,就是判断这个用户的账号密码是否正确,先查找是否有这个用户,再去匹配密码是否正确
(所以代码逻辑没有去用,在查找的时候直接去判断 where 账号=? and 密码=? ,然后返回Boolean值判断能否登录,的这种方式)
(这种逻辑方式也可以,但是上面的更合乎业务逻辑,例如QQ登录的时候,你一输入账号,他就会显示你对应的头像,只等你输入密码验证登录)
7、编写servlet
package com.qia.servlet.user;
import com.qia.pojo.User;
import com.qia.service.user.UserService;
import com.qia.service.user.UserServiceImpl;
import com.qia.tools.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
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//登录还是别写在doget里了,账号密码都显示在url里了
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(" ============ login ============ ");
//获取用户名和密码
String userCode = request.getParameter("userCode");
String userPassword = request.getParameter("userPassword");
//调用service方法,进行用户匹配
UserService userService = new UserServiceImpl();
User user = userService.login(userCode,userPassword);
//判断登录 成功还是失败
// if(null != user){
if(user != null){//登录成功
//放入session
request.getSession().setAttribute(Constants.USER_SESSION, user);
//页面跳转(frame.jsp)
response.sendRedirect("jsp/frame.jsp");
}else{//登录失败
//页面跳转(login.jsp)带出提示信息--转发
request.setAttribute("error", "用户名或密码不正确");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
自定义的Constants存放常量,方便前端jsp页面调用
package com.qia.tools;
/**
* 自定义的Constants存放常量,方便前端jsp页面调用
* */
public class Constants {
public final static String USER_SESSION = "userSession";
public final static String SYS_MESSAGE = "message";
public final static int pageSize = 5;
}
8、注册首页
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.qia.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
9、测试访问,确保以上能成功!
dao数据库交互
service业务逻辑
servlet处理请求响应
pojo实体类
注意:
cpr,查需要r,更新不需要r
dao层使用基础类后,只需要关闭pr,不要关闭连接c
业务层会传c给dao层,dao层不用new c,但是业务层要new c
service用c关c,dao用cpr,收c不关c,开pr关pr
servlet包 有的也叫 controller
登录功能优化
3. smbms注销及权限过滤
注销功能
即登出功能
思路:移除session,返回登录页面(servlet即可解决)
package com.qia.servlet.user;
import com.qia.tools.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 退出登录,移除session中的用户对象Constants.USER_SESSION
* */
public class LogoutServlet extends HttpServlet {
public LogoutServlet() {
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//清除session
request.getSession().removeAttribute(Constants.USER_SESSION);//移除session
response.sendRedirect(request.getContextPath()+"/login.jsp");//重定向
}
@Override
public void init() throws ServletException {
}
}
注册xml
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.qia.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登录拦截优化
编写一个过滤器,并注册
filter解决
package com.qia.filter;
import com.qia.pojo.User;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 判断是否退出登录
* */
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println(" =========== SysFilter doFilter() =========== ");
HttpServletRequest rq = (HttpServletRequest)request;
HttpServletResponse rp = (HttpServletResponse)response;
//过滤器,从session中获取用户
User userSession = (User)rq.getSession().getAttribute("userSession");
// if(null == userSession){
if(userSession == null){//未登录,已经被移除或者注销了
rp.sendRedirect(rq.getContextPath()+"/error.jsp");//重定向
}else{//已登录,通行
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
xml注册
<!-- 用户登录过滤器 -->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.qia.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
servlet结构:
构造器
初始化
销毁
doget
dopost
filter结构:
初始化
doFilter
销毁
测试,登录,注销,权限,都要保证OK
密码修改
4. smbms密码修改实现
1、导入前端素材
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/common/head.jsp"%>
<div class="right">
<div class="location">
<strong>你现在所在的位置是:</strong>
<span>密码修改页面</span>
</div>
<div class="providerAdd">
<form id="userForm" name="userForm" method="post" action="${pageContext.request.contextPath }/jsp/user.do">
<input type="hidden" name="method" value="savepwd">
<!--div的class 为error是验证错误,ok是验证成功-->
<div class="info">${message}</div>
<div class="">
<label for="oldPassword">旧密码:</label>
<input type="password" name="oldpassword" id="oldpassword" value="">
<font color="red"></font>
</div>
<div>
<label for="newPassword">新密码:</label>
<input type="password" name="newpassword" id="newpassword" value="">
<font color="red"></font>
</div>
<div>
<label for="newPassword">确认新密码:</label>
<input type="password" name="rnewpassword" id="rnewpassword" value="">
<font color="red"></font>
</div>
<div class="providerAddBtn">
<!--<a href="#">保存</a>-->
<input type="button" name="save" id="save" value="保存" class="input-button">
</div>
</form>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/pwdmodify.js"></script>
2、代码实现分析
需求分析 从前往后
代码实现 从后往前
3、UserDao 接口
/**
* 修改当前用户密码
* @param connection
* @param id
* @param pwd
* @return
* @throws Exception
*/
public int updatePwd(Connection connection, int id, String pwd)throws Exception;
4、UserDao 接口实现类
//修改当前用户密码
@Override
public int updatePwd(Connection connection, int id, String pwd)
throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
String sql = "update smbms_user set userPassword= ? where id = ?";
Object[] params = {pwd, id};
int execute = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
return execute;
}
###/5、UserService层接口
/**
* 根据userId修改密码
* @param id
* @param pwd
* @return
*/
public boolean updatePwd(int id, String pwd);
6、UserService实现类
//修改密码
//业务逻辑:执行dao层数据库修改密码,成功返回boolean
@Override
public boolean updatePwd(int id, String pwd) {
Connection connection = null;
boolean flag = false;
try{
connection = BaseDao.getConnection();
if(userDao.updatePwd(connection,id,pwd) > 0) {
flag = true;
}
}catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return flag;
}
7、实现servlet复用
实现servlet复用,记得提出方法,在dopost里根据方法去分别调用
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String method = request.getParameter("method");
if(method != null && method.equals("savepwd")){
this.updatePwd(request, response);
}
private void updatePwd(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从session里面拿user信息
Object o = request.getSession().getAttribute(Constants.USER_SESSION);
//获取参数新密码
String newpassword = request.getParameter("newpassword");
boolean flag = false;
if(o != null && !StringUtils.isNullOrEmpty(newpassword)){//不为null且不为“”空字符串
UserService userService = new UserServiceImpl();
flag = userService.updatePwd(((User)o).getId(),newpassword);
if(flag){
request.setAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录!");
request.getSession().removeAttribute(Constants.USER_SESSION);//session注销
}else{
request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败!");
}
}else{
request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败!");
}
request.getRequestDispatcher("pwdmodify.jsp").forward(request, response);//请求转发
}
请求与重定向
- 使用情况:
- 如果希望跳转前后地址栏地址不会发生变化, 只能使用转发;
如果希望跳转前后地址栏地址会发生变化, 只能使用重定向; - 如果你要跳转的那个页面需要用到你本页的参数,就用转发,反之不需要则可以用重定向
- 转发是服务器内部跳转,数据不会丢失,浏览器只提交了一次请求
重定向是客户端二次跳转,数据会丢失,浏览器提交了二次请求 - 如果仅仅是做一个跳转,没有其他要求,此时推荐使用转发(转发是一次请求,一次响应,可以减少访问服务器的次数,降低服务器的压力)
- 如果请求中有表单数据,而数据又比较重要,不能重复提交,建议使用重定向
- 如果请求被Servlet接收后,无法进行处理,建议使用重定向定位到可以处理的资源,但因为是两次请求数据无法流转过来还想用第一次的数据,这时候就要用session。
- 做增、删、改的时候最好用重定向,因为如果不用重定向,每次刷新页面就相当于再请求一次,就可能会做额外的操作,导致数据不对。
- 如果希望跳转前后地址栏地址不会发生变化, 只能使用转发;
- 对比:
- 请求转发
请求转发:req.getRequestDispatcher(“要转发的jsp”).forward(req,resp);
弊端
1、由于是一次请求内,所以地址栏不改变,容易造成用户重复刷新,每刷一次就重新登录一次。
什么情况下可以用请求转发呢:请求数据中的表单数据可以允许重复的提交,提交一次重新再处理一次问题不大。
什么情况下不可以用请求转发呢:如果用户数据已经处理完了,如果用户再刷新就不能再执行了,这时候为了保证数据不被变更就不可以
2、当前的请求,Servlet无法进行处理
表单数据:是html收集的数据的实体,刷一次就提交一次 - 重定向
resp.sendRedirect(“要定向的url”);
特点:
两次请求,两个request对象
浏览器地址栏信息改变
- 请求转发
Ctrl + shift + - 代码最小化块 快捷键
8、测试
5. Ajax验证旧密码实现(使用Ajax优化密码修改)
1、阿里巴巴的fastjson
<!--fastjson依赖-处理json字符串-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
2、后台代码
//验证旧密码,session中有用户的密码
private void getPwdByUserId(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从session里面拿user的id
Object o = request.getSession().getAttribute(Constants.USER_SESSION);
//获取用户输入的旧密码
String oldpassword = request.getParameter("oldpassword");
//存旧密码输入判断的结果的集合
Map<String, String> resultMap = new HashMap<String, String>();//万能的Map:结果集
// if(null == o ){//session过期 或者 session失效
if(o == null ){
//session过期
resultMap.put("result", "session-error");
}
else if(StringUtils.isNullOrEmpty(oldpassword)){
//旧密码输入为空或者为空字符串
resultMap.put("result", "isNullOrEmpty-error");
}
else{
//进行判断旧密码输入是否正确
String sessionPwd = ((User)o).getUserPassword();
if(oldpassword.equals(sessionPwd)){//旧密码输入正确
resultMap.put("result", "true");
}else{//旧密码输入不正确
resultMap.put("result", "false");
}
}
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
//JSONArray 阿里巴巴的JSON工具类,转换格式
/*
resultMap = [<"result","session-error">,<"result","isNullOrEmpty-error">]
JSON格式 = {key:value}
*/
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
3、js代码
聚焦,失焦,事件
var oldpassword = null;
var newpassword = null;
var rnewpassword = null;
var saveBtn = null;
$(function(){
oldpassword = $("#oldpassword");
newpassword = $("#newpassword");
rnewpassword = $("#rnewpassword");
saveBtn = $("#save");
oldpassword.next().html("*");
newpassword.next().html("*");
rnewpassword.next().html("*");
oldpassword.on("blur",function(){
$.ajax({
type:"GET",
url:path+"/jsp/user.do",
//path+"/jsp/user.do?method="pwdmodify"&oldpassword=oldpassword.val()
//url&data
data:{method:"pwdmodify",oldpassword:oldpassword.val()},//Ajax传递的参数
dataType:"json",//主流开发都是用JSON实现前后端 {键值对}
success:function(data){
if(data.result == "true"){//旧密码正确
validateTip(oldpassword.next(),{"color":"green"},imgYes,true);
}else if(data.result == "false"){//旧密码输入不正确
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 原密码输入不正确",false);
}else if(data.result == "sessionerror"){//当前用户session过期,请重新登录
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 当前用户session过期,请重新登录",false);
}else if(data.result == "error"){//旧密码输入为空
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请输入旧密码",false);
}
},
error:function(data){
//请求出错
validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请求错误",false);
}
});
}).on("focus",function(){
validateTip(oldpassword.next(),{"color":"#666666"},"* 请输入原密码",false);
});
newpassword.on("focus",function(){
validateTip(newpassword.next(),{"color":"#666666"},"* 密码长度必须是大于6小于20",false);
}).on("blur",function(){
if(newpassword.val() != null && newpassword.val().length > 5
&& newpassword.val().length < 20 ){
validateTip(newpassword.next(),{"color":"green"},imgYes,true);
}else{
validateTip(newpassword.next(),{"color":"red"},imgNo + " 密码输入不符合规范,请重新输入",false);
}
});
rnewpassword.on("focus",function(){
validateTip(rnewpassword.next(),{"color":"#666666"},"* 请输入与上面一致的密码",false);
}).on("blur",function(){
if(rnewpassword.val() != null && rnewpassword.val().length > 5
&& rnewpassword.val().length < 20 && newpassword.val() == rnewpassword.val()){
validateTip(rnewpassword.next(),{"color":"green"},imgYes,true);
}else{
validateTip(rnewpassword.next(),{"color":"red"},imgNo + " 两次密码输入不一致,请重新输入",false);
}
});
saveBtn.on("click",function(){
oldpassword.blur();
newpassword.blur();
rnewpassword.blur();
if(oldpassword.attr("validateStatus") == "true"
&& newpassword.attr("validateStatus") == "true"
&& rnewpassword.attr("validateStatus") == "true"){
if(confirm("确定要修改密码?")){
$("#userForm").submit();
}
}
});
});
AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
三步曲:
1、编写对应处理的controller,返回消息或者字符串或者json格式的数据
2、编写ajax请求
url:controller请求
data:键值对
success:回调函数
3、给ajax绑定事件:
点击click,失去焦点onblur,键盘弹起keyup
web.xml
<!-- 设置session默认的过期时间:真实业务需求(30min) -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
4、测试
用户管理实现
6. smbms用户管理底层实现
思路:
1、导入分页的工具类
2、用户列表页面导入
工具类
PageSupport
前端页面
userlist.jsp
rollpage.jsp
后端实现
userservlet等
1、获取用户数量
1、UserDao
/**
* 通过条件查询-用户表记录数(根据用户名或者角色查询用户总数court)
* @param connection
* @param userName
* @param userRole
* @return
* @throws Exception
*/
public int getUserCount(Connection connection, String userName, int userRole)throws Exception;
2、UserDaoImpl
//通过条件查询-用户表记录数
// 根据用户名或者角色查询用户总数court
// 理解一下这个SQL,是拼接的用法
@Override
public int getUserCount(Connection connection, String userName, int userRole)
throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
ResultSet rs = null;
int count = 0;
if (connection != null) {
StringBuffer sql = new StringBuffer();//准备sql语句
sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");
List<Object> list = new ArrayList<Object>();
//判断是否需要拼接 userName
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" and u.userName like ?");
list.add("%" + userName + "%");
}
//判断是否需要拼接 userRole
if (userRole > 0) {
sql.append(" and u.userRole = ?");
list.add(userRole);
}
Object[] params = list.toArray();//准备传参的参数,将req的list转成数组存入传参数组
System.out.println("sql ----> " + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);//执行sql
if (rs.next()) {
count = rs.getInt("count");//从结果集中获取最终的数据
}
BaseDao.closeResource(null, pstm, rs);
}
return count;
}
3、UserService
/**
* 根据条件查询用户表记录数
* @param queryUserName
* @param queryUserRole
* @return
*/
public int getUserCount(String queryUserName, int queryUserRole);
4、UserServiceImpl
//通过查询获得用户总数
@Override
public int getUserCount(String queryUserName, int queryUserRole) {
// TODO Auto-generated method stub
Connection connection = null;
int count = 0;
//获取servlet传过来的参数 queryUserName ,queryUserRole
System.out.println("queryUserName ---- > " + queryUserName);
System.out.println("queryUserRole ---- > " + queryUserRole);
try {
connection = BaseDao.getConnection();//获取连接
count = userDao.getUserCount(connection, queryUserName,queryUserRole);//执行dao层方法
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return count;
}
5、test
@Test
public void test3(){
UserServiceImpl userService = new UserServiceImpl();
int userCount = userService.getUserCount(null,1);
// int userCount = userService.getUserCount("孙",0);
System.out.println("userCount ---- > "+userCount);
//select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id //联表操作
// and u.userName like ?
// and u.userRole = ?
}
2、获取用户列表
1、UserDao
/**
* 通过条件查询-userList(得到list)
* @param connection
* @param userName
* @param userRole
* @return
* @throws Exception
*/
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)throws Exception;
2、UserDaoImpl
//获取用户列表(根据条件查询,也需要拼接sql)
@Override
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)
throws Exception {
// TODO Auto-generated method stub
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>();//用list传参
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" and u.userName like ?");
list.add("%" + userName + "%");
}
if (userRole > 0) {
sql.append(" and u.userRole = ?");
list.add(userRole);
}
//拼接limit分页的sql(根据创建时间,降序,排序)
// 在数据库中,分页使用Limit(startIndex,pageSize)
// 第一页从0开始,第二页从1*pageSize开始
// 当前页首条记录 = (传进来的当前页首条记录-1)*页面条数容量大小
sql.append(" order by creationDate DESC limit ?,?");
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.closeResource(null, pstm, rs);
}
return userList;
}
3、UserService
/**
* 根据条件查询用户列表
* @param queryUserName
* @param queryUserRole
* @return
*/
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize);
4、UserServiceImpl
//根据条件查询用户列表
@Override
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
// TODO Auto-generated method stub
Connection connection = null;
List<User> userList = null;
System.out.println("queryUserName ---- > " + queryUserName);//查询条件:query_UserName//用户名含有的字
System.out.println("queryUserRole ---- > " + queryUserRole);//查询条件: queryUserRole//用户角色
System.out.println("currentPageNo ---- > " + currentPageNo);//查询条件: currentPageNo//当前页请求的首条记录的号数
System.out.println("pageSize ---- > " + pageSize);//查询条件: pageSize//当前页请求的记录条数
try {
connection = BaseDao.getConnection();//连接
userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize);//调用dao执行
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return userList;
}
3、获取角色列表
1、RoleDao
//获取角色列表
public List<Role> getRoleList(Connection connection)throws Exception;
2、RoleDaoImpl
//获取角色列表
@Override
public List<Role> getRoleList(Connection connection) throws Exception {
PreparedStatement pstm = 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, pstm, rs, sql, params);
while(rs.next()){
Role _role = new Role();
_role.setId(rs.getInt("id"));
_role.setRoleCode(rs.getString("roleCode"));
_role.setRoleName(rs.getString("roleName"));
roleList.add(_role);
}
BaseDao.closeResource(null, pstm, rs);
}
return roleList;
}
3、RoleService
//获取角色列表
public List<Role> getRoleList();
4、RoleServiceImpl
//获取角色列表
@Override
public List<Role> getRoleList() {
Connection connection = null;
List<Role> roleList = null;
try {
connection = BaseDao.getConnection();
roleList = roleDao.getRoleList(connection);
} catch (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return roleList;
}
5、test
@Test
public void test4(){
RoleServiceImpl roleService = new RoleServiceImpl();
List<Role> roleList = roleService.getRoleList();
for (Role role : roleList) {
System.out.println(role.getRoleName());
}
// System.out.println(Arrays.toString(roleList.toArray()));
}
4、用户显示的servlet
1、获取用户前端的数据(查询的条件)
2、判断请求是否需要执行,看参数的值判断
3、为了实现分页,需要计算出当前页码和总页码,页面大小…
4、用户列表展示
5、返回前端的参数
/*
doPost()
else if(method != null && method.equals("getrolelist")){
//获取角色列表
this.getRoleList(request, response);
}
*/
//用户管理页面(查询用户列表、分页)(重点、难点)
private void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从前端获取数据 //注意这些前后端参数命名的不同
String queryUserName = request.getParameter("queryname");//queryname -- queryUserName//此处变量名对照关系 前端 -- 后端
String temp = request.getParameter("queryUserRole");//queryUserRole -- temp(queryUserRole)//传过来的参数是字符串String型的,这个后端变量实际需要的是数值型的,后面需要转换,所以用temp
String pageIndex = request.getParameter("pageIndex");//pageIndex -- pageIndex(currentPageNo)//传过来的参数是字符串String型的,这个后端变量实际需要的是数值型的,后面需要转换,所以实际上对应的变量名是currentPageNo
//赋初值:定义 前端数据 字符串 转换成 数值型 后的变量
int queryUserRole = 0;//temp会转成queryUserRole,先赋个默认值
int currentPageNo = 1;//当前页码,第一次走页面一定是第一页//pageIndex会转成currentPageNo,先赋个默认值,后面可再赋值
//处理前端传的值,转换成后端实际需要的值
if(queryUserName == null){//前端传的为空时,对应的传入值
queryUserName = "";
}
if(temp != null && !temp.equals("")){//queryUserRole//前端传的 0,1,2,3
queryUserRole = Integer.parseInt(temp);//给查询赋值,传过来的参数是字符串String型的,这个变量需要的是数值型的
}
if(pageIndex != null){
currentPageNo = Integer.parseInt(pageIndex);
// try{
// currentPageNo = Integer.valueOf(pageIndex);
// }catch(NumberFormatException e){
// response.sendRedirect("error.jsp");
// }
}
/*
1,Integer.valueOf()和Integer.parseInt()的作用:
Integer.valueOf()和Integer.valueOf()这两个方法都是Integer的静态方法,都可以传入一个只包含整数的字符串类型,将其转换为整数。
2,Integer.valueOf()和Integer.parseInt()的不同:
Integer.valueOf()和Integer.valueOf()两个方法的 返回值类型不一样
Integer.valueOf()返回一个 Integer 类型的数据,是int的包装类 -- 装箱
Integer.parseInt()返回一个 int 类型的数据。 -- 拆箱
!!!如果使用int类型数据接受返回值,两者没有什么不同,但是如果使用Integer类型数据接受返回值,Integer.valueOf()会报警告。
3,Integer.valueOf().intValue()和Integer.parseInt()是相同的:
Integer.valueOf().intValue() 和 Integer.parseInt() 都返回int类型数据,他们两个的结果是完全相同的。
4,自动装箱 和 自动拆箱
*/
//控制台输出处理后的数据(前端-->后端)
System.out.println("query UserName servlet -------- >" + queryUserName);
System.out.println("query UserRole servlet -------- >" + queryUserRole);
System.out.println("query currentPageNo servlet--------- > " + currentPageNo);
//准备调用业务层
UserService userService = new UserServiceImpl();
int totalCount = userService.getUserCount(queryUserName,queryUserRole);//获取用户的总数
int pageSize = Constants.pageSize;//设置页面容量 //把页面大小放在配置文件Constants中,方便后期修改
//使用工具类 PageSupport :主要为了获取 总页码
// 4个成员变量:
// currentPageNo 当前页码 已定义 已获值
// totalCount 总用户记录数 已定义 已获值
// pageSize 页面大小 已定义 已获值
// totalPageCount 总页数 待定义 待计算 (set前三个变量 后自动得出)
PageSupport pages=new PageSupport();
//当前页码
pages.setCurrentPageNo(currentPageNo);
//页面容量
pages.setPageSize(pageSize);
//用户总数
pages.setTotalCount(totalCount);
//只要上面三个变量就可以实例化一个PageSupport对象了 -- 也就可以直接get总页数了
//总页数
int totalPageCount = pages.getTotalPageCount();
//控制首页和尾页
if(currentPageNo < 1){//首页
currentPageNo = 1;
}else if(currentPageNo > totalPageCount){//尾页
currentPageNo = totalPageCount;
}
//获取用户列表
List<User> userList = null;
userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize);
//获取角色列表
List<Role> roleList = null;
RoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
//给传回去的前端的参数赋值
request.setAttribute("userList", userList);//用户列表
request.setAttribute("roleList", roleList);//角色列表
request.setAttribute("totalPageCount", totalPageCount);//总页数
request.setAttribute("totalCount", totalCount);//用户总数
request.setAttribute("currentPageNo", currentPageNo);//当前页码
//前端页面查询后,为了使查询条件栏里还保持着查询的条件,要把这两个参数传回去
request.setAttribute("queryUserName", queryUserName);//用户名
request.setAttribute("queryUserRole", queryUserRole);//用户角色
//转发请求
request.getRequestDispatcher("userlist.jsp").forward(request, response);
}
小黄鸭调试法 (自言自语,向 他人/物 梳理一遍代码逻辑)
7. smbms用户管理分页OK
userlist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@include file="/jsp/common/head.jsp" %>
<div class="right">
<div class="location">
<strong>你现在所在的位置是:</strong>
<span>用户管理页面</span>
</div>
<div class="search">
<form method="get" action="${pageContext.request.contextPath }/jsp/user.do">
<input name="method" value="query" class="input-text" type="hidden">
<span>用户名:</span>
<input name="queryname" class="input-text" type="text" value="${queryUserName }">
<span>用户角色:</span>
<select name="queryUserRole">
<c:if test="${roleList != null }">
<option value="0">--请选择--</option>
<c:forEach var="role" items="${roleList}">
<option>
<c:if test="${role.id == queryUserRole }">selected="selected"</c:if>
value="${role.id}">${role.roleName}
</option>
</c:forEach>
</c:if>
</select>
<input type="hidden" name="pageIndex" value="1"/>
<input value="查 询" type="submit" id="searchbutton">
<a href="${pageContext.request.contextPath}/jsp/useradd.jsp">添加用户</a>
</form>
</div>
<!--用户-->
<table class="providerTable" cellpadding="0" cellspacing="0">
<tr class="firstTr">
<th width="10%">用户编码</th>
<th width="20%">用户名称</th>
<th width="10%">性别</th>
<th width="10%">年龄</th>
<th width="10%">电话</th>
<th width="10%">用户角色</th>
<th width="30%">操作</th>
</tr>
<c:forEach var="user" items="${userList }" varStatus="status">
<tr>
<td>
<span>${user.userCode }</span>
</td>
<td>
<span>${user.userName }</span>
</td>
<td>
<span>
<c:if test="${user.gender==1}">男</c:if>
<c:if test="${user.gender==2}">女</c:if>
</span>
</td>
<td>
<span>${user.age}</span>
</td>
<td>
<span>${user.phone}</span>
</td>
<td>
<span>${user.userRoleName}</span>
</td>
<td>
<span><a class="viewUser" href="javascript:;" userid=${user.id } username=${user.userName }><img
src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a></span>
<span><a class="modifyUser" href="javascript:;" userid=${user.id } username=${user.userName }><img
src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span>
<span><a class="deleteUser" href="javascript:;" userid=${user.id } username=${user.userName }><img
src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a></span>
</td>
</tr>
</c:forEach>
</table>
<input type="hidden" id="totalPageCount" value="${totalPageCount}"/>
<c:import url="rollpage.jsp">
<c:param name="totalCount" value="${totalCount}"/>
<c:param name="currentPageNo" value="${currentPageNo}"/>
<c:param name="totalPageCount" value="${totalPageCount}"/>
</c:import>
</div>
</section>
<!--点击删除按钮后弹出的页面-->
<div class="zhezhao"></div>
<div class="remove" id="removeUse">
<div class="removerChid">
<h2>提示</h2>
<div class="removeMain">
<p>你确定要删除该用户吗?</p>
<a href="#" id="yes">确定</a>
<a href="#" id="no">取消</a>
</div>
</div>
</div>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/userlist.js"></script>
rollpage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<script type="text/javascript">
</script>
</head>
<body>
<div class="page-bar">
<ul class="page-num-ul clearfix">
<li>共${param.totalCount }条记录 ${param.currentPageNo }/${param.totalPageCount }页</li>
<c:if test="${param.currentPageNo > 1}">
<a href="javascript:page_nav(document.forms[0],1);">首页</a>
<a href="javascript:page_nav(document.forms[0],${param.currentPageNo-1});">上一页</a>
</c:if>
<c:if test="${param.currentPageNo < param.totalPageCount }">
<a href="javascript:page_nav(document.forms[0],${param.currentPageNo+1 });">下一页</a>
<a href="javascript:page_nav(document.forms[0],${param.totalPageCount });">最后一页</a>
</c:if>
</ul>
<span class="page-go-form"><label>跳转至</label>
<input type="text" name="inputPage" id="inputPage" class="page-key" />页
<button type="button" class="page-btn" onClick='jump_to(document.forms[0],document.getElementById("inputPage").value)'>GO</button>
</span>
</div>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/rollpage.js"></script>
</html>
PageSupport
package com.qia.tools;
//工具类:总页数支持
public class PageSupport {
//4个成员变量
//当前页码-来自于用户输入
private int currentPageNo = 1;
//总用户记录数
private int totalCount = 0;
//页面容量
private int pageSize = 0;
//总页数 - totalCount/pageSize(+1)//即使没有记录页也至少是一页
private int totalPageCount = 1;
//以下是set和get方法
//当前页码
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;
//设置总页数 //为什么在这里调用设置总页数,因为默认总页数是1,如果有总用户数( >0),那才有必要计算总页数
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;
}
//下面是方法,用于计算: 总用户数 / 页面容量 = 总页数 totalPageCount
//这个类实例化时,setTotalCount会直接调用这个方法
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;
}
}
}
js
var userObj;
//用户管理页面上点击删除按钮弹出删除框(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"){//删除成功:移除删除行
cancelBtn();
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("对不起,删除失败");
}
});
}
function openYesOrNoDLG(){
$('.delView').css('display', 'block');
$('#removeUse').fadeIn();
}
function cancelBtn(){
$('.delView').css('display', 'none');
$('#removeUse').fadeOut();
}
function changeDLGContent(contentStr){
var p = $(".removeMain").find("p");
p.html(contentStr);
}
$(function(){
//通过jquery的class选择器(数组)
//对每个class为viewUser的元素进行动作绑定(click)
/**
* bind、live、delegate
* on
*/
$(".viewUser").on("click",function(){
//将被绑定的元素(a)转换成jquery对象,可以使用jquery方法
var obj = $(this);
window.location.href=path+"/jsp/user.do?method=view&uid="+ obj.attr("userid");
});
$(".modifyUser").on("click",function(){
var obj = $(this);
window.location.href=path+"/jsp/user.do?method=modify&uid="+ obj.attr("userid");
});
$('#no').click(function () {
cancelBtn();
});
$('#yes').click(function () {
deleteUser(userObj);
});
$(".deleteUser").on("click",function(){
userObj = $(this);
changeDLGContent("你确定要删除用户【"+userObj.attr("username")+"】吗?");
openYesOrNoDLG();
});
/*$(".deleteUser").on("click",function(){
var obj = $(this);
if(confirm("你确定要删除用户【"+obj.attr("username")+"】吗?")){
$.ajax({
type:"GET",
url:path+"/jsp/user.do",
data:{method:"deluser",uid:obj.attr("userid")},
dataType:"json",
success:function(data){
if(data.delResult == "true"){//删除成功:移除删除行
alert("删除成功");
obj.parents("tr").remove();
}else if(data.delResult == "false"){//删除失败
alert("对不起,删除用户【"+obj.attr("username")+"】失败");
}else if(data.delResult == "notexist"){
alert("对不起,用户【"+obj.attr("username")+"】不存在");
}
},
error:function(data){
alert("对不起,删除失败");
}
});
}
});*/
});
8. smbms架构分析及方法学习
分析新增用户的思路
…
总结
前端 --> 过滤器 --> 查询 --> 更新(增删改)–> servlet --> service --> dao --> jdbc --> mysql