目錄
- 一,bookstore order management system
-
- bookstore order management system_address
- bookstore order management system_bill
- bookstore order management system_provider
- bookstore order management system_role(使用者角色表)
- bookstore order management system_user
- 二,項目如何搭建?
-
- 搭建項目準備工作
-
- 1,搭建一個maven web 項目
- 2,配置Tomcat
- 3,測試項目是否能夠跑起來
- 4,導入項目中需要的jar包;
- 5,建構項目包結構
- 6,編寫實體類
- 7,編寫基礎公共類
-
- (1)資料庫配置檔案(mysql5.xx和8.xx的編寫有差異)
- (2)編寫資料庫的公共類
- (3)編寫字元編碼過濾器
- 8,導入靜态資源
- 三,登入功能實作
-
- 1,編寫前端頁面
- 2,設定首頁
- 3,編寫dao層登入使用者登入的接口 UserDao
- 4,編寫dao層接口的實作類 UserDaoImpl
- 5,業務層接口 UserService
- 6,業務層實作類
- 7,編寫Servlet LoginServlet
- 8,注冊Servlet
- 9,測試通路,保證以上功能可以成功
- 四,登入功能優化
-
- 登出功能 LogoutServlet
- 登入攔截優化
- 五,密碼修改
-
- 1,導入前端素材
- 2,寫項目,建議從底層向上寫
- 3,UserDao接口
- 4,UserDao接口實作類
- 5,UserService層
- 6,UserService實作類
- 7,servlet記得實作複用,要提取出方法!
- 8,測試
- 六,優化密碼修改使用Ajax
-
- 1,阿裡巴巴的fastjson
- 2,pwdmodify.js
- 3,通過ajax驗證舊密碼,session中有使用者的密碼
- 4,測試
- 七,使用者管理實作
-
- 1,擷取使用者數量
- 2,擷取使用者清單
- 3,擷取角色清單
- 4,使用者顯示的Servlet UserServlet
- 5,使用者管理子產品—添加使用者功能
- 6,使用者管理子產品—删除使用者功能
- 7,使用者管理子產品—修改使用者功能
- 8,使用者管理子產品—檢視使用者資訊功能
- 9, layui 開源子產品化前端 UI 架構 月曆元件(Calendar)
- 10,反編譯
- 八,項目整體架構
- 九,供應商管理
-
- 1,擷取供應商清單
- 2,使用者顯示的Servlet ProviderServlet
- 3,供應商管理子產品—添加供應商功能
- 4,供應商管理子產品—删除供應商功能
- 5,供應商管理子產品—修改供應商功能
- 6,供應商管理子產品—檢視供應商資訊功能
- 十,訂單管理
-
- 1,擷取訂單清單
- 2,使用者顯示的Servlet BillServlet
- 3,擷取訂單供應商清單
- 4,訂單管理子產品—添加訂單功能
- 5,訂單管理子產品—删除訂單功能
- 6,訂單管理子產品—修改訂單功能
- 7,訂單管理子產品—檢視訂單資訊功能
一,bookstore order management system
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHLzkEVPNTQU50dVpHW3BjMMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL5ETYhFmM3QDOwgTYwIWZhZDO3QDZhJTNhVWYjRGZxM2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
資料庫:Bookstore order management system
bookstore order management system_address
CREATE DATABASE `Bookstore order management system`;
USE `Bookstore order management system`;
DROP TABLE IF EXISTS `Bookstore order management system order_address`;
CREATE TABLE `Bookstore order management system_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 `Bookstore order management system_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);
bookstore order management system_bill
DROP TABLE IF EXISTS `Bookstore order management system_bill`;
CREATE TABLE `Bookstore order management system_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 `Bookstore order management system_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','C++參考大全','大學教材','本','500.00','23000.00',1,1,'2016-07-22 10:10:22',NULL,NULL,14),
(8,'BILL2016_008','《IT經濟學》','大學教材','本','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','《MATLAB程式設計和計算機仿真》','大學教材','本','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','Java','大學教材','本','2000.00','4000.00',2,1,'2015-11-24 15:12:03',NULL,NULL,2);
bookstore order management system_provider
DROP TABLE IF EXISTS `Bookstore order management system_provider`;
CREATE TABLE `Bookstore order management system_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 `Bookstore order management system_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','廣東省深圳市福田區','0755-67776212',1,'2014-03-21 16:56:07',NULL,NULL),
(4,'GZ_GYS002','漂移有限公司','專賣飄移','林妮','18599897645','廣東省深圳市','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','北京市朝陽區珠江帝景','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','廣西','0771-98861134',1,'2013-03-21 19:52:07',NULL,NULL),
(10,'JS_GYS002','等你下課有限公司','專賣等你下課,副業賣課本','陳女士','13098992113','江蘇省','025-86223345',1,'2013-03-25 16:52:07',NULL,NULL),
(11,'GZ_GYS003','愛在西元前公司','專賣愛在西元前,副業賣課本','梁天','13562276775','廣州市','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','山東濟陽','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);
bookstore order management system_role(使用者角色表)
DROP TABLE IF EXISTS `Bookstore order management system_role`;
CREATE TABLE `Bookstore order management system_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 `Bookstore order management system_role`(`id`,`roleCode`,`roleName`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) values
(1,'ADMIN','系統管理者',1,'2016-04-13 00:00:00',NULL,NULL),
(2,'MANAGER','經理',1,'2016-04-13 00:00:00',NULL,NULL),
(3,'EMPLOYEE','普通員工',1,'2016-04-13 00:00:00',NULL,NULL);
bookstore order management system_user
DROP TABLE IF EXISTS `Bookstore order management system_user`;
CREATE TABLE `Bookstore order management system_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 `Bookstore order management system_user`(`id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) values
(1,'admin','系統管理者','1234567',1,'1983-10-10','13688889999','北京市',1,1,'2013-03-21 16:52:07',NULL,NULL),
(2,'liming','李明','0000000',2,'1983-12-10','13688884457','北京市東大街',2,1,'2014-12-31 19:52:09',NULL,NULL),
(5,'zhangsan','張三','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,'wangwu','王五','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,'sun大','孫大','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,'lisi','李四','0000000',1,'1986-03-28','18098765434','三期13号樓',3,1,'2016-08-09 05:52:37',1,'2016-04-14 14:15:36'),
(13,'zhaoliu','趙六','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,'shenxianjiejie','神仙姐姐','0000000',1,'1987-12-04','18099897657','天通苑3區12号樓',2,1,'2015-09-12 12:02:12',NULL,NULL);
二,項目如何搭建?
考慮是不是用maven? jar包,依賴
搭建項目準備工作
1,搭建一個maven web 項目
2,配置Tomcat
3,測試項目是否能夠跑起來
4,導入項目中需要的jar包;
jsp,Servlet,mysql驅動jstl,stand…
<dependencies>
<!--單元測試-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- Servlet依賴https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- JSP依賴https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!--JSTL表達式的依賴 https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!--standard标簽庫 https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--連接配接資料庫-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
</dependencies>
5,建構項目包結構
6,編寫實體類
ROM映射:表-類映射
7,編寫基礎公共類
(1)資料庫配置檔案(mysql5.xx和8.xx的編寫有差異)
(2)編寫資料庫的公共類
package com.wang.dao;
BaseDao
package com.wang.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* 操作資料庫的公共類
*/
public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;
//靜态代碼塊,在類加載的時候就初始化了
static {
Properties params = new Properties();
String configFile = "db.properties";
//通過類加載器讀取對應的資源
InputStream is = com.wang.dao.BaseDao.class.getClassLoader().getResourceAsStream(configFile);
try {
params.load(is);//加載流
} catch (IOException e) {
e.printStackTrace();
}
//擷取
driver = params.getProperty("driver");
url = params.getProperty("url");
username = params.getProperty("username");
password = params.getProperty("password");
}
/**
* 擷取資料庫連接配接
* @return
*/
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName(driver);//固定寫法,加載驅動
//連接配接成功,資料庫對象,connection代表資料庫
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
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) {
try {
//預編譯sql
pstm = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
//setObject占位符從1開始
pstm.setObject(i + 1, params[i]);
}
rs = pstm.executeQuery();//執行SQL
} catch (SQLException throwables) {
throwables.printStackTrace();
}
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) {
//預編譯的sql,在後面直接執行就可以了
int updateRows = 0;
try {
pstm = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
updateRows = pstm.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
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) {
e.printStackTrace();
flag = false;//關閉出現錯誤
}
}
if (pstm != null) {
try {
pstm.close();
pstm = null;//GC回收
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (connection != null) {
try {
connection.close();
connection = null;//GC回收
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
//都釋放成功,傳回true
return flag;
}
}
(3)編寫字元編碼過濾器
package com.wang.filter;
CharacterEncoding
/**
* 字元編碼過濾器
* 過濾所有請求 /*
*/
@WebFilter("/*")
public class CharacterEncoding 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() {
}
}
web.xml
<!--字元編碼過濾器-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.wang.filter.CharacterEncoding</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
8,導入靜态資源
三,登入功能實作
1,編寫前端頁面
login.jsp
2,設定首頁
設定歡迎首頁
<!-- 設定歡迎頁面(首頁)-->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
3,編寫dao層登入使用者登入的接口 UserDao
/**
* 通過userCode擷取登陸的User
* @param connection
* @param userCode
* @return
* @throws Exception
*/
User getLoginUser(Connection connection, String userCode) throws Exception;
4,編寫dao層接口的實作類 UserDaoImpl
/**
* 得到要登入的使用者
*
* @param connection
* @param userCode
* @return
*/
public User getLoginUser(Connection connection, String userCode) throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
User user = null;
try {
if (null != connection) {
String sql = "select * from `bookstore order management system_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"));
}
}
//connection不用關,可能存在業務,我們需要到事務層,就是調業務的時候,
BaseDao.closeResource(null, pstm, rs);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return user;
}
業務層:
/**
* service層捕獲異常,進行事務處理
* 事務處理:調用不同dao的多個方法,必須使用同一個connection(connection作為參數傳遞)
* 事務完成之後,需要在service層進行connection的關閉,在dao層關閉(PreparedStatement和ResultSet對象)
* @author Administrator
*/
5,業務層接口 UserService
/**
* 使用者登入
* @param userCode
* @param userPassword
* @return
*/
public User login(String userCode, String userPassword);
6,業務層實作類
業務層都會調用dao層,是以我們要引入dao層
//業務層調用Dao層,是以我們要引入Dao層
private UserDao userDao;
public UserServiceImpl() {
userDao = new UserDaoImpl();
}
/**
* 使用者登入實作
*
* @param userCode
* @param userPassword
* @return
*/
public User login(String userCode, String userPassword) {
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
//通過業務層調用對應的具體資料庫操作
user = userDao.getLoginUser(connection, userCode);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
//比對密碼
if (null != user) {
if (!user.getUserPassword().equals(userPassword)) {
user = null;
}
}
return user;
}
@Test
public void loginTest(){
UserService userService=new UserServiceImpl();
User admin=userService.login("admin","1234567");
System.out.println(admin.getUserPassword());
}
7,編寫Servlet LoginServlet
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
//servlet : 控制層調業務層
private static final long serialVersionUID = -4672709233628500722L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//擷取使用者名和密碼
String userCode = request.getParameter("userCode");
String userPassword = request.getParameter("userPassword");
//調用service方法,進行使用者比對
UserService userService = new UserServiceImpl();
User user = userService.login(userCode, userPassword);//把登入的人查出來了
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);
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
8,注冊Servlet
<!--注冊Servlet-->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.wang.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
9,測試通路,保證以上功能可以成功
四,登入功能優化
登出功能 LogoutServlet
思路:移除session,傳回登入頁面
@WebServlet("/jsp/logout.do")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = -5088734013104489465L;
@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);
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
}
注冊xml
<!--登出 -->
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.wang.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登入攔截優化
編寫一個過濾器,并注冊
@WebFilter("/jsp/*")
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest rq = (HttpServletRequest) request;
HttpServletResponse rp = (HttpServletResponse) response;
//過濾器,從session中擷取使用者
User userSession = (User) rq.getSession().getAttribute("userSession");
if (null == userSession) {
//使用者已被移除或者登出,或者沒有登陸
rp.sendRedirect("/bookstore_order_management_system_war/error.jsp");
} else {
chain.doFilter(request, response);
}
}
public void destroy() {
}
}
注冊xml
<!-- 使用者登入過濾器 -->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.wang.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
五,密碼修改
1,導入前端素材
2,寫項目,建議從底層向上寫
從後往前寫
3,UserDao接口
/**
* 修改目前使用者密碼
*
* @param connection
* @param id
* @param pwd
* @return
* @throws Exception
*/
int updatePwd(Connection connection, int id, String pwd) throws Exception;
4,UserDao接口實作類
/**
* 修改目前使用者密碼
*
* @param connection
* @param id
* @param pwd
* @return
* @throws Exception
*/
public int updatePwd(Connection connection, int id, String pwd) throws Exception {
int flag = 0;
PreparedStatement pstm = null;
if (connection != null) {
String sql = "update `bookstore order management system_user` set userPassword= ? where id = ?";
Object[] params = {pwd, id};//參數封裝成數組
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
5,UserService層
/**
* 根據userId修改密碼
*
* @param id
* @param pwd
* @return
*/
public boolean updatePwd(int id, String pwd);
6,UserService實作類
public boolean updatePwd(int id, String pwd) {
boolean flag = false;
Connection connection = null;
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記得實作複用,要提取出方法!
在 dao層 和 service層 自己寫映射類和實作類
下面是 servlet層 的主體
//實作Servlet複用
@WebServlet("/jsp/user.do")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO 自動生成的方法存根
String method = req.getParameter("method");
if (method != "savepwd" && method != null) {
this.updatePwd(req, resp);
}
//實作複用~~~~~~
// 想添加新的增删改查,直接用if(method != "savepwd" && method != null);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO 自動生成的方法存根
doGet(req, resp);
}
public void updatePwd(HttpServletRequest req, HttpServletResponse resp) {
// 通過session獲得使用者id
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
boolean flag = false;
if (o != null && newpassword != null) {
UserService userService = new UserServiceImpl();
try {
flag = userService.updatePwd(((User) o).getId(), newpassword);
} catch (Exception e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
if (flag) {
req.setAttribute("message", "密碼修改成功,請退出,使用新密碼登入");
// 密碼修改成功,移除session(移除後不能再次修改密碼,建議不移除)
req.getSession().removeAttribute(Constants.USER_SESSION);
} else {
// 密碼修改失敗
req.setAttribute("message", "密碼修改失敗");
}
} else {
// 密碼修改有問題
req.setAttribute("message", "新密碼有問題");
}
try {
req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req, resp);
} catch (ServletException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
}
}
注冊xml
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.wang.servlet.user.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/jsp/user.do</url-pattern>
</servlet-mapping>
8,測試
六,優化密碼修改使用Ajax
1,阿裡巴巴的fastjson
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
2,pwdmodify.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",
data: {method: "pwdmodify", oldpassword: oldpassword.val()}, //ajax傳遞的參數
dataType: "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 > 6
&& 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 > 6
&& 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();
}
}
});
});
web.xml
<!--預設Session過期時間-->
<session-config>
<session-timeout>18</session-timeout>
</session-config>
3,通過ajax驗證舊密碼,session中有使用者的密碼
//通過ajax驗證舊密碼,session中有使用者的密碼
private void getPwdByUserId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//從session中拿Id
Object o = request.getSession().getAttribute(Constants.USER_SESSION);
String oldpassword = request.getParameter("oldpassword");
Map<String, String> resultMap = new HashMap();
if (null == o) {//session過期
resultMap.put("result", "sessionerror");
} else if (StringUtils.isNullOrEmpty(oldpassword)) {//舊密碼輸入為空
resultMap.put("result", "error");
} else {
//從session中取出使用者舊密碼
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工具類,轉換格式的
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
4,測試
七,使用者管理實作
(1)導入分頁的工具類-PageSupport
package com.wang.util;
public class PageSupport {
//目前頁碼-來自于使用者輸入
private int currentPageNo = 1;
//總數量(表)
private int totalCount = 0;
//頁面容量
private int pageSize = 0;
//總頁數-totalCount/pageSize(+1)
private int totalPageCount = 1;
public int getCurrentPageNo() {
return currentPageNo;
}
public void setCurrentPageNo(int currentPageNo) {
if (currentPageNo > 0) {
this.currentPageNo = currentPageNo;
}
}
public int getTotalCount() {
return totalCount;
}
//三大特性:封裝(屬性私有,get/set,在set中限定一些不安全的因素),繼承,多态
public void setTotalCount(int totalCount) {
if (totalCount > 0) {
this.totalCount = totalCount;
//設定總頁數
this.setTotalPageCountByRs();
}
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
if (pageSize > 0) {
this.pageSize = pageSize;
}
}
public int getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public void setTotalPageCountByRs() {
if (this.totalCount % this.pageSize == 0) {
this.totalPageCount = this.totalCount / this.pageSize;
} else if (this.totalCount % this.pageSize > 0) {
this.totalPageCount = this.totalCount / this.pageSize + 1;
} else {
this.totalPageCount = 0;
}
}
}
(2)使用者清單頁面導入-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>
(3)分頁–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>
1,擷取使用者數量
(1)UserDao
/**
* 通過條件查詢-根據使用者名或者角色查詢使用者總數
*
* @param connection
* @param userName
* @param userRole
* @return
* @throws Exception
*/
int getUserCount(Connection connection, String userName, int userRole) throws Exception;
(2)UserDaoImpl
//根據使用者名或者角色查詢使用者總數
public int getUserCount(Connection connection, String userName, int userRole) throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
int count = 0;
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("select count(1) as count from `bookstore order management system_user` u,`bookstore order management system_role` r where u.userRole = r.id");
//List用來儲存我們的參數
List<Object> list = new ArrayList();
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" and u.userName like ?");
list.add("%" + userName + "%");
}
if (userRole > 0) {
sql.append(" and u.userRole = ?");
list.add(userRole);
}
Object[] params = list.toArray();
System.out.println("sql ----> " + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
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
//查詢記錄數
public int getUserCount(String queryUserName, int queryUserRole) {
Connection connection = null;
int count = 0;
try {
connection = BaseDao.getConnection();
count = userDao.getUserCount(connection, queryUserName, queryUserRole);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return count;
}
2,擷取使用者清單
(1)UserDao
/**
* 通過條件查詢擷取使用者清單-userList
*
* @param connection
* @param userName
* @param userRole
* @return
* @throws Exception
*/
List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception;
(2)UserDaoImpl
//擷取使用者清單-userList
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 `bookstore order management system_user` u,`bookstore order management system_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);
}
//在mysql中,分頁使用 limit startIndex,pageSize ; 總數 DESC降序排列資料
sql.append(" order by creationDate DESC limit ?,?");
//目前頁=(目前頁-1)*頁面大小
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
// 根據條件查詢使用者清單
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("pageSize:"+pageSize);
try {
connection = BaseDao.getConnection();
userList = userDao.getUserList(connection, queryUserName, queryUserRole, currentPageNo, pageSize);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return userList;
}
3,擷取角色清單
為了我們的職責統一,我們可以把角色的操作單獨放在一個包中,和pojo類對應
(1)UserDao
/**
* 擷取角色清單
*
* @param connection
* @return
* @throws Exception
*/
List<Role> getRoleList(Connection connection) throws Exception;
(2)UserDaoImpl
/**
* 擷取角色清單
*
* @param connection
* @return
* @throws Exception
*/
public List<Role> getRoleList(Connection connection) throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
List<Role> roleList = new ArrayList();
if (connection != null) {
String sql = "select * from `bookstore order management system_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)UserService
/**
* 擷取角色清單
*
* @return
*/
public List<Role> getRoleList();
(4)UserServiceImpl
public class RoleServiceImpl implements RoleService {
//引入Dao
private RoleDao roleDao;
public RoleServiceImpl() {
roleDao = new RoleDaoImpl();
}
/**
* 擷取角色清單
*
* @return
*/
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;
}
}
4,使用者顯示的Servlet UserServlet
1,擷取使用者前端的資料(查詢)
2,判斷請求是否需要執行,看參數的值判斷
3,為了實作分頁,需要計算出目前頁面和總頁面,頁面大小…
4,使用者清單展示
5,傳回前端
private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//查詢使用者清單
//從前端擷取資料
String queryUserName = request.getParameter("queryname");
String temp = request.getParameter("queryUserRole");
String pageIndex = request.getParameter("pageIndex");
int queryUserRole = 0;
//擷取使用者清單
UserService userService = new UserServiceImpl();
List<User> userList = null;
//第一次走這個請求,一定是第一頁,頁面大小是固定的
//設定頁面容量
int pageSize = Constants.pageSize;
//預設目前頁碼
int currentPageNo = 1;
if (queryUserName == null) {
queryUserName = "";
}
//前端下拉框擷取角色,給查詢指派 0,1,2,3
if (temp != null && !temp.equals("")) {
queryUserRole = Integer.parseInt(temp);
}
//擷取目前第幾頁
if (pageIndex != null) {
try {
currentPageNo = Integer.valueOf(pageIndex);
} catch (NumberFormatException e) {
response.sendRedirect("error.jsp");
}
}
//使用者總數量(分頁:上一頁,下一頁)
int totalCount = userService.getUserCount(queryUserName, queryUserRole);
//總頁數 PageSupport
PageSupport pages = new PageSupport();
pages.setCurrentPageNo(currentPageNo); //目前頁
pages.setPageSize(pageSize); //頁面大小
pages.setTotalCount(totalCount); //總數量
int totalPageCount = pages.getTotalPageCount(); //總頁面數量
//控制首頁和尾頁,第一頁不能再往前,最後一頁不能再往後
//如果頁面小于第一頁,就顯示第一頁
if (currentPageNo < 1) {
currentPageNo = 1;
//如果目前頁面大于最後一頁,目前頁等于最後一頁即可
} else if (currentPageNo > totalPageCount) {
currentPageNo = totalPageCount;
}
//擷取使用者清單展示
userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
request.setAttribute("userList", userList);
//擷取角色清單
List<Role> roleList = null;
RoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
request.setAttribute("roleList", roleList);
request.setAttribute("queryUserName", queryUserName);
request.setAttribute("queryUserRole", queryUserRole);
request.setAttribute("totalPageCount", totalPageCount);
request.setAttribute("totalCount", totalCount);
request.setAttribute("currentPageNo", currentPageNo);
request.getRequestDispatcher("userlist.jsp").forward(request, response);
}
測試
調試方法:小黃鴨調試法:自言自語
5,使用者管理子產品—添加使用者功能
userlist.jsp
useradd.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/common/head.jsp"%>
<style>
.providerAdd{
background-color: #FFDEE9;
background-image: linear-gradient(0deg, #FFDEE9 0%, #B5FFFC 100%);
}
</style>
<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="add">
<!--div的class 為error是驗證錯誤,ok是驗證成功-->
<div>
<label for="userCode">使用者編碼:</label>
<input type="text" name="userCode" id="userCode" value="">
<!-- 放置提示資訊 -->
<font color="red"></font>
</div>
<div>
<label for="userName">使用者名稱:</label>
<input type="text" name="userName" id="userName" value="">
<font color="red"></font>
</div>
<div>
<label for="userPassword">使用者密碼:</label>
<input type="password" name="userPassword" id="userPassword" value="">
<font color="red"></font>
</div>
<div>
<label for="ruserPassword">确認密碼:</label>
<input type="password" name="ruserPassword" id="ruserPassword" value="">
<font color="red"></font>
</div>
<div>
<label >使用者性别:</label>
<select name="gender" id="gender">
<option value="1" selected="selected">男</option>
<option value="2">女</option>
</select>
</div>
<div>
<label for="birthday">出生日期:</label>
<input type="text" Class="Wdate" id="birthday" name="birthday"
readonly="readonly" onclick="WdatePicker();">
<font color="red"></font>
</div>
<div>
<label for="phone">使用者電話:</label>
<input type="text" name="phone" id="phone" value="">
<font color="red"></font>
</div>
<div>
<label for="address">使用者位址:</label>
<input name="address" id="address" value="">
</div>
<div>
<label >使用者角色:</label>
<!-- 列出所有的角色分類 -->
<select name="userRole" id="userRole"></select>
<font color="red"></font>
</div>
<div class="providerAddBtn">
<input type="button" name="add" id="add" value="儲存" >
<input type="button" id="back" name="back" value="傳回" >
</div>
</form>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/useradd.js"></script>
UserServlet
//添加使用者
private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userCode = request.getParameter("userCode");
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
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.setUserCode(userCode);
user.setUserName(userName);
user.setUserPassword(userPassword);
user.setAddress(address);
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
user.setGender(Integer.valueOf(gender));
user.setPhone(phone);
user.setUserRole(Integer.valueOf(userRole));
user.setCreationDate(new Date());
user.setCreatedBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
UserService userService = new UserServiceImpl();
if (userService.add(user)) {
response.sendRedirect(request.getContextPath() + "/jsp/user.do?method=query");
} else {
request.getRequestDispatcher("useradd.jsp").forward(request, response);
}
}
UserServiceImpl
一切的增删改都需要操作事務
connection.setAutoCommit(false);//開啟JDBC事務管理
如果成功Commit
如果失敗connection.rollback();復原
//添加使用者
public boolean add(User user) {
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);//開啟JDBC事務管理
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.closeResource(connection, null, null);
}
return flag;
}
UserDaoImpl
public int add(Connection connection, User user) throws Exception {
PreparedStatement pstm = null;
int updateRows = 0;
if (null != connection) {
String sql = "insert into `bookstore order management system_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.closeResource(null, pstm, null);
}
return updateRows;
}
測試:
6,使用者管理子產品—删除使用者功能
使用者管理頁面上點選删除按鈕彈出删除框(userlist.jsp)
userlist.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") {//删除成功:移除删除行
cancleBtn();
obj.parents("tr").remove();
} else if (data.delResult == "false") {//删除失敗
//alert("對不起,删除使用者【"+obj.attr("username")+"】失敗");
changeDLGContent("對不起,删除使用者【" + obj.attr("username") + "】失敗");
} else if (data.delResult == "notexist") {
//alert("對不起,使用者【"+obj.attr("username")+"】不存在");
changeDLGContent("對不起,使用者【" + obj.attr("username") + "】不存在");
}
},
error: function (data) {
//alert("對不起,删除失敗");
changeDLGContent("對不起,删除失敗");
}
});
}
function openYesOrNoDLG() {
$('.zhezhao').css('display', 'block');
$('#removeUse').fadeIn();
}
function cancleBtn() {
$('.zhezhao').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 () {
cancleBtn();
});
$('#yes').click(function () {
deleteUser(userObj);
});
$(".deleteUser").on("click", function () {
userObj = $(this);
changeDLGContent("你确定要删除使用者【" + userObj.attr("username") + "】嗎?");
openYesOrNoDLG();
});
});
UserServlet
//删除使用者
private void delUser(HttpServletRequest request, HttpServletResponse response)
throws ServletException, 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();
}
UserServiceImpl
//删除使用者
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.closeResource(connection, null, null);
}
return flag;
}
UserDaoImpl
//删除使用者
public int deleteUserById(Connection connection, Integer delId) throws Exception {
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
String sql = "delete from `bookstore order management system_user` where id=?";
Object[] params = {delId};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
測試:
userlist.jsp
<!--點選删除按鈕後彈出的頁面-->
<div class="zhezhao"></div>
<div class="remove" id="removeUse">
<div class="removerChid">
<h2>提示</h2>
<div class="removeMain">
<p>你确定要删除該使用者嗎?</p>
<a href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" id="yes">确定</a>
<a href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" id="no">取消</a>
</div>
</div>
</div>
7,使用者管理子產品—修改使用者功能
userlist.js
UserServlet
//修改使用者
private 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);
}
}
UserServiceImpl
//修改使用者
public User getUserById(String id) {
// TODO Auto-generated method stub
User user = null;
Connection connection = null;
try {
connection = BaseDao.getConnection();
user = userDao.getUserById(connection, id);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
user = null;
} finally {
BaseDao.closeResource(connection, null, null);
}
return user;
}
UserDaoImpl
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 `bookstore order management system_user` u,`bookstore order management system_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.closeResource(null, pstm, rs);
}
System.out.println(user);
return user;
}
測試:
usermodify.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@include file="/jsp/common/head.jsp" %>
<style>
.right{
background-color: #FEE140;
background-image: linear-gradient(90deg, #FEE140 0%, #FA709A 100%);
}
</style>
<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="modifyexe">
<input type="hidden" name="uid" value="${user.id }"/>
<div>
<label for="userName">使用者名稱:</label>
<input type="text" name="userName" id="userName" value="${user.userName }">
<font color="red"></font>
</div>
<div>
<label>使用者性别:</label>
<select name="gender" id="gender">
<c:choose>
<c:when test="${user.gender == 1 }">
<option value="1" selected="selected">男</option>
<option value="2">女</option>
</c:when>
<c:otherwise>
<option value="1">男</option>
<option value="2" selected="selected">女</option>
</c:otherwise>
</c:choose>
</select>
</div>
<div>
<label for="birthday">出生日期:</label>
<input type="text" Class="Wdate" id="birthday" name="birthday" value="${user.birthday }"
readonly="readonly" onclick="WdatePicker();">
<font color="red"></font>
</div>
<div>
<label for="phone">使用者電話:</label>
<input type="text" name="phone" id="phone" value="${user.phone }">
<font color="red"></font>
</div>
<div>
<label for="address">使用者位址:</label>
<input type="text" name="address" id="address" value="${user.address }">
</div>
<div>
<label>使用者角色:</label>
<!-- 列出所有的角色分類 -->
<input type="hidden" value="${user.userRole }" id="rid"/>
<select name="userRole" id="userRole"></select>
<font color="red"></font>
</div>
<div class="providerAddBtn">
<input type="button" name="save" id="save" value="儲存"/>
<input type="button" id="back" name="back" value="傳回"/>
</div>
</form>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/usermodify.js"></script>
8,使用者管理子產品—檢視使用者資訊功能
userlist.js
UserServlet
//檢視使用者
private 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);
}
}
UserServiceImpl
//檢視使用者
public User getUserById(String id) {
// TODO Auto-generated method stub
User user = null;
Connection connection = null;
try {
connection = BaseDao.getConnection();
user = userDao.getUserById(connection, id);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
user = null;
} finally {
BaseDao.closeResource(connection, null, null);
}
return user;
}
UserDaoImpl
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 `bookstore order management system_user` u,`bookstore order management system_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.closeResource(null, pstm, rs);
}
System.out.println(user);
return user;
}
測試:
userview.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/common/head.jsp"%>
<style>
.right{
background-color: #08AEEA;
background-image: linear-gradient(0deg, #08AEEA 0%, #2AF598 100%);
}
</style>
<div class="right">
<div class="location">
<strong>你現在所在的位置是:</strong>
<span>使用者管理頁面 >> 使用者資訊檢視頁面</span>
</div>
<div class="providerView">
<p><strong>使用者編号:</strong><span>${user.userCode }</span></p>
<p><strong>使用者名稱:</strong><span>${user.userName }</span></p>
<p><strong>使用者性别:</strong>
<span>
<c:if test="${user.gender == 1 }">男</c:if>
<c:if test="${user.gender == 2 }">女</c:if>
</span>
</p>
<p><strong>出生日期:</strong><span>${user.birthday }</span></p>
<p><strong>使用者電話:</strong><span>${user.phone }</span></p>
<p><strong>使用者位址:</strong><span>${user.address }</span></p>
<p><strong>使用者角色:</strong><span>${user.userRoleName}</span></p>
<div class="providerAddBtn">
<input type="button" id="back" name="back" value="傳回" >
</div>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/userview.js"></script>
9, layui 開源子產品化前端 UI 架構 月曆元件(Calendar)
https://www.layui.com/demo/
【EasyUI篇】Calendar月曆元件:https://blog.csdn.net/ooyhao/article/details/82723999
10,反編譯
八,項目整體架構
九,供應商管理
(1)供應商清單頁面導入-providerlist.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/provider.do">
<input name="method" value="query" type="hidden">
<span>供應商編碼:</span>
<input name="queryProCode" type="text" value="${queryProCode }">
<span>供應商名稱:</span>
<input name="queryProName" type="text" value="${queryProName }">
<input value="查 詢" type="submit" id="searchbutton">
<a href="${pageContext.request.contextPath }/jsp/provideradd.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="provider" items="${providerList }" varStatus="status">
<tr>
<td>
<span>${provider.proCode }</span>
</td>
<td>
<span>${provider.proName }</span>
</td>
<td>
<span>${provider.proContact}</span>
</td>
<td>
<span>${provider.proPhone}</span>
</td>
<td>
<span>${provider.proFax}</span>
</td>
<td>
<span>
<fmt:formatDate value="${provider.creationDate}" pattern="yyyy-MM-dd"/>
</span>
</td>
<td>
<span><a class="viewProvider" href="javascript:;" proid=${provider.id } proname=${provider.proName }><img src="${pageContext.request.contextPath }/images/read.png" alt="檢視" title="檢視"/></a></span>
<span><a class="modifyProvider" href="javascript:;" proid=${provider.id } proname=${provider.proName }><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span>
<span><a class="deleteProvider" href="javascript:;" proid=${provider.id } proname=${provider.proName }><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a></span>
</td>
</tr>
</c:forEach>
</table>
</div>
</section>
<!--點選删除按鈕後彈出的頁面-->
<div class="zhezhao"></div>
<div class="remove" id="removeProv">
<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/providerlist.js"></script>
1,擷取供應商清單
(1)ProviderDao
/**
* 通過供應商名稱、編碼擷取供應商清單-模糊查詢-providerList
*
* @param connection
* @param proName
* @return
* @throws Exception
*/
List<Provider> getProviderList(Connection connection, String proName, String proCode) throws Exception;
(2)ProviderDaoImpl
//通過供應商名稱、編碼擷取供應商清單-模糊查詢-providerList
public List<Provider> getProviderList(Connection connection, String proName, String proCode) throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
ResultSet rs = null;
List<Provider> providerList = new ArrayList<Provider>();
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("select * from `bookstore order management system_provider` where 1=1 ");
List<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(proName)) {
sql.append(" and proName like ?");
list.add("%" + proName + "%");
}
if (!StringUtils.isNullOrEmpty(proCode)) {
sql.append(" and proCode like ?");
list.add("%" + proCode + "%");
}
Object[] params = list.toArray();
System.out.println("sql ----> " + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
while (rs.next()) {
Provider _provider = new Provider();
_provider.setId(rs.getInt("id"));
_provider.setProCode(rs.getString("proCode"));
_provider.setProName(rs.getString("proName"));
_provider.setProDesc(rs.getString("proDesc"));
_provider.setProContact(rs.getString("proContact"));
_provider.setProPhone(rs.getString("proPhone"));
_provider.setProAddress(rs.getString("proAddress"));
_provider.setProFax(rs.getString("proFax"));
_provider.setCreationDate(rs.getTimestamp("creationDate"));
providerList.add(_provider);
}
BaseDao.closeResource(null, pstm, rs);
}
return providerList;
}
(3)ProviderService
/**
* 通過供應商名稱、編碼擷取供應商清單-模糊查詢-providerList
*
* @param proName
* @return
*/
public List<Provider> getProviderList(String proName, String proCode);
(4)ProviderServiceImpl
//通過供應商名稱、編碼擷取供應商清單-模糊查詢-providerList
public List<Provider> getProviderList(String proName, String proCode) {
// TODO Auto-generated method stub
Connection connection = null;
List<Provider> providerList = null;
System.out.println("query proName ---- > " + proName);
System.out.println("query proCode ---- > " + proCode);
try {
connection = BaseDao.getConnection();
providerList = providerDao.getProviderList(connection, proName, proCode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return providerList;
}
2,使用者顯示的Servlet ProviderServlet
1,擷取使用者前端的資料(查詢)
2,判斷請求是否需要執行,看參數的值判斷
3,使用者清單展示
4,傳回前端
//擷取供應商清單
private void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String queryProName = request.getParameter("queryProName");
String queryProCode = request.getParameter("queryProCode");
if (StringUtils.isNullOrEmpty(queryProName)) {
queryProName = "";
}
if (StringUtils.isNullOrEmpty(queryProCode)) {
queryProCode = "";
}
List<Provider> providerList = null;
ProviderService providerService = new ProviderServiceImpl();
providerList = providerService.getProviderList(queryProName, queryProCode);
request.setAttribute("providerList", providerList);
request.setAttribute("queryProName", queryProName);
request.setAttribute("queryProCode", queryProCode);
request.getRequestDispatcher("providerlist.jsp").forward(request, response);
}
注冊Servlet
<servlet>
<servlet-name>ProviderServlet</servlet-name>
<servlet-class>com.wang.servlet.provider.ProviderServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProviderServlet</servlet-name>
<url-pattern>/jsp/provider.do</url-pattern>
</servlet-mapping>
測試:
3,供應商管理子產品—添加供應商功能
providerlist.jsp
provideradd.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/common/head.jsp"%>
<style>
.providerAdd{
background-color: #FFDEE9;
background-image: linear-gradient(0deg, #FFDEE9 0%, #B5FFFC 100%);
}
</style>
<div class="right">
<div class="location">
<strong>你現在所在的位置是:</strong>
<span>供應商管理頁面 >> 供應商添加頁面</span>
</div>
<div class="providerAdd">
<form id="providerForm" name="providerForm" method="post" action="${pageContext.request.contextPath }/jsp/provider.do">
<input type="hidden" name="method" value="add">
<!--div的class 為error是驗證錯誤,ok是驗證成功-->
<div class="">
<label for="proCode">供應商編碼:</label>
<input type="text" name="proCode" id="proCode" value="">
<!-- 放置提示資訊 -->
<font color="red"></font>
</div>
<div>
<label for="proName">供應商名稱:</label>
<input type="text" name="proName" id="proName" value="">
<font color="red"></font>
</div>
<div>
<label for="proContact">聯系人:</label>
<input type="text" name="proContact" id="proContact" value="">
<font color="red"></font>
</div>
<div>
<label for="proPhone">聯系電話:</label>
<input type="text" name="proPhone" id="proPhone" value="">
<font color="red"></font>
</div>
<div>
<label for="proAddress">聯系位址:</label>
<input type="text" name="proAddress" id="proAddress" value="">
</div>
<div>
<label for="proFax">傳真:</label>
<input type="text" name="proFax" id="proFax" value="">
</div>
<div>
<label for="proDesc">描述:</label>
<input type="text" name="proDesc" id="proDesc" value="">
</div>
<div class="providerAddBtn">
<input type="button" name="add" id="add" value="儲存">
<input type="button" id="back" name="back" value="傳回" >
</div>
</form>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/provideradd.js"></script>
ProviderServlet
//添加供應商
private void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String proCode = request.getParameter("proCode");
String proName = request.getParameter("proName");
String proContact = request.getParameter("proContact");
String proPhone = request.getParameter("proPhone");
String proAddress = request.getParameter("proAddress");
String proFax = request.getParameter("proFax");
String proDesc = request.getParameter("proDesc");
Provider provider = new Provider();
provider.setProCode(proCode);
provider.setProName(proName);
provider.setProContact(proContact);
provider.setProPhone(proPhone);
provider.setProFax(proFax);
provider.setProAddress(proAddress);
provider.setProDesc(proDesc);
provider.setCreatedBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
provider.setCreationDate(new Date());
boolean flag = false;
ProviderService providerService = new ProviderServiceImpl();
flag = providerService.add(provider);
if (flag) {
response.sendRedirect(request.getContextPath() + "/jsp/provider.do?method=query");
} else {
request.getRequestDispatcher("provideradd.jsp").forward(request, response);
}
}
ProviderServiceImpl
一切的增删改都需要操作事務
connection.setAutoCommit(false);//開啟JDBC事務管理
如果成功Commit
如果失敗connection.rollback();復原
//添加供應商
public boolean add(Provider provider) {
// TODO Auto-generated method stub
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);//開啟JDBC事務管理
if (providerDao.add(connection, provider) > 0)
flag = true;
connection.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
//在service層進行connection連接配接的關閉
BaseDao.closeResource(connection, null, null);
}
return flag;
}
ProviderDaoImpl
//添加供應商
public int add(Connection connection, Provider provider) throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
String sql = "insert into `bookstore order management system_provider`(proCode,proName,proDesc," +
"proContact,proPhone,proAddress,proFax,createdBy,creationDate) " +
"values(?,?,?,?,?,?,?,?,?)";
Object[] params = {provider.getProCode(), provider.getProName(), provider.getProDesc(),
provider.getProContact(), provider.getProPhone(), provider.getProAddress(),
provider.getProFax(), provider.getCreatedBy(), provider.getCreationDate()};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
測試:
4,供應商管理子產品—删除供應商功能
供應商管理頁面上點選删除按鈕彈出删除框(providerlist.jsp)
providerlist.js
var providerObj;
//供應商管理頁面上點選删除按鈕彈出删除框(providerlist.jsp)
function deleteProvider(obj){
$.ajax({
type:"GET",
url:path+"/jsp/provider.do",
data:{method:"delprovider",proid:obj.attr("proid")},
dataType:"json",
success:function(data){
if(data.delResult == "true"){//删除成功:移除删除行
cancleBtn();
obj.parents("tr").remove();
}else if(data.delResult == "false"){//删除失敗
//alert("對不起,删除供應商【"+obj.attr("proname")+"】失敗");
changeDLGContent("對不起,删除供應商【"+obj.attr("proname")+"】失敗");
}else if(data.delResult == "notexist"){
//alert("對不起,供應商【"+obj.attr("proname")+"】不存在");
changeDLGContent("對不起,供應商【"+obj.attr("proname")+"】不存在");
}else{
//alert("對不起,該供應商【"+obj.attr("proname")+"】下有【"+data.delResult+"】條訂單,不能删除");
changeDLGContent("對不起,該供應商【"+obj.attr("proname")+"】下有【"+data.delResult+"】條訂單,不能删除");
}
},
error:function(data){
//alert("對不起,删除失敗");
changeDLGContent("對不起,删除失敗");
}
});
}
function openYesOrNoDLG(){
$('.zhezhao').css('display', 'block');
$('#removeProv').fadeIn();
}
function cancleBtn(){
$('.zhezhao').css('display', 'none');
$('#removeProv').fadeOut();
}
function changeDLGContent(contentStr){
var p = $(".removeMain").find("p");
p.html(contentStr);
}
$(function(){
$(".viewProvider").on("click",function(){
//将被綁定的元素(a)轉換成jquery對象,可以使用jquery方法
var obj = $(this);
window.location.href=path+"/jsp/provider.do?method=view&proid="+ obj.attr("proid");
});
$(".modifyProvider").on("click",function(){
var obj = $(this);
window.location.href=path+"/jsp/provider.do?method=modify&proid="+ obj.attr("proid");
});
$('#no').click(function () {
cancleBtn();
});
$('#yes').click(function () {
deleteProvider(providerObj);
});
$(".deleteProvider").on("click",function(){
providerObj = $(this);
changeDLGContent("你确定要删除供應商【"+providerObj.attr("proname")+"】嗎?");
openYesOrNoDLG();
});
/* $(".deleteProvider").on("click",function(){
var obj = $(this);
if(confirm("你确定要删除供應商【"+obj.attr("proname")+"】嗎?")){
$.ajax({
type:"GET",
url:path+"/jsp/provider.do",
data:{method:"delprovider",proid:obj.attr("proid")},
dataType:"json",
success:function(data){
if(data.delResult == "true"){//删除成功:移除删除行
alert("删除成功");
obj.parents("tr").remove();
}else if(data.delResult == "false"){//删除失敗
alert("對不起,删除供應商【"+obj.attr("proname")+"】失敗");
}else if(data.delResult == "notexist"){
alert("對不起,供應商【"+obj.attr("proname")+"】不存在");
}else{
alert("對不起,該供應商【"+obj.attr("proname")+"】下有【"+data.delResult+"】條訂單,不能删除");
}
},
error:function(data){
alert("對不起,删除失敗");
}
});
}
});*/
});
ProviderServlet
//删除管理者
private void delProvider(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("proid");
HashMap<String, String> resultMap = new HashMap<String, String>();
if (!StringUtils.isNullOrEmpty(id)) {
ProviderService providerService = new ProviderServiceImpl();
int flag = providerService.deleteProviderById(id);
if (flag == 0) {//删除成功
resultMap.put("delResult", "true");
} else if (flag == -1) {//删除失敗
resultMap.put("delResult", "false");
} else if (flag > 0) {//該供應商下有訂單,不能删除,傳回訂單數
resultMap.put("delResult", String.valueOf(flag));
}
} else {
resultMap.put("delResult", "notexit");
}
//把resultMap轉換成json對象輸出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
ProviderServiceImpl
/**
* 業務:根據ID删除供應商表的資料之前,需要先去訂單表裡進行查詢操作
* 若訂單表中無該供應商的訂單資料,則可以删除
* 若有該供應商的訂單資料,則不可以删除
* 傳回值billCount
* 1> billCount == 0 删除--- 1 成功 (0) 2 不成功 (-1)
* 2> billCount > 0 不能删除-- 查詢成功(0) 查詢不成功(-1)
* <p>
* ---判斷
* 如果billCount = -1 失敗
* 若billCount >= 0 成功
*/
public int deleteProviderById(String delId) {
Connection connection = null;
int billCount = -1;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);
billCount = billDao.getBillCountByProviderId(connection, delId);
if (billCount == 0) {
providerDao.deleteProviderById(connection, delId);
}
connection.commit();
} catch (Exception e) {
e.printStackTrace();
billCount = -1;
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
BaseDao.closeResource(connection, null, null);
}
return billCount;
}
ProviderDaoImpl
//删除供應商
public int deleteProviderById(Connection connection, String delId) throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
String sql = "delete from `bookstore order management system_provider` where id=?";
Object[] params = {delId};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
測試:
providerlist.jsp
<!--點選删除按鈕後彈出的頁面-->
<div class="zhezhao"></div>
<div class="remove" id="removeProv">
<div class="removerChid">
<h2>提示</h2>
<div class="removeMain" >
<p>你确定要删除該供應商嗎?</p>
<a href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" id="yes">确定</a>
<a href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" id="no">取消</a>
</div>
</div>
</div>
5,供應商管理子產品—修改供應商功能
providerlist.js
ProviderServlet
//修改供應商
private void getProviderById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("proid");
if (!StringUtils.isNullOrEmpty(id)) {
ProviderService providerService = new ProviderServiceImpl();
Provider provider = null;
provider = providerService.getProviderById(id);
request.setAttribute("provider", provider);
request.getRequestDispatcher(url).forward(request, response);
}
}
ProviderServiceImpl
//修改使用者
public Provider getProviderById(String id) {
Provider provider = null;
Connection connection = null;
try {
connection = BaseDao.getConnection();
provider = providerDao.getProviderById(connection, id);
} catch (Exception e) {
e.printStackTrace();
provider = null;
} finally {
BaseDao.closeResource(connection, null, null);
}
return provider;
}
ProviderDaoImpl
//修改供應商
public Provider getProviderById(Connection connection, String id) throws Exception {
// TODO Auto-generated method stub
Provider provider = null;
PreparedStatement pstm = null;
ResultSet rs = null;
if (null != connection) {
String sql = "select * from `bookstore order management system_provider` where id=?";
Object[] params = {id};
rs = BaseDao.execute(connection, pstm, rs, sql, params);
if (rs.next()) {
provider = new Provider();
provider.setId(rs.getInt("id"));
provider.setProCode(rs.getString("proCode"));
provider.setProName(rs.getString("proName"));
provider.setProDesc(rs.getString("proDesc"));
provider.setProContact(rs.getString("proContact"));
provider.setProPhone(rs.getString("proPhone"));
provider.setProAddress(rs.getString("proAddress"));
provider.setProFax(rs.getString("proFax"));
provider.setCreatedBy(rs.getInt("createdBy"));
provider.setCreationDate(rs.getTimestamp("creationDate"));
provider.setModifyBy(rs.getInt("modifyBy"));
provider.setModifyDate(rs.getTimestamp("modifyDate"));
}
BaseDao.closeResource(null, pstm, rs);
}
return provider;
}
測試:
providermodify.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@include file="/jsp/common/head.jsp" %>
<style>
.right{
background-color: #FEE140;
background-image: linear-gradient(90deg, #FEE140 0%, #FA709A 100%);
}
</style>
<div class="right">
<div class="location">
<strong>你現在所在的位置是:</strong>
<span>供應商管理頁面 >> 供應商修改頁</span>
</div>
<div class="providerAdd">
<form id="providerForm" name="providerForm" method="post"
action="${pageContext.request.contextPath }/jsp/provider.do">
<input type="hidden" name="method" value="modifysave">
<input type="hidden" name="id" value="${provider.id}">
<!--div的class 為error是驗證錯誤,ok是驗證成功-->
<div class="">
<label for="proCode">供應商編碼:</label>
<input type="text" name="proCode" id="proCode" value="${provider.proCode }" readonly="readonly">
</div>
<div>
<label for="proName">供應商名稱:</label>
<input type="text" name="proName" id="proName" value="${provider.proName }">
<font color="red"></font>
</div>
<div>
<label for="proContact">聯系人:</label>
<input type="text" name="proContact" id="proContact" value="${provider.proContact }">
<font color="red"></font>
</div>
<div>
<label for="proPhone">聯系電話:</label>
<input type="text" name="proPhone" id="proPhone" value="${provider.proPhone }">
<font color="red"></font>
</div>
<div>
<label for="proAddress">聯系位址:</label>
<input type="text" name="proAddress" id="proAddress" value="${provider.proAddress }">
</div>
<div>
<label for="proFax">傳真:</label>
<input type="text" name="proFax" id="proFax" value="${provider.proFax }">
</div>
<div>
<label for="proDesc">描述:</label>
<input type="text" name="proDesc" id="proDesc" value="${provider.proDesc }">
</div>
<div class="providerAddBtn">
<input type="button" name="save" id="save" value="儲存">
<input type="button" id="back" name="back" value="傳回">
</div>
</form>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/providermodify.js"></script>
6,供應商管理子產品—檢視供應商資訊功能
providerlist.js
ProviderServlet
//修改供應商,檢視供應商
private void getProviderById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("proid");
if (!StringUtils.isNullOrEmpty(id)) {
//調用背景方法得到provider對象
ProviderService providerService = new ProviderServiceImpl();
Provider provider = null;
provider = providerService.getProviderById(id);
request.setAttribute("provider", provider);
request.getRequestDispatcher(url).forward(request, response);
}
}
ProviderServiceImpl
//修改使用者,檢視使用者
public Provider getProviderById(String id) {
Provider provider = null;
Connection connection = null;
try {
connection = BaseDao.getConnection();
provider = providerDao.getProviderById(connection, id);
} catch (Exception e) {
e.printStackTrace();
provider = null;
} finally {
BaseDao.closeResource(connection, null, null);
}
return provider;
}
ProviderDaoImpl
//修改供應商,檢視供應商
public Provider getProviderById(Connection connection, String id) throws Exception {
// TODO Auto-generated method stub
Provider provider = null;
PreparedStatement pstm = null;
ResultSet rs = null;
if (null != connection) {
String sql = "select * from `bookstore order management system_provider` where id=?";
Object[] params = {id};
rs = BaseDao.execute(connection, pstm, rs, sql, params);
if (rs.next()) {
provider = new Provider();
provider.setId(rs.getInt("id"));
provider.setProCode(rs.getString("proCode"));
provider.setProName(rs.getString("proName"));
provider.setProDesc(rs.getString("proDesc"));
provider.setProContact(rs.getString("proContact"));
provider.setProPhone(rs.getString("proPhone"));
provider.setProAddress(rs.getString("proAddress"));
provider.setProFax(rs.getString("proFax"));
provider.setCreatedBy(rs.getInt("createdBy"));
provider.setCreationDate(rs.getTimestamp("creationDate"));
provider.setModifyBy(rs.getInt("modifyBy"));
provider.setModifyDate(rs.getTimestamp("modifyDate"));
}
BaseDao.closeResource(null, pstm, rs);
}
return provider;
}
測試:
providerview.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/common/head.jsp"%>
<style>
.right{
background-color: #08AEEA;
background-image: linear-gradient(0deg, #08AEEA 0%, #2AF598 100%);
}
</style>
<div class="right">
<div class="location">
<strong>你現在所在的位置是:</strong>
<span>供應商管理頁面 >> 資訊檢視</span>
</div>
<div class="providerView">
<p><strong>供應商編碼:</strong><span>${provider.proCode }</span></p>
<p><strong>供應商名稱:</strong><span>${provider.proName }</span></p>
<p><strong>聯系人:</strong><span>${provider.proContact }</span></p>
<p><strong>聯系電話:</strong><span>${provider.proPhone }</span></p>
<p><strong>傳真:</strong><span>${provider.proFax }</span></p>
<p><strong>描述:</strong><span>${provider.proDesc}</span></p>
<div class="providerAddBtn">
<input type="button" id="back" name="back" value="傳回" >
</div>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/providerview.js"></script>
十,訂單管理
(1)訂單管理清單頁面導入-billlist.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/bill.do">
<input name="method" value="query" class="input-text" type="hidden">
<span>商品名稱:</span>
<input name="queryProductName" type="text" value="${queryProductName }">
<span>供應商:</span>
<select name="queryProviderId">
<c:if test="${providerList != null }">
<option value="0">--請選擇--</option>
<c:forEach var="provider" items="${providerList}">
<option
<c:if test="${provider.id == queryProviderId }">selected="selected"</c:if>
value="${provider.id}">${provider.proName}</option>
</c:forEach>
</c:if>
</select>
<span>是否付款:</span>
<select name="queryIsPayment">
<option value="0">--請選擇--</option>
<option value="1" ${queryIsPayment == 1 ? "selected=\"selected\"":"" }>未付款</option>
<option value="2" ${queryIsPayment == 2 ? "selected=\"selected\"":"" }>已付款</option>
</select>
<input value="查 詢" type="submit" id="searchbutton">
<a href="${pageContext.request.contextPath }/jsp/billadd.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="bill" items="${billList }" varStatus="status">
<tr>
<td>
<span>${bill.billCode }</span>
</td>
<td>
<span>${bill.productName }</span>
</td>
<td>
<span>${bill.providerName}</span>
</td>
<td>
<span>${bill.totalPrice}</span>
</td>
<td>
<span>
<c:if test="${bill.isPayment == 1}">未付款</c:if>
<c:if test="${bill.isPayment == 2}">已付款</c:if>
</span>
</td>
<td>
<span>
<fmt:formatDate value="${bill.creationDate}" pattern="yyyy-MM-dd"/>
</span>
</td>
<td>
<span><a class="viewBill" href="javascript:;" billid=${bill.id } billcc=${bill.billCode }><img
src="${pageContext.request.contextPath }/images/read.png" alt="檢視" title="檢視"/></a></span>
<span><a class="modifyBill" href="javascript:;" billid=${bill.id } billcc=${bill.billCode }><img
src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span>
<span><a class="deleteBill" href="javascript:;" billid=${bill.id } billcc=${bill.billCode }><img
src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a></span>
</td>
</tr>
</c:forEach>
</table>
</div>
</section>
<!--點選删除按鈕後彈出的頁面-->
<div class="zhezhao"></div>
<div class="remove" id="removeBi">
<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/billlist.js"></script>
1,擷取訂單清單
(1)BillDao
/**
* 通過查詢條件擷取供應商清單-模糊查詢-getBillList
*
* @param connection
* @param bill
* @return
* @throws Exception
*/
List<Bill> getBillList(Connection connection, Bill bill) throws Exception;
(2)BillDaoImpl
//通過查詢條件擷取供應商清單-模糊查詢-getBillList
public List<Bill> getBillList(Connection connection, Bill bill) throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
List<Bill> billList = new ArrayList<Bill>();
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("select b.*,p.proName as providerName from `bookstore order management system_bill` b, `bookstore order management system_provider` p where b.providerId = p.id");
List<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(bill.getProductName())) {
sql.append(" and productName like ?");
list.add("%" + bill.getProductName() + "%");
}
if (bill.getProviderId() > 0) {
sql.append(" and providerId = ?");
list.add(bill.getProviderId());
}
if (bill.getIsPayment() > 0) {
sql.append(" and isPayment = ?");
list.add(bill.getIsPayment());
}
Object[] params = list.toArray();
System.out.println("sql --------- > " + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
while (rs.next()) {
Bill _bill = new Bill();
_bill.setId(rs.getInt("id"));
_bill.setBillCode(rs.getString("billCode"));
_bill.setProductName(rs.getString("productName"));
_bill.setProductDesc(rs.getString("productDesc"));
_bill.setProductUnit(rs.getString("productUnit"));
_bill.setProductCount(rs.getBigDecimal("productCount"));
_bill.setTotalPrice(rs.getBigDecimal("totalPrice"));
_bill.setIsPayment(rs.getInt("isPayment"));
_bill.setProviderId(rs.getInt("providerId"));
_bill.setProviderName(rs.getString("providerName"));
_bill.setCreationDate(rs.getTimestamp("creationDate"));
_bill.setCreatedBy(rs.getInt("createdBy"));
billList.add(_bill);
}
BaseDao.closeResource(null, pstm, rs);
}
return billList;
}
(3)BillService
/**
* 通過條件擷取訂單清單-模糊查詢-billList
*
* @param bill
* @return
*/
public List<Bill> getBillList(Bill bill);
(4)BillServiceImpl
//通過條件擷取訂單清單-模糊查詢-billList
public List<Bill> getBillList(Bill bill) {
// TODO Auto-generated method stub
Connection connection = null;
List<Bill> billList = null;
System.out.println("query productName ---- > " + bill.getProductName());
System.out.println("query providerId ---- > " + bill.getProviderId());
System.out.println("query isPayment ---- > " + bill.getIsPayment());
try {
connection = BaseDao.getConnection();
billList = billDao.getBillList(connection, bill);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return billList;
}
2,使用者顯示的Servlet BillServlet
1,擷取使用者前端的資料(查詢)
2,判斷請求是否需要執行,看參數的值判斷
3,使用者清單展示
4,傳回前端
//通過條件擷取訂單清單-模糊查詢-billList
private void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Provider> providerList;
ProviderService providerService = new ProviderServiceImpl();
providerList = providerService.getProviderList("", "");
request.setAttribute("providerList", providerList);
String queryProductName = request.getParameter("queryProductName");
String queryProviderId = request.getParameter("queryProviderId");
String queryIsPayment = request.getParameter("queryIsPayment");
if (StringUtils.isNullOrEmpty(queryProductName)) {
queryProductName = "";
}
List<Bill> billList = new ArrayList<Bill>();
BillService billService = new BillServiceImpl();
Bill bill = new Bill();
if (StringUtils.isNullOrEmpty(queryIsPayment)) {
bill.setIsPayment(0);
} else {
bill.setIsPayment(Integer.parseInt(queryIsPayment));
}
if (StringUtils.isNullOrEmpty(queryProviderId)) {
bill.setProviderId(0);
} else {
bill.setProviderId(Integer.parseInt(queryProviderId));
}
bill.setProductName(queryProductName);
billList = billService.getBillList(bill);
request.setAttribute("billList", billList);
request.setAttribute("queryProductName", queryProductName);
request.setAttribute("queryProviderId", queryProviderId);
request.setAttribute("queryIsPayment", queryIsPayment);
request.getRequestDispatcher("billlist.jsp").forward(request, response);
}
注冊Servlet
<!--訂單管理-->
<servlet>
<servlet-name>BillServlet</servlet-name>
<servlet-class>com.wang.servlet.bill.BillServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BillServlet</servlet-name>
<url-pattern>/jsp/bill.do</url-pattern>
</servlet-mapping>
測試:
3,擷取訂單供應商清單
4,訂單管理子產品—添加訂單功能
billlist.jsp
billadd.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/common/head.jsp"%>
<style>
.providerAdd{
background-color: #FFDEE9;
background-image: linear-gradient(0deg, #FFDEE9 0%, #B5FFFC 100%);
}
</style>
<div class="right">
<div class="location">
<strong>你現在所在的位置是:</strong>
<span>訂單管理頁面 >> 訂單添加頁面</span>
</div>
<div class="providerAdd">
<form id="billForm" name="billForm" method="post" action="${pageContext.request.contextPath }/jsp/bill.do">
<!--div的class 為error是驗證錯誤,ok是驗證成功-->
<input type="hidden" name="method" value="add">
<div class="">
<label for="billCode">訂單編碼:</label>
<input type="text" name="billCode" class="text" id="billCode" value="">
<!-- 放置提示資訊 -->
<font color="red"></font>
</div>
<div>
<label for="productName">商品名稱:</label>
<input type="text" name="productName" id="productName" value="">
<font color="red"></font>
</div>
<div>
<label for="productUnit">商品機關:</label>
<input type="text" name="productUnit" id="productUnit" value="">
<font color="red"></font>
</div>
<div>
<label for="productCount">商品數量:</label>
<input type="text" name="productCount" id="productCount" value="">
<font color="red"></font>
</div>
<div>
<label for="totalPrice">總金額:</label>
<input type="text" name="totalPrice" id="totalPrice" value="">
<font color="red"></font>
</div>
<div>
<label >供應商:</label>
<select name="providerId" id="providerId">
</select>
<font color="red"></font>
</div>
<div>
<label >是否付款:</label>
<input type="radio" name="isPayment" value="1" checked="checked">未付款
<input type="radio" name="isPayment" value="2" >已付款
</div>
<div class="providerAddBtn">
<input type="button" name="add" id="add" value="儲存">
<input type="button" id="back" name="back" value="傳回" >
</div>
</form>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/billadd.js"></script>
BillServlet
//添加訂單
private void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String billCode = request.getParameter("billCode");
String productName = request.getParameter("productName");
String productDesc = request.getParameter("productDesc");
String productUnit = request.getParameter("productUnit");
String productCount = request.getParameter("productCount");
String totalPrice = request.getParameter("totalPrice");
String providerId = request.getParameter("providerId");
String isPayment = request.getParameter("isPayment");
Bill bill = new Bill();
bill.setBillCode(billCode);
bill.setProductName(productName);
bill.setProductDesc(productDesc);
bill.setProductUnit(productUnit);
bill.setProductCount(new BigDecimal(productCount).setScale(2, BigDecimal.ROUND_DOWN));
bill.setIsPayment(Integer.parseInt(isPayment));
bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN));
bill.setProviderId(Integer.parseInt(providerId));
bill.setCreatedBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
bill.setCreationDate(new Date());
boolean flag = false;
BillService billService = new BillServiceImpl();
flag = billService.add(bill);
System.out.println("add flag -- > " + flag);
if (flag) {
response.sendRedirect(request.getContextPath() + "/jsp/bill.do?method=query");
} else {
request.getRequestDispatcher("billadd.jsp").forward(request, response);
}
}
BillServiceImpl
一切的增删改都需要操作事務
connection.setAutoCommit(false);//開啟JDBC事務管理
如果成功Commit
如果失敗connection.rollback();復原
//添加訂單
public boolean add(Bill bill) {
// TODO Auto-generated method stub
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);//開啟JDBC事務管理
if (billDao.add(connection, bill) > 0)
flag = true;
connection.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
//在service層進行connection連接配接的關閉
BaseDao.closeResource(connection, null, null);
}
return flag;
}
BillDaoImpl
//添加訂單
public int add(Connection connection, Bill bill) throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
String sql = "insert into `bookstore order management system_bill`(billCode,productName,productDesc," +
"productUnit,productCount,totalPrice,isPayment,providerId,createdBy,creationDate) " +
"values(?,?,?,?,?,?,?,?,?,?)";
Object[] params = {bill.getBillCode(), bill.getProductName(), bill.getProductDesc(),
bill.getProductUnit(), bill.getProductCount(), bill.getTotalPrice(), bill.getIsPayment(),
bill.getProviderId(), bill.getCreatedBy(), bill.getCreationDate()};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
System.out.println("dao--------flag " + flag);
}
return flag;
}
測試:
5,訂單管理子產品—删除訂單功能
訂單管理頁面上點選删除按鈕彈出删除框(billlist.jsp)
billlist.js
var billObj;
//訂單管理頁面上點選删除按鈕彈出删除框(billlist.jsp)
function deleteBill(obj) {
$.ajax({
type: "GET",
url: path + "/jsp/bill.do",
data: {method: "delbill", billid: obj.attr("billid")},
dataType: "json",
success: function (data) {
if (data.delResult == "true") {//删除成功:移除删除行
cancleBtn();
obj.parents("tr").remove();
} else if (data.delResult == "false") {//删除失敗
//alert("對不起,删除訂單【"+obj.attr("billcc")+"】失敗");
changeDLGContent("對不起,删除訂單【" + obj.attr("billcc") + "】失敗");
} else if (data.delResult == "notexist") {
//alert("對不起,訂單【"+obj.attr("billcc")+"】不存在");
changeDLGContent("對不起,訂單【" + obj.attr("billcc") + "】不存在");
}
},
error: function (data) {
alert("對不起,删除失敗");
}
});
}
function openYesOrNoDLG() {
$('.zhezhao').css('display', 'block');
$('#removeBi').fadeIn();
}
function cancleBtn() {
$('.zhezhao').css('display', 'none');
$('#removeBi').fadeOut();
}
function changeDLGContent(contentStr) {
var p = $(".removeMain").find("p");
p.html(contentStr);
}
$(function () {
$(".viewBill").on("click", function () {
//将被綁定的元素(a)轉換成jquery對象,可以使用jquery方法
var obj = $(this);
window.location.href = path + "/jsp/bill.do?method=view&billid=" + obj.attr("billid");
});
$(".modifyBill").on("click", function () {
var obj = $(this);
window.location.href = path + "/jsp/bill.do?method=modify&billid=" + obj.attr("billid");
});
$('#no').click(function () {
cancleBtn();
});
$('#yes').click(function () {
deleteBill(billObj);
});
$(".deleteBill").on("click", function () {
billObj = $(this);
changeDLGContent("你确定要删除訂單【" + billObj.attr("billcc") + "】嗎?");
openYesOrNoDLG();
});
});
BillServlet
//删除訂單
private void delBill(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("billid");
HashMap<String, String> resultMap = new HashMap<String, String>();
if (!StringUtils.isNullOrEmpty(id)) {
BillService billService = new BillServiceImpl();
boolean flag = billService.deleteBillById(id);
if (flag) {//删除成功
resultMap.put("delResult", "true");
} else {//删除失敗
resultMap.put("delResult", "false");
}
} else {
resultMap.put("delResult", "notexit");
}
//把resultMap轉換成json對象輸出
response.setContentType("application/json");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();
}
BillServiceImpl
//删除訂單
public boolean deleteBillById(String delId) {
// TODO Auto-generated method stub
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if (billDao.deleteBillById(connection, delId) > 0)
flag = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeResource(connection, null, null);
}
return flag;
}
BillDaoImpl
//删除訂單
public int deleteBillById(Connection connection, String delId) throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
int flag = 0;
if (null != connection) {
String sql = "delete from `bookstore order management system_bill` where id=?";
Object[] params = {delId};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
測試:
billlist.jsp
<div class="zhezhao"></div>
<div class="remove" id="removeBi">
<div class="removerChid">
<h2>提示</h2>
<div class="removeMain">
<p>你确定要删除該訂單嗎?</p>
<a href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" id="yes">确定</a>
<a href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" id="no">取消</a>
</div>
</div>
</div>
6,訂單管理子產品—修改訂單功能
billlist.js
BillServlet
//修改訂單
private void getBillById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("billid");
if (!StringUtils.isNullOrEmpty(id)) {
BillService billService = new BillServiceImpl();
Bill bill = null;
bill = billService.getBillById(id);
request.setAttribute("bill", bill);
request.getRequestDispatcher(url).forward(request, response);
}
}
BillServiceImpl
//修改訂單
public Bill getBillById(String id) {
// TODO Auto-generated method stub
Bill bill = null;
Connection connection = null;
try {
connection = BaseDao.getConnection();
bill = billDao.getBillById(connection, id);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
bill = null;
} finally {
BaseDao.closeResource(connection, null, null);
}
return bill;
}
BillDaoImpl
//修改訂單
public Bill getBillById(Connection connection, String id) throws Exception {
Bill bill = null;
PreparedStatement pstm = null;
ResultSet rs = null;
if (null != connection) {
String sql = "select b.*,p.proName as providerName from `bookstore order management system_bill` b, `bookstore order management system_provider` p " +
"where b.providerId = p.id and b.id=?";
Object[] params = {id};
rs = BaseDao.execute(connection, pstm, rs, sql, params);
if (rs.next()) {
bill = new Bill();
bill.setId(rs.getInt("id"));
bill.setBillCode(rs.getString("billCode"));
bill.setProductName(rs.getString("productName"));
bill.setProductDesc(rs.getString("productDesc"));
bill.setProductUnit(rs.getString("productUnit"));
bill.setProductCount(rs.getBigDecimal("productCount"));
bill.setTotalPrice(rs.getBigDecimal("totalPrice"));
bill.setIsPayment(rs.getInt("isPayment"));
bill.setProviderId(rs.getInt("providerId"));
bill.setProviderName(rs.getString("providerName"));
bill.setModifyBy(rs.getInt("modifyBy"));
bill.setModifyDate(rs.getTimestamp("modifyDate"));
}
BaseDao.closeResource(null, pstm, rs);
}
return bill;
}
測試:
billmodify.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/common/head.jsp"%>
<style>
.right{
background-color: #FEE140;
background-image: linear-gradient(90deg, #FEE140 0%, #FA709A 100%);
}
</style>
<div class="right">
<div class="location">
<strong>你現在所在的位置是:</strong>
<span>訂單管理頁面 >> 訂單添加頁面</span>
</div>
<div class="providerAdd">
<form id="billForm" name="billForm" method="post" action="${pageContext.request.contextPath }/jsp/bill.do">
<input type="hidden" name="method" value="modifysave">
<input type="hidden" name="id" value="${bill.id }">
<!--div的class 為error是驗證錯誤,ok是驗證成功-->
<div class="">
<label for="billCode">訂單編碼:</label>
<input type="text" name="billCode" id="billCode" value="${bill.billCode }" readonly="readonly">
</div>
<div>
<label for="productName">商品名稱:</label>
<input type="text" name="productName" id="productName" value="${bill.productName }">
<font color="red"></font>
</div>
<div>
<label for="productUnit">商品機關:</label>
<input type="text" name="productUnit" id="productUnit" value="${bill.productUnit }">
<font color="red"></font>
</div>
<div>
<label for="productCount">商品數量:</label>
<input type="text" name="productCount" id="productCount" value="${bill.productCount }">
<font color="red"></font>
</div>
<div>
<label for="totalPrice">總金額:</label>
<input type="text" name="totalPrice" id="totalPrice" value="${bill.totalPrice }">
<font color="red"></font>
</div>
<div>
<label for="providerId">供應商:</label>
<input type="hidden" value="${bill.providerId }" id="pid" />
<select name="providerId" id="providerId">
</select>
<font color="red"></font>
</div>
<div>
<label >是否付款:</label>
<c:if test="${bill.isPayment == 1 }">
<input type="radio" name="isPayment" value="1" checked="checked">未付款
<input type="radio" name="isPayment" value="2" >已付款
</c:if>
<c:if test="${bill.isPayment == 2 }">
<input type="radio" name="isPayment" value="1">未付款
<input type="radio" name="isPayment" value="2" checked="checked">已付款
</c:if>
</div>
<div class="providerAddBtn">
<input type="button" name="save" id="save" value="儲存">
<input type="button" id="back" name="back" value="傳回" >
</div>
</form>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/billmodify.js"></script>
7,訂單管理子產品—檢視訂單資訊功能
billlist.js
BillServlet
//修改訂單,檢視訂單資訊
private void getBillById(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
String id = request.getParameter("billid");
if (!StringUtils.isNullOrEmpty(id)) {
BillService billService = new BillServiceImpl();
Bill bill = null;
bill = billService.getBillById(id);
request.setAttribute("bill", bill);
request.getRequestDispatcher(url).forward(request, response);
}
}
BillServiceImpl
//修改訂單 ,檢視訂單資訊
public Bill getBillById(String id) {
// TODO Auto-generated method stub
Bill bill = null;
Connection connection = null;
try {
connection = BaseDao.getConnection();
bill = billDao.getBillById(connection, id);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
bill = null;
} finally {
BaseDao.closeResource(connection, null, null);
}
return bill;
}
BillDaoImpl
//修改訂單,檢視訂單資訊
public Bill getBillById(Connection connection, String id) throws Exception {
Bill bill = null;
PreparedStatement pstm = null;
ResultSet rs = null;
if (null != connection) {
String sql = "select b.*,p.proName as providerName from `bookstore order management system_bill` b, `bookstore order management system_provider` p " +
"where b.providerId = p.id and b.id=?";
Object[] params = {id};
rs = BaseDao.execute(connection, pstm, rs, sql, params);
if (rs.next()) {
bill = new Bill();
bill.setId(rs.getInt("id"));
bill.setBillCode(rs.getString("billCode"));
bill.setProductName(rs.getString("productName"));
bill.setProductDesc(rs.getString("productDesc"));
bill.setProductUnit(rs.getString("productUnit"));
bill.setProductCount(rs.getBigDecimal("productCount"));
bill.setTotalPrice(rs.getBigDecimal("totalPrice"));
bill.setIsPayment(rs.getInt("isPayment"));
bill.setProviderId(rs.getInt("providerId"));
bill.setProviderName(rs.getString("providerName"));
bill.setModifyBy(rs.getInt("modifyBy"));
bill.setModifyDate(rs.getTimestamp("modifyDate"));
}
BaseDao.closeResource(null, pstm, rs);
}
return bill;
}
測試:
billview.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/common/head.jsp"%>
<style>
.right{
background-color: #08AEEA;
background-image: linear-gradient(0deg, #08AEEA 0%, #2AF598 100%);
}
</style>
<div class="right">
<div class="location">
<strong>你現在所在的位置是:</strong>
<span>訂單管理頁面 >> 資訊檢視</span>
</div>
<div class="providerView">
<p><strong>訂單編号:</strong><span>${bill.billCode }</span></p>
<p><strong>商品名稱:</strong><span>${bill.productName }</span></p>
<p><strong>商品機關:</strong><span>${bill.productUnit }</span></p>
<p><strong>商品數量:</strong><span>${bill.productCount }</span></p>
<p><strong>總金額:</strong><span>${bill.totalPrice }</span></p>
<p><strong>供應商:</strong><span>${bill.providerName }</span></p>
<p><strong>是否付款:</strong>
<span>
<c:if test="${bill.isPayment == 1}">未付款</c:if>
<c:if test="${bill.isPayment == 2}">已付款</c:if>
</span>
</p>
<div class="providerAddBtn">
<input type="button" id="back" name="back" value="傳回" >
</div>
</div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/billview.js"></script>