文章目錄
- 一.功能需求
- 二.設計思路
- 三.實現步驟
- (一)創建數據表
- (二)創建Web項目
- (三)創建實體類
- (四)創建數據工具類ConnectionManager
- 1.在web\WEB-INF目錄下創建lib子目錄,添加MySQL驅動程序jar包
- 2.在src下創建net.ysy.shop.dbutil包,在裏面加ConnectionManager類
- 3.運行程序,查看結果
- 建議採用數據庫連接池,效率更高,建議使用數據源方式獲取數據連接.
- (五)數據訪問接口(XXXDao)
- (六)數據訪問接口實現類(XXXDaoImpl)
- 1.用戶數據訪問接口實現類UserDaoImpl
- 2.類別數據訪問接口實現類CategoryDaoImpl
- 3.商品數據訪問接口實現類ProductDaoImpl
- 4.訂單數據訪問接口實現類OrderDaoImpl
- (七)數據訪問接口實現類(XXXService)
本項目採用MVC模式進行開發,整合JSP+Servlet+DB(DAO).
一.功能需求
1.普通用戶
只有註冊用戶登錄成功之後纔可查看商品類別,查看商品,選購商品、生成訂單、查看訂單.
2.管理員用戶
只有管理員纔有權限進入購物網後臺管理,進行用戶管理
二.設計思路
(一)採用MVC設計模式
分層架構:展現層(JSP)<——>控制層(Servlet)<——>業務層(Service)<——>模型層(Dao)<——>數據庫(DB)
(二)前臺購物
1.購物流程
登錄-------顯示商品類別------顯示某類商品信息------查看購物車------生成訂單------支付
2.用戶註冊
系統只有一個管理員,在註冊頁面註冊的都是普通用戶.
(三)後臺管理
1.用戶管理
用戶的增刪改查
2.類別管理
商品類別的增刪改查
3.商品管理
商品的增刪改查
4.訂單管理
訂單的查看與刪除
三.實現步驟
(一)創建數據表
創建MySQL數據庫shop,包含四張表:用戶表(t_user)、類別表(t_category)、商品表(t_product)和訂單表(t_order).
(二)創建Web項目
1.創建Web項目shop
2.在項目結構窗口設置Artifacts名詞:shop
3.配置服務器(Server)
4.設置部署(Deployment)
(三)創建實體類
1.用戶實體類User
package net.ysy.shop.bean;
import java.util.Date;
public class User {
/**
* 用戶表示符
*/
private int id;
/**
*用戶名
*/
private String username;
/**
* 密碼
*/
private String password;
/**
* 電話號碼
*/
private String telephone;
/**
* 註冊時間
*/
private Date registerTime;
/**
* 權限(0:管理員;1:普通用戶)
*/
private int popedom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
public int getPopedom() {
return popedom;
}
public void setPopedom(int popedom) {
this.popedom = popedom;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
", popedom=" + popedom +
'}';
}
}
2.類別實體類Category
package net.ysy.shop.bean;
public class Category {
/**
* 類別標識符
*/
private int id;
/**
* 類別名稱
*/
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
3.商品實體類Product
package net.ysy.shop.bean;
import java.util.Date;
public class Product {
/**
* 商品標識符
*/
private int id;
/**
* 商品名稱
*/
private String name;
/**
* 商品上架時間
*/
private Date addTime;
/**
* 商品所屬類別標識符
*/
private int categoryId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", addTime=" + addTime +
", categoryId=" + categoryId +
'}';
}
}
4.訂單實體類Order
package net.ysy.shop.bean;
import javafx.scene.chart.PieChart;
import javax.xml.crypto.Data;
public class Order {
/**
* 訂單標識符
*/
private int id;
/**
* 用戶名
*/
private String username;
/**
* 聯繫電話
*/
private String telephone;
/**
* 訂單總金額
*/
private String totalPric;
/**
* 送貨地址
*/
private String deliveryAddrrss;
/**
* 下單時間
*/
private Data orderTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getTotalPric() {
return totalPric;
}
public void setTotalPric(String totalPric) {
this.totalPric = totalPric;
}
public String getDeliveryAddrrss() {
return deliveryAddrrss;
}
public void setDeliveryAddrrss(String deliveryAddrrss) {
this.deliveryAddrrss = deliveryAddrrss;
}
public Data getOrderTime() {
return orderTime;
}
public void setOrderTime(Data orderTime) {
this.orderTime = orderTime;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", username='" + username + '\'' +
", telephone='" + telephone + '\'' +
", totalPric='" + totalPric + '\'' +
", deliveryAddrrss='" + deliveryAddrrss + '\'' +
", orderTime=" + orderTime +
'}';
}
}
(四)創建數據工具類ConnectionManager
1.在web\WEB-INF目錄下創建lib子目錄,添加MySQL驅動程序jar包
2.在src下創建net.ysy.shop.dbutil包,在裏面加ConnectionManager類
package net.ysy.shop.dbutil;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
/**
* 數據庫驅動程序
*/
private static final String DRIVER="com.mysql.jdbc.Driver";
/**
* 數據庫統一標識符
*/
private static final String URL="jdbc:mysql://localhost:3306/simonshop";
/**
* 數據庫用戶名
*/
private static final String USERNAME="root";
/**
* 數據庫密碼
*/
private static final String PASSWORD="pASSWORD";
/**
* 私有構造方法,拒絕實例化
*/
private ConnectionManager(){
}
/**
* 獲取數據庫連接靜態方法
* @return 數據庫連接對象
*/
public static Connection getconnection(){
//定義數據庫連接
Connection conn=null;
try{
//安裝驅動程序
Class.forName(DRIVER);
//獲取數據庫連接
conn= DriverManager.getConnection(URL
+"?useUnicode=true&charaterEncoding=UTF8",USERNAME,PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
//返回數據庫連接
return conn;
}
/**
* 關閉數據庫連接靜態方法
* @param conn
*/
public static void closeConnection(Connection conn){
//判斷數據庫連接是否爲空
if (conn !=null){
//判斷數據庫連接是否關閉
try{
if (!conn.isClosed()){
//關閉數據庫
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 測試數據庫連接是否成功
*/
public static void main(String[] args) {
//獲取數據庫連接
Connection conn=getconnection();
//判斷是否連接成功
if (conn !=null){
JOptionPane.showMessageDialog(null,"恭喜連接成功!");
}else {
JOptionPane.showMessageDialog(null,"遺憾,數據庫連接失敗!");
}
}
}
3.運行程序,查看結果
建議採用數據庫連接池,效率更高,建議使用數據源方式獲取數據連接.
(五)數據訪問接口(XXXDao)
1.用戶數據訪問接口UserDao
package net.ysy.shop.dao;
import net.ysy.shop.bean.User;
import java.sql.SQLException;
import java.util.List;
public interface UserDao {
//插入用戶
int insert(User user) throws SQLException;
//按標識符刪除用戶
int deleteById(int id);
//更新用戶
int update(User user);
//按標識符查詢用戶
User findById(int id);
//按用戶名查詢用戶
List<User> findByUsername(String username);
//查詢全部用戶
List<User> findAll();
//用戶登錄
User login(String username,String password);
}
2.類別數據訪問接口CategoryDao
package net.ysy.shop.dao;
import net.ysy.shop.bean.Category;
import java.util.List;
public interface CategoryDao {
//插入類別
int insert(Category category);
//按標識符刪除類別
int deletById(int id);
//更新類別
int update(Category category);
//按標識符查詢類別
Category findById(int id);
//查詢全部類別
List<Category> findAll();
}
3.商品數據訪問接口ProductDao
package net.ysy.shop.dao;
import net.ysy.shop.bean.Product;
import java.util.List;
public interface ProductDao {
//插入商品
int insert(Product product);
//按標識符刪除商品
int deletById(int id);
//更新商品
int update(Product product);
//按標識符查詢商品
Product findById(int id);
//按類別查詢商品
List<Product> findByCategoryId(int categoryId);
//查詢全部商品
List<Product> findAll();
}
4.訂單數據訪問接口OrderDao
package net.ysy.shop.dao;
import net.ysy.shop.bean.Order;
import java.util.List;
public interface OrderDao {
//插入訂單
int insert(Order order);
//按標識符刪除訂單
int deleteById(int id);
//更新訂單
int update(Order order);
//按標識符查詢訂單
Order findById(int id);
//查詢最後一個訂單
Order findLast();
//查詢全部訂單
List<Order> findAll();
}
(六)數據訪問接口實現類(XXXDaoImpl)
1.用戶數據訪問接口實現類UserDaoImpl
package net.ysy.shop.dao.impl;
import net.ysy.shop.bean.User;
import net.ysy.shop.dao.UserDao;
import net.ysy.shop.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements UserDao {
/**
* 插入用戶
*/
@Override
public int insert(User user) throws SQLException {
//定義插入記錄數
int count=0;
//獲得數據庫連接
Connection conn= ConnectionManager.getconnection();
//定義SQL字符串
String strSQL="INSERT INTO t_user(username,password,telephone,register_time,popedom)"+"VALUES(?,?,?,?,?)";
try {
//創建預備語句對象
PreparedStatement pstm=conn.prepareStatement(strSQL);
//設置佔位符的值
pstm.setString(1,user.getUsername());
pstm.setString(2,user.getPassword());
pstm.setString(3,user.getTelephone());
pstm.setTimestamp(4,new Timestamp(user.getRegisterTime().getTime()));
pstm.setInt(5,user.getPopedom());
//執行更新操作,插入新記錄
count=pstm.executeUpdate();
//關閉預備語句
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回插入記錄數
return count;
}
@Override
public int deleteById(int id) {
//定義刪除距離數
int count=0;
//獲得數據庫連接
Connection conn=ConnectionManager.getconnection();
//定義SQL字符串
String strSQL="DELETE FROM t_user WHERE id =? ";
try{
//創建預備語句
PreparedStatement pstm=conn.prepareStatement(strSQL);
//設置佔位符的值
pstm.setInt(1,id);
//執行更新操作,刪除記錄
count=pstm.executeUpdate();
//關閉預備語句對象
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回刪除距離數
return count;
}
/**
* 更新用戶
*/
@Override
public int update(User user) {
//定義記錄數
int count=0;
//獲取數據庫連接
Connection conn=ConnectionManager.getconnection();
//定義SQL字符串
String strSQL="UPDATE t_user SET username = ?,password = ?,telephone = ?,"
+"register_time = ? ,popem = ? WHERE id= ?";
try{
//創建預備語句對象
PreparedStatement pstm=conn.prepareStatement(strSQL);
//設置佔位符的值
pstm.setString(1,user.getUsername());
pstm.setString(2,user.getPassword());
pstm.setString(3,user.getTelephone());
pstm.setTimestamp(4,new Timestamp(user.getRegisterTime().getTime()));
pstm.setInt(5,user.getPopedom());
pstm.setInt(6,user.getId());
//執行更新操作,更新記錄
count=pstm.executeUpdate();
//關閉預備語句對象
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回更新記錄數
return count;
}
@Override
public User findById(int id) {
//聲明用戶
User user=null;
//獲取數據庫連接對象
Connection conn=ConnectionManager.getconnection();
//定義字符串
String strSQL=" SELECT * FROM t_user WHERE id =?";
try{
//創建預備語句對象
PreparedStatement pstm=conn.prepareStatement(strSQL);
//設置佔位符
pstm.setInt(1,id);
//執行SQL查詢,返回結果集
ResultSet rs=pstm.executeQuery();
//判斷結果集是否有記錄
if (rs.next()){
//實例化用戶
user=new User();
//利用當前記錄字段去設置商品類別屬性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
return user;
}
@Override
public List<User> findByUsername(String username) {
//聲明用戶列表
List<User> users=new ArrayList<User>();
//獲取數據庫連接對象
Connection conn=ConnectionManager.getconnection();
//定義SQL字符串
String strSQL="SELECT * FROM t_user WHERE username =? ";
try{
//創建預備語句
PreparedStatement pstm=conn.prepareStatement(strSQL);
//設置佔位符的值
pstm.setString(1,username);
//執行SQl查詢,返回結果集
ResultSet rs=pstm.executeQuery();
//遍歷結果集
while (rs.next()){
//創建類別實體類
User user=new User();
//設置實體屬性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
//將實體類添加到用戶列表
users.add(user);
}
//關閉結果集
rs.close();
//關閉語句對象
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
return users;
}
@Override
public List<User> findAll() {
//聲明用戶列表
List<User> users=new ArrayList<>();
//獲取數據庫連接對象
Connection conn=ConnectionManager.getconnection();
//定義SQL字符串
String strSQL="SELECT * FROM t_user";
try{
//創建預備語句
Statement stmt=conn.createStatement();
//執行SQL,返回結果集
ResultSet rs=stmt.executeQuery(strSQL);
while (rs.next()){
//設置實體屬性
User user=new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
//將實體類添加到用戶列表
users.add(user);
}
//關閉結果集
rs.close();
//關閉語句對象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
//返回用戶列表
return users;
}
/**
* 登錄方法
* @param username
* @param password
* @return
*/
@Override
public User login(String username, String password) {
//定義用戶對象
User user=null;
//獲取數據庫連接
Connection conn=ConnectionManager.getconnection();
//定義SQL字符
String strSQL="SELECT * FROM t_user WHERE username = ? AND password = ?";
try{
//創建預備語句
PreparedStatement pstm=conn.prepareStatement(strSQL);
//設置佔位符的值
pstm.setString(1,username);
pstm.setString(2,password);
//執行查詢,返回結果集
ResultSet rs=pstm.executeQuery();
//判斷結果集是否有記錄
if (rs.next()){
//實例化對象
user=new User();
//用戶記錄設置用戶屬性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getDate("register_time"));
user.setPopedom(rs.getInt("popedom"));
}
//關閉結果集
rs.close();
//關閉預備語句
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
//返回用戶對象
return user;
}
}
我們需要對用戶數據訪問接口實現類的各個方法進行單元測試,採用JUnit來進行單元測試.
在項目根目錄創建一個test文件夾,然後在項目結構窗口裏將標記爲"Tests",這樣文件夾顏色將變爲green.
在test文件夾裏面創建net.ysy.shop.dao.impl包,在裏面創建測試類TestUserDaoImpl
(1)編寫測試登錄方法testLogin()
將光標定位到@Test註解符,按組合鍵Alt+Enter:
package net.ysy.shop.dao.impl;
import net.ysy.shop.bean.User;
import net.ysy.shop.dao.UserDao;
import org.junit.Test;
public class TestUserDaoImpl {
@Test
public void testLogin(){
String username,password;
username="admin";
password="12345";
//父類接口指向子類對象
UserDao userDao=new UserDaoImpl();
//調用登錄用戶數據訪問對象的登錄方法
User user=userDao.login(username,password);
//判斷用戶是否登錄成功
if (user !=null){
System.out.println("恭喜,登錄成功!");
}else {
System.out.println("遺憾,登錄失敗!");
}
}
}
修改登錄密碼,在進行測試,看結構如何:
將用戶[塗文豔]的密碼改爲"123456",電話改爲"15883723523",塗文豔的用戶id是4,進行測試.
實現刪除用戶方法,尋找用戶id,進行刪除.