一、功能需求

1、只有注册用户成功登录之后才可查看商品类别,查看商品,选购商品,生成订单、查看订单。

2、只有管理员才有权限进入购物网后台管理,进行用户管理、类别管理、商品管理与订单管理。

二、设计思路

1、采用MVC设计模式

分层架构:展现层(JSP)<——>控制层(Servlet)<——>业务层(Service)<——>模型层(Dao)<——>数据库(DB)
2、前台

(1)登录——显示商品类别——显示某类商品信息——查看购物车——生成订单——支付

(2)注册<——>登录

3、后台

(1)用户管理:用户的增删改查

(2)类别管理:商品类别的增删改查

(3)商品管理:商品的增删改查

(4)订单管理:订单的查看与删除

说明:只完成了用户管理中的查看用户功能。其他功能,有兴趣的不妨拿来操练一下。
4、西蒙购物网业务流程图

三、实现步骤

(一)创建数据库

创建MySQL数据库simonshop,包含四张表:用户表(t_user)、类别表(t_category)、商品表(t_product)和订单表(t_order)。

1、用户表t_user

表结构,表记录


2、类别表t_category

表结构,表记录


3、商品表t_product

表结构,表记录


4、订单表t_order

表结构,表记录


ps:数据库命令文件

数据库命令文件

(二)创建Web项目simonshop


web项目创建过程

(三)创建实体类

在src里创建net.gongjing.shop.bean包,创建四个实体类:User、Category、Product与Order,与四张表t_user、t_category、t_product与t_order一一对应。

1、用户实体类User

package net.gongjing.shop.bean;/*** 功能:用户实体类* 作者:gongjing* 日期:2019年12月5日*/
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;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", telephone='" + telephone + '\'' +", registerTime=" + registerTime +", popedom=" + popedom +'}';}
}

2、类别实体类Category

package net.gongjing.shop.bean;/*** 功能:商品类别实体类* 作者:gongjing* 日期:2019年12月5日*/
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;}@Overridepublic String toString() {return "Category{" +"id=" + id +", name='" + name + '\'' +'}';}
}

3、商品实体类Product

package net.gongjing.shop.bean;/*** 功能:商品实体类* 作者:gongjing* 日期:2019年12月5日*/
import java.util.Date;public class Product {/*** 商品标识符*/private int id;/*** 商品名称*/private String name;/*** 商品单价*/private double price;/*** 商品上架时间*/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 double getPrice() {return price;}public void setPrice(double price) {this.price = price;}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;}@Overridepublic String toString() {return "Product{" +"id=" + id +", name='" + name + '\'' +", price=" + price +", addTime=" + addTime +", categoryId=" + categoryId +'}';}
}

4、订单实体类Order

package net.gongjing.shop.bean;/*** 功能:订单实体类* 作者:gongjing* 日期:2019年12月5日*/
import java.util.Date;public class Order {/*** 订单标识符*/private int id;/*** 用户名*/private String username;/*** 联系电话*/private String telephone;/*** 订单总金额*/private double totalPrice;/*** 送货地址*/private String deliveryAddress;/*** 下单时间*/private Date 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 double getTotalPrice() {return totalPrice;}public void setTotalPrice(double totalPrice) {this.totalPrice = totalPrice;}public String getDeliveryAddress() {return deliveryAddress;}public void setDeliveryAddress(String deliveryAddress) {this.deliveryAddress = deliveryAddress;}public Date getOrderTime() {return orderTime;}public void setOrderTime(Date orderTime) {this.orderTime = orderTime;}@Overridepublic String toString() {return "Order{" +"id=" + id +", username='" + username + '\'' +", telephone='" + telephone + '\'' +", totalPrice=" + totalPrice +", deliveryAddress='" + deliveryAddress + '\'' +", orderTime=" + orderTime +'}';}
}

(四)创建数据库工具类ConnectionManager

1、在web\WEB-INF目录下创建lib子目录,添加MySQL驱动程序的jar包


MySQL驱动程序的jar包

2、在src下创建net.hw.shop.dbutil包,在里面创建ConnectionManager类

package net.gongjing.shop.dbutil;/*** 功能:数据库连接管理类* 作者:gongjing* 日期:2019年12月5日*/import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;import javax.swing.JOptionPane;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 = "gongjing";/*** 私有化构造方法,拒绝实例化*/private ConnectionManager() {}/*** 获取数据库连接静态方法** @return 数据库连接对象*/public static Connection getConnection() {// 定义数据库连接Connection conn = null;try {// 安装数据库驱动程序Class.forName(DRIVER);// 获得数据库连接conn = DriverManager.getConnection(URL+ "?useUnicode=true&characterEncoding=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();}}}/*** 测试数据库连接是否成功** @param args*/public static void main(String[] args) {// 获得数据库连接Connection conn = getConnection();// 判断是否连接成功if (conn != null) {JOptionPane.showMessageDialog(null, "恭喜,数据库连接成功!");} else {JOptionPane.showMessageDialog(null, "遗憾,数据库连接失败!");}// 关闭数据库连接closeConnection(conn);}
}

运行结果如下

(五)数据访问接口(XXXDao)

在src里创建net.hw.shop.dao包,在里面创建UserDao、CategoryDao、ProductDao与OrderDao。

1、用户数据访问接口UserDao

package net.gongjing.shop.dao;/*** 功能:用户数据访问接口* 作者:gongjing* 日期:2019年12月5日*/
import java.util.List;import net.gongjing.shop.bean.User;public interface UserDao {// 插入用户int insert(User user);// 按标识符删除用户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.gongjing.shop.dao;/*** 功能:类别数据访问接口* 作者:gongjing* 日期:2019年12月5日*/
import java.util.List;import net.gongjing.shop.bean.Category;public interface CategoryDao {// 插入类别int insert(Category category);// 按标识符删除类别int deleteById(int id);// 更新类别int update(Category category);// 按标识符查询类别Category findById(int id);// 查询全部类别List<Category> findAll();
}

3、商品数据访问接口ProductDao

package net.gongjing.shop.dao;/*** 功能:商品数据访问接口* 作者:gongjing* 日期:2019年12月5日*/
import java.util.List;import net.gongjing.shop.bean.Product;public interface ProductDao {// 插入商品int insert(Product product);// 按标识符删除商品int deleteById(int id);// 更新商品int update(Product product);// 按标识符查询商品Product findById(int id);// 按类别查询商品List<Product> findByCategoryId(int categoryId);// 查询全部商品List<Product> findAll();
}

4、订单数据访问接口OrderDao

package net.gongjing.shop.dao;/*** 功能:订单数据访问接口* 作者:华卫* 日期:2019年12月2日*/
import java.util.List;import net.gongjing.shop.bean.Order;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

在src下创建net.hw.shop.dao.impl包,在里面创建UserDaoImpl、CategoryDaoImpl、ProductDaoImpl与OrderDaoImpl。

1、用户数据访问接口实现类UserDaoImpl

package net.gongjing.shop.dao.impl;/*** 功能:用户数据访问接口实现类* 作者:华卫* 日期:2019年12月2日*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;import net.gongjing.shop.bean.User;
import net.gongjing.shop.dao.UserDao;
import net.gongjing.shop.dbutil.ConnectionManager;public class UserDaoImpl implements UserDao {/*** 插入用户*/@Overridepublic int insert(User user) {// 定义插入记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "INSERT INTO t_user (username, password, telephone, register_time, popedom)"+ " VALUES (?, ?, ?, ?, ?)";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setString(1, user.getUsername());pstmt.setString(2, user.getPassword());pstmt.setString(3, user.getTelephone());pstmt.setTimestamp(4, new Timestamp(user.getRegisterTime().getTime()));pstmt.setInt(5, user.getPopedom());// 执行更新操作,插入新记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回插入记录数return count;}/*** 删除用户记录*/@Overridepublic int deleteById(int id) {// 定义删除记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "DELETE FROM t_user WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setInt(1, id);// 执行更新操作,删除记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回删除记录数return count;}/*** 更新用户*/@Overridepublic int update(User user) {// 定义更新记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "UPDATE t_user SET username = ?, password = ?, telephone = ?,"+ " register_time = ?, popedom = ? WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setString(1, user.getUsername());pstmt.setString(2, user.getPassword());pstmt.setString(3, user.getTelephone());pstmt.setTimestamp(4, new Timestamp(user.getRegisterTime().getTime()));pstmt.setInt(5, user.getPopedom());pstmt.setInt(6, user.getId());// 执行更新操作,更新记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回更新记录数return count;}/*** 按标识符查询用户*/@Overridepublic User findById(int id) {// 声明用户User user = null;// 获取数据库连接对象Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "SELECT * FROM t_user WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setInt(1, id);// 执行SQL查询,返回结果集ResultSet rs = pstmt.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.getTimestamp("register_time"));user.setPopedom(rs.getInt("popedom"));}} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回用户return user;}@Overridepublic 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 pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setString(1, username);// 执行SQL查询,返回结果集ResultSet rs = pstmt.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();// 关闭语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {// 关闭数据库连接ConnectionManager.closeConnection(conn);}// 返回用户列表return users;}@Overridepublic List<User> findAll() {// 声明用户列表List<User> users = new ArrayList<User>();// 获取数据库连接对象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;}/*** 登录方法*/@Overridepublic 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 psmt = conn.prepareStatement(strSQL);// 设置占位符的值psmt.setString(1, username);psmt.setString(2, password);// 执行查询,返回结果集ResultSet rs = psmt.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();// 关闭预备语句psmt.close();} catch (SQLException e) {e.printStackTrace();} finally {// 关闭数据库连接ConnectionManager.closeConnection(conn);}// 返回用户对象return user;}
}

我们需要对用户数据访问接口实现类的各个方法进行单元测试,采用JUnit来进行单元测试。

在项目根目录创建一个test文件夹,然后在项目结构窗口里将其标记为"Tests",这样文件夹颜色变成绿色。

(1)编写测试登录方法testLogin()

package test.net.gongjing.shop.dao.impl;import net.gongjing.shop.bean.User;
import net.gongjing.shop.dao.UserDao;
import net.gongjing.shop.dao.impl.UserDaoImpl;
import org.junit.Test;import java.util.Date;
import java.util.List;public class TestUserDaoImpl {@Testpublic 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("遗憾,登录失败!");}}@Testpublic void testUpdate() {//定义用户数据访问对象UserDao userDao = new UserDaoImpl();//找到id为4的用户[涂文艳]User user = userDao. findById(4);//修改用户密码与电话user. setPassword( "903213");user. setTelephone( "13945457890");//利用用户数据访问对象的更新方法更新用户int count = userDao . update(user);//判断更新用户是否成功if (count > 0) {System. out . println("恭喜,用户更新成功! ");} else {System. out . println("遗憾,用户更新失败! ");}// 再次查询id为4的用户user = userDao. findById(4);//输出该用户的信息System. out . println(user);}//插入@Testpublic void testInsert(){UserDao userDao = new UserDaoImpl();User user = new User();user.setUsername("ZJY");user.setPassword("123456");user.setTelephone("13378323305");user.setRegisterTime(new Date());user.setPopedom(1);int count = userDao.insert(user);if (count > 0){System.out.println("恭喜,用户插入成功");}else {System.out.println("遗憾,用户插入失败");}}//删除@Testpublic void testDeleteById(){UserDao userDao = new UserDaoImpl();int count = userDao.deleteById(2);if (count > 0){System.out.println("恭喜,用户删除成功");}else {System.out.println("遗憾,用户删除失败");}}//按用户名查询@Testpublic void testFindByUsername(){String username;username = "123456";UserDao userDao = new UserDaoImpl();List<User> user = userDao.findByUsername(username);if (user != null){System.out.println("查询成功");System.out.println(user);}else {System.out.println("查询失败");}}//查询全部@Testpublic void testFindAll(){UserDao userDao = new UserDaoImpl();List<User> users = userDao.findAll();if (!users.isEmpty()){System.out.println("查询成功");}else {System.out.println("查询失败");}}@Testpublic void testFindById(){UserDao userDao = new UserDaoImpl();User user = userDao.findById(10);if (user == null){System.out.println("查询失败");}else {System.out.println("查询成功");System.out.println(user);}}}

各自运行结果





2、类别数据访问接口实现类CategoryDaoImpl

package net.gongjing.shop.dao.impl;/*** 功能:类别数据访问接口实现类* 作者:华卫* 日期:2019年12月10日*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;import net.gongjing.shop.bean.Category;
import net.gongjing.shop.dao.CategoryDao;
import net.gongjing.shop.dbutil.ConnectionManager;public class CategoryDaoImpl implements CategoryDao {/*** 插入类别*/@Overridepublic int insert(Category category) {// 定义插入记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "INSERT INTO t_category (name) VALUES (?)";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setString(1, category.getName());// 执行更新操作,插入新录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回插入记录数return count;}/*** 删除类别*/@Overridepublic int deleteById(int id) {// 定义删除记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "DELETE FROM t_category WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setInt(1, id);// 执行更新操作,删除记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回删除记录数return count;}/*** 更新类别*/@Overridepublic int update(Category category) {// 定义更新记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "UPDATE t_category SET name = ? WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setString(1, category.getName());pstmt.setInt(2, category.getId());// 执行更新操作,更新记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回更新记录数return count;}/*** 按标识符查询类别*/@Overridepublic Category findById(int id) {// 声明商品类别Category category = null;// 获取数据库连接对象Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "SELECT * FROM t_category WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setInt(1, id);// 执行SQL查询,返回结果集ResultSet rs = pstmt.executeQuery();// 判断结果集是否有记录if (rs.next()) {// 实例化商品类别category = new Category();// 利用当前记录字段值去设置商品类别的属性category.setId(rs.getInt("id"));category.setName(rs.getString("name"));}} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回商品类别return category;}/*** 查询全部类别*/@Overridepublic List<Category> findAll() {// 声明类别列表List<Category> categories = new ArrayList<Category>();// 获取数据库连接对象Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "SELECT * FROM t_category";try {// 创建语句对象Statement stmt = conn.createStatement();// 执行SQL,返回结果集ResultSet rs = stmt.executeQuery(strSQL);// 遍历结果集while (rs.next()) {// 创建类别实体Category category = new Category();// 设置实体属性category.setId(rs.getInt("id"));category.setName(rs.getString("name"));// 将实体添加到类别列表categories.add(category);}// 关闭结果集rs.close();// 关闭语句对象stmt.close();} catch (SQLException e) {e.printStackTrace();} finally {// 关闭数据库连接ConnectionManager.closeConnection(conn);}// 返回类别列表return categories;}
}

测试代码

package test.net.gongjing.shop.dao.impl;import net.gongjing.shop.bean.Category;
import net.gongjing.shop.dao.CategoryDao;
import net.gongjing.shop.dao.impl.CategoryDaoImpl;
import org.junit.Test;import java.util.List;public class TestCategoryDaoImpl {@Testpublic void testFindAll(){CategoryDao categoryDao = new CategoryDaoImpl();List<Category> categories = categoryDao.findAll();//判断是否有类别//判断集合是否为空有两种方式  size()>0    isEmpty()if(!categories.isEmpty()){for (Category category: categories){System.out.println(category);}}else {System.out.println("没有商品类别!");}}@Testpublic void testFindById(){CategoryDao categoryDao = new CategoryDaoImpl();Category category = categoryDao.findById(3);if (category == null){System.out.println("查询失败");}else {System.out.println("查询成功");System.out.println(category);}}@Testpublic void testUpdate(){CategoryDao categoryDao = new CategoryDaoImpl();Category category = categoryDao.findById(3);category.setName("不实用电器");int count = categoryDao.update(category);if (count > 0){System.out.println("更新成功");System.out.println(category);}else {System.out.println("更新失败");}}@Testpublic void testDelete(){CategoryDao categoryDao = new CategoryDaoImpl();int count  = categoryDao.deleteById(2);if (count > 0){System.out.println("删除成功");}else {System.out.println("删除失败");}}@Testpublic void testInsert(){CategoryDao categoryDao = new CategoryDaoImpl();Category category = new Category();category.setName("实用工具");int count = categoryDao.insert(category);if (count > 0){System.out.println("插入成功");}else {System.out.println("插入失败");}}
}

测试结果不予展示,自行测试

3、商品数据访问接口实现类ProductDaoImpl

package net.gongjing.shop.dao.impl;/*** 功能:产品数据访问接口实现类* 作者:华卫* 日期:2019年12月2日*/import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;import net.gongjing.shop.bean.Product;
import net.gongjing.shop.dao.ProductDao;
import net.gongjing.shop.dbutil.ConnectionManager;public class ProductDaoImpl implements ProductDao {/*** 插入商品*/@Overridepublic int insert(Product product) {// 定义插入记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "INSERT INTO t_product (name, price, add_time, category_id)" + " VALUES (?, ?, ?, ?)";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setString(1, product.getName());pstmt.setDouble(2, product.getPrice());pstmt.setTimestamp(3, new Timestamp(product.getAddTime().getTime()));pstmt.setInt(4, product.getCategoryId());// 执行更新操作,插入新记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回插入记录数return count;}/*** 删除商品*/@Overridepublic int deleteById(int id) {// 定义删除记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "DELETE FROM t_product WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setInt(1, id);// 执行更新操作,删除记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回删除记录数return count;}/*** 更新商品*/@Overridepublic int update(Product product) {// 定义更新记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "UPDATE t_product SET name = ?, price = ?, add_time = ?,"+ " category_id = ? WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setString(1, product.getName());pstmt.setDouble(2, product.getPrice());pstmt.setTimestamp(3, new Timestamp(product.getAddTime().getTime()));pstmt.setInt(4, product.getCategoryId());pstmt.setInt(5, product.getId());// 执行更新操作,更新记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回更新记录数return count;}/*** 按标识符查找商品*/@Overridepublic Product findById(int id) {// 声明商品Product product = null;// 获取数据库连接对象Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "SELECT * FROM t_product WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setInt(1, id);// 执行SQL查询,返回结果集ResultSet rs = pstmt.executeQuery();// 判断结果集是否有记录if (rs.next()) {// 实例化商品product = new Product();// 利用当前记录字段值去设置商品类别的属性product.setId(rs.getInt("id"));product.setName(rs.getString("name"));product.setPrice(rs.getDouble("price"));product.setAddTime(rs.getTimestamp("add_time"));product.setCategoryId(rs.getInt("category_id"));}} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回商品return product;}/*** 按类别查询商品*/@Overridepublic List<Product> findByCategoryId(int categoryId) {// 定义商品列表List<Product> products = new ArrayList<Product>();// 获取数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "SELECT * FROM t_product WHERE category_id = ?";try {// 创建预备语句PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setInt(1, categoryId);// 执行SQL语句,返回结果集ResultSet rs = pstmt.executeQuery();// 遍历结果集,将其中的每条记录生成商品对象,添加到商品列表while (rs.next()) {// 实例化商品对象Product product = new Product();// 利用当前记录字段值设置实体对应属性product.setId(rs.getInt("id"));product.setName(rs.getString("name"));product.setPrice(rs.getDouble("price"));product.setAddTime(rs.getTimestamp("add_time"));product.setCategoryId(rs.getInt("category_id"));// 将商品添加到商品列表products.add(product);}} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回商品列表return products;}/*** 查询全部商品*/@Overridepublic List<Product> findAll() {// 声明商品列表List<Product> products = new ArrayList<Product>();// 获取数据库连接对象Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "SELECT * FROM t_product";try {// 创建语句对象Statement stmt = conn.createStatement();// 执行SQL,返回结果集ResultSet rs = stmt.executeQuery(strSQL);// 遍历结果集while (rs.next()) {// 创建商品实体Product product = new Product();// 设置实体属性product.setId(rs.getInt("id"));product.setName(rs.getString("name"));product.setPrice(rs.getDouble("price"));product.setAddTime(rs.getTimestamp("add_time"));product.setCategoryId(rs.getInt("category_id"));// 将实体添加到商品列表products.add(product);}// 关闭结果集rs.close();// 关闭语句对象stmt.close();} catch (SQLException e) {e.printStackTrace();} finally {// 关闭数据库连接ConnectionManager.closeConnection(conn);}// 返回商品列表return products;}
}

测试代码

package test.net.gongjing.shop.dao.impl;import net.gongjing.shop.bean.Category;
import net.gongjing.shop.bean.Product;
import net.gongjing.shop.bean.User;
import net.gongjing.shop.dao.CategoryDao;
import net.gongjing.shop.dao.ProductDao;
import net.gongjing.shop.dao.UserDao;
import net.gongjing.shop.dao.impl.CategoryDaoImpl;
import net.gongjing.shop.dao.impl.ProductDaoImpl;
import org.junit.Test;import java.util.Date;
import java.util.List;public class TestProductDaoImpl {@Testpublic void testUpdate(){ProductDao productDao = new ProductDaoImpl();Product product = productDao.findById(3);product.setName("Yaa");int count = productDao.update(product);if (count > 0){System.out.println("恭喜,用户更新成功");}else {System.out.println("遗憾,用户更新失败");}}//按类别@Testpublic void testFindByCategoryId(){//创建商品数据访问对象ProductDao productDao = new ProductDaoImpl();int categoryId = 5;CategoryDao categoryDao = new CategoryDaoImpl();if (categoryDao.findById(categoryId) != null){String categoryName = categoryDao.findById(categoryId).getName();List<Product> products = productDao.findByCategoryId(categoryId);if (!products.isEmpty()){for (Product product: products){System.out.println(product);}}else {System.out.println("["+ categoryName +"]类别没有商品!");}}else {System.out.println("类别编号[" + categoryId + "]不存在!");};}@Testpublic void testFindAll(){ProductDao productDao = new ProductDaoImpl();List<Product> products = productDao.findAll();//判断是否有类别//判断集合是否为空有两种方式  size()>0    isEmpty()if(!products.isEmpty()){for (Product product: products){System.out.println(product);}}else {System.out.println("没有商品类别!");}}@Testpublic void testInsert(){ProductDao productDao = new ProductDaoImpl();Product product =  new Product();product.setName("学习办公123");product.setAddTime(new Date());product.setCategoryId(1);product.setPrice(200);int count = productDao.insert(product);if (count > 0){System.out.println("插入成功");}else {System.out.println("插入失败");}}@Testpublic void testFindById(){ProductDao productDao = new ProductDaoImpl();Product product = productDao.findById(1);if (product == null){System.out.println("查询失败");}else {System.out.println("查询成功");System.out.println(product);}}@Testpublic void testDelete(){ProductDao productDao = new ProductDaoImpl();int count  = productDao.deleteById(100);if (count > 0){System.out.println("删除成功");}else {System.out.println("删除失败");

4、订单数据访问接口实现类OrderDaoImpl

package net.gongjing.shop.dao.impl;
/*** 功能:订单数据访问接口实现类* 作者:华卫* 日期:2019年12月2日*/import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;import net.gongjing.shop.bean.Order;
import net.gongjing.shop.dao.OrderDao;
import net.gongjing.shop.dbutil.ConnectionManager;public class OrderDaoImpl implements OrderDao {/*** 插入订单*/@Overridepublic int insert(Order order) {// 定义插入记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "INSERT INTO t_order (username, telephone, total_price, delivery_address, order_time)"+ " VALUES (?, ?, ?, ?, ?)";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setString(1, order.getUsername());pstmt.setString(2, order.getTelephone());pstmt.setDouble(3, order.getTotalPrice());pstmt.setString(4, order.getDeliveryAddress());pstmt.setTimestamp(5, new Timestamp(order.getOrderTime().getTime()));// 执行更新操作,插入记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回插入记录数return count;}/*** 删除订单*/@Overridepublic int deleteById(int id) {// 定义删除记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "DELETE FROM t_order WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setInt(1, id);// 执行更新操作,删除记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回删除记录数return count;}/*** 更新订单*/@Overridepublic int update(Order order) {// 定义更新记录数int count = 0;// 获得数据库连接Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "UPDATE t_order SET username = ?, telephone = ?, total_price = ?,"+ " delivery_address = ?, order_time = ? WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setString(1, order.getUsername());pstmt.setString(2, order.getTelephone());pstmt.setDouble(3, order.getTotalPrice());pstmt.setString(4, order.getDeliveryAddress());pstmt.setTimestamp(5, new Timestamp(order.getOrderTime().getTime()));pstmt.setInt(6, order.getId());// 执行更新操作,更新记录count = pstmt.executeUpdate();// 关闭预备语句对象pstmt.close();} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回更新记录数return count;}/*** 查询最后一个订单*/@Overridepublic Order findLast() {// 声明订单Order order = null;// 获取数据库连接对象Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "SELECT * FROM t_order";try {// 创建语句对象Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);// 执行SQL,返回结果集ResultSet rs = stmt.executeQuery(strSQL);// 定位到最后一条记录if (rs.last()) {// 创建订单实体order = new Order();// 设置实体属性order.setId(rs.getInt("id"));order.setUsername(rs.getString("username"));order.setTelephone(rs.getString("telephone"));order.setTotalPrice(rs.getDouble("total_price"));order.setDeliveryAddress(rs.getString("delivery_address"));order.setOrderTime(rs.getTimestamp("order_time"));}// 关闭结果集rs.close();// 关闭语句对象stmt.close();} catch (SQLException e) {e.printStackTrace();} finally {// 关闭数据库连接ConnectionManager.closeConnection(conn);}// 返回订单对象return order;}/*** 按标识符查询订单*/@Overridepublic Order findById(int id) {// 声明订单Order order = null;// 获取数据库连接对象Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "SELECT * FROM t_order WHERE id = ?";try {// 创建预备语句对象PreparedStatement pstmt = conn.prepareStatement(strSQL);// 设置占位符的值pstmt.setInt(1, id);// 执行SQL查询,返回结果集ResultSet rs = pstmt.executeQuery();// 判断结果集是否有记录if (rs.next()) {// 实例化订单order = new Order();// 利用当前记录字段值去设置订单的属性order.setId(rs.getInt("id"));order.setUsername(rs.getString("username"));order.setTelephone(rs.getString("telephone"));order.setDeliveryAddress(rs.getString("delivery_address"));order.setOrderTime(rs.getTimestamp("order_time"));}} catch (SQLException e) {e.printStackTrace();} finally {ConnectionManager.closeConnection(conn);}// 返回订单return order;}/*** 查询全部订单*/@Overridepublic List<Order> findAll() {// 声明订单列表List<Order> orders = new ArrayList<Order>();// 获取数据库连接对象Connection conn = ConnectionManager.getConnection();// 定义SQL字符串String strSQL = "SELECT * FROM t_order";try {// 创建语句对象Statement stmt = conn.createStatement();// 执行SQL,返回结果集ResultSet rs = stmt.executeQuery(strSQL);// 遍历结果集while (rs.next()) {// 创建订单实体Order order = new Order();// 设置实体属性order.setId(rs.getInt("id"));order.setUsername(rs.getString("username"));order.setTelephone(rs.getString("telephone"));order.setDeliveryAddress(rs.getString("delivery_address"));order.setOrderTime(rs.getTimestamp("order_time"));// 将实体添加到订单列表orders.add(order);}// 关闭结果集rs.close();// 关闭语句对象stmt.close();} catch (SQLException e) {e.printStackTrace();} finally {// 关闭数据库连接ConnectionManager.closeConnection(conn);}// 返回用户列表return orders;}
}

测试代码

package test.net.gongjing.shop.dao.impl;import com.sun.org.apache.xpath.internal.operations.Or;
import net.gongjing.shop.bean.Order;
import net.gongjing.shop.dao.OrderDao;
import net.gongjing.shop.dao.impl.OrderDaoImpl;
import org.junit.Test;import java.util.Date;
import java.util.List;public class TestOrderService {@Testpublic void testFindAll(){OrderDao orderDao = new OrderDaoImpl();List<Order> orders = orderDao.findAll();if (orders.size() > 0 ){for (Order order: orders){System.out.println(order);}}else {System.out.println("没有订单!");}}@Testpublic void testUpdate(){OrderDao orderDao = new OrderDaoImpl();Order order = orderDao.findById(3);order.setUsername("ZZJJYY");int count = orderDao.update(order);if (count > 0){System.out.println("恭喜,用户更新成功");}else {System.out.println("遗憾,用户更新失败");}}//插入@Testpublic void testInsert(){OrderDao orderDao = new OrderDaoImpl();Order order = new Order();order.setUsername("YUK");order.setDeliveryAddress("China");order.setOrderTime(new Date());order.setTelephone("123336333");int count = orderDao.insert(order);if (count > 0){System.out.println("恭喜,订单插入成功");}else {System.out.println("遗憾,订单插入失败");}}//删除@Testpublic void testDeleteById(){OrderDao orderDao = new OrderDaoImpl();Order order = new OrderDaoImpl().findById(4);int count = orderDao.deleteById(4);if (count > 0){System.out.println("恭喜,订单删除成功");System.out.println(order);}else {System.out.println("遗憾,订单删除失败");}}//按id查询@Testpublic void testFindById(){OrderDao orderDao = new OrderDaoImpl();Order order  = orderDao.findById(9);if (order== null){System.out.println("查询失败");}else {System.out.println("查询成功");System.out.println(order);}}@Testpublic void testFindLast(){OrderDao orderDao = new OrderDaoImpl();Order order = orderDao.findLast();if (order== null){System.out.println("查询失败");}else {System.out.println("查询成功");System.out.println(order);}}}

(七)数据访问服务类XXXService

在src里创建net.hw.shop.service包,在里面创建四个服务类:UserService、CategoryService、ProductService与OrderService。

1、用户服务类UserService

package net.gongjing.shop.service;/*** 功能:用户服务类* 作者:gongjing* 日期:2019年12月5日*/import java.util.List;import net.gongjing.shop.bean.User;
import net.gongjing.shop.dao.UserDao;
import net.gongjing.shop.dao.impl.UserDaoImpl;public class UserService {/*** 声明用户访问对象*/private UserDao userDao = new UserDaoImpl();public int addUser(User user) {return userDao.insert(user);}public int deleteUserById(int id) {return userDao.deleteById(id);}public int updateUser(User user) {return userDao.update(user);}public User findUserById(int id) {return userDao.findById(id);}public List<User> findUsersByUsername(String username) {return userDao.findByUsername(username);}public List<User> findAllUsers() {return userDao.findAll();}public User login(String username, String password) {return userDao.login(username, password);}
}

测试代码

package test.net.gongjing.shop.service;import net.gongjing.shop.bean.User;
import net.gongjing.shop.dao.UserDao;
import net.gongjing.shop.dao.impl.UserDaoImpl;
import org.junit.Test;import java.util.Date;
import java.util.List;public class TestUserService {@Testpublic 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("遗憾登陆失败");}}@Testpublic void testUpdateUser(){UserDao userDao = new UserDaoImpl();User user = userDao.findById(3);user.setPassword("123");user.setTelephone("133909");if (user == null){System.out.println("恭喜,用户更新成功");System.out.println(user);}else {System.out.println("遗憾,用户更新失败");}}//插入@Testpublic void testAddUser(){UserDao userDao = new UserDaoImpl();User user = new User();user.setUsername("ZJY");user.setPassword("123456");user.setTelephone("13378323305");user.setRegisterTime(new Date());user.setPopedom(1);int count = userDao.insert(user);if (count > 0 ){System.out.println("恭喜,用户插入成功");}else {System.out.println("遗憾,用户插入失败");}}//删除@Testpublic void testDeleteUserById(){UserDao userDao = new UserDaoImpl();int count = userDao.deleteById(2);if (count > 0){System.out.println("恭喜,用户删除成功");}else {System.out.println("遗憾,用户删除失败");}}//按用户名查询@Testpublic void testFindUserByUsername(){String username;username = "admin";UserDao userDao = new UserDaoImpl();List<User> user = userDao.findByUsername(username);if (!user.isEmpty()){System.out.println("查询成功");System.out.println(user);}else {System.out.println("查询失败");}}//查询全部@Testpublic void testFindAllUser(){UserDao userDao = new UserDaoImpl();List<User> user = userDao.findAll();if (!user.isEmpty()){System.out.println("查询成功");System.out.println(user);}else {System.out.println("查询失败");}}@Testpublic void testFindUserById(){UserDao userDao = new UserDaoImpl();User user = userDao.findById(1);if (user == null){System.out.println("查询失败");}else {System.out.println("查询成功");System.out.println(user);}}}

2、类别服务类CategoryService

package net.gongjing.shop.service;/*** 功能:类别服务类* 作者:gongjing* 日期:2019年12月2日*/import java.util.List;import net.gongjing.shop.bean.Category;
import net.gongjing.shop.dao.CategoryDao;
import net.gongjing.shop.dao.impl.CategoryDaoImpl;public class CategoryService {/*** 声明类别数据访问对象*/private CategoryDao categoryDao = new CategoryDaoImpl();public int addCategory(Category category) {return categoryDao.insert(category);}public int deleteCategoryById(int id) {return categoryDao.deleteById(id);}public int updateCategory(Category category) {return categoryDao.update(category);}public Category findCategoryById(int id) {return categoryDao.findById(id);}public List<Category> findAllCategories() {return categoryDao.findAll();}
}

测试代码

package test.net.gongjing.shop.service;import net.gongjing.shop.bean.Category;
import net.gongjing.shop.dao.CategoryDao;
import net.gongjing.shop.dao.impl.CategoryDaoImpl;
import org.junit.Test;import java.util.List;public class TestCategoryService {@Testpublic void testAddCategory(){CategoryDao categoryDao = new CategoryDaoImpl();Category category = new Category();category.setName("实用工具");int count = categoryDao.insert(category);if (count > 0){System.out.println("插入成功");}else {System.out.println("插入失败");}}@Testpublic void testDeleteCategoryById(){CategoryDao categoryDao = new CategoryDaoImpl();int count  = categoryDao.deleteById(2);if (count > 0){System.out.println("删除成功");}else {System.out.println("删除失败");}}@Testpublic void testUpdateCategory(){CategoryDao categoryDao = new CategoryDaoImpl();Category category = categoryDao.findById(3);//     category.setName("不实用电器");
//        int count = categoryDao.update(category);if (category == null){System.out.println("更新成功");}else {System.out.println("更新失败");}}@Testpublic void testFindCategoryById(){CategoryDao categoryDao = new CategoryDaoImpl();Category category = categoryDao.findById(2);if (category == null){System.out.println("查询失败");}else {System.out.println("查询成功");}System.out.println(category);}@Testpublic void testFindAllCategories(){CategoryDao categoryDao = new CategoryDaoImpl();List<Category> categories = categoryDao.findAll();//判断是否有类别//判断集合是否为空有两种方式  size()>0    isEmpty()if(!categories.isEmpty()){for (Category category: categories){System.out.println(category);}}else {System.out.println("没有商品类别!");}}
}

3、商品服务类ProductService

package net.gongjing.shop.service;/*** 功能:商品服务类* 作者:gongjing* 日期:2019年12月5日*/import java.util.List;import net.gongjing.shop.bean.Product;
import net.gongjing.shop.dao.ProductDao;
import net.gongjing.shop.dao.impl.ProductDaoImpl;public class ProductService {/*** 声明商品数据访问对象*/private ProductDao productDao = new ProductDaoImpl();public int addProduct(Product product) {return productDao.insert(product);}public int deleteProductById(int id) {return productDao.deleteById(id);}public int updateProduct(Product product) {return productDao.update(product);}public Product findProductById(int id) {return productDao.findById(id);}public List<Product> findProductsByCategoryId(int categoryId) {return productDao.findByCategoryId(categoryId);}public List<Product> findAllProducts() {return productDao.findAll();}
}

测试代码

package test.net.gongjing.shop.service;import net.gongjing.shop.bean.Product;
import net.gongjing.shop.dao.CategoryDao;
import net.gongjing.shop.dao.ProductDao;
import net.gongjing.shop.dao.impl.CategoryDaoImpl;
import net.gongjing.shop.dao.impl.ProductDaoImpl;
import org.junit.Test;import java.util.Date;
import java.util.List;public class TestProductService {@Testpublic void testUpdateProduct(){ProductDao productDao = new ProductDaoImpl();Product product = productDao.findById(2);//product.setName("Yss");if (product == null){System.out.println("恭喜,用户更新成功");}else {System.out.println("遗憾,用户更新失败");}}//按类别@Testpublic void testFindProductsByCategoryId(){//创建商品数据访问对象ProductDao productDao = new ProductDaoImpl();int categoryId = 2;CategoryDao categoryDao = new CategoryDaoImpl();if (categoryDao.findById(categoryId) != null){String categoryName = categoryDao.findById(categoryId).getName();List<Product> products = productDao.findByCategoryId(categoryId);if (!products.isEmpty()){for (Product product: products){System.out.println(product);}}else {System.out.println("该类别下面没商品");}}else {System.out.println("类别编号[" + categoryId + "]不存在");};}@Testpublic void testFindAllProduct(){ProductDao productDao = new ProductDaoImpl();List<Product> products = productDao.findAll();//判断是否有类别//判断集合是否为空有两种方式  size()>0    isEmpty()if(!products.isEmpty()){for (Product product: products){System.out.println(product);}}else {System.out.println("没有商品类别!");}}@Testpublic void testAddProduct(){ProductDao productDao = new ProductDaoImpl();Product product =  new Product();product.setName("学习办公123");product.setAddTime(new Date());product.setCategoryId(1);product.setPrice(200);int count = productDao.insert(product);if (count > 0){System.out.println("插入成功");}else {System.out.println("插入失败");}}@Testpublic void testFindProductById(){ProductDao productDao = new ProductDaoImpl();Product product = productDao.findById(200);if (product == null){System.out.println("查询失败");}else {System.out.println("查询成功");}System.out.println(product);}@Testpublic void testDeleteProductById(){ProductDao productDao = new ProductDaoImpl();int count  = productDao.deleteById(1);if (count > 0){System.out.println("删除成功");}else {System.out.println("删除失败");}}
}

4、订单服务类OrderService

package net.gongjing.shop.service;/*** 功能:订单服务类* 作者:gongjing* 日期:2019年12月2日*/import java.util.List;import net.gongjing.shop.bean.Order;
import net.gongjing.shop.dao.OrderDao;
import net.gongjing.shop.dao.impl.OrderDaoImpl;public class OrderService {/*** 声明订单数据访问对象*/OrderDao orderDao = new OrderDaoImpl();public int addOrder(Order order) {return orderDao.insert(order);}public int deleteOrderById(int id) {return orderDao.deleteById(id);}public int updateOrder(Order order) {return orderDao.update(order);}public Order findOrderById(int id) {return orderDao.findById(id);}public Order findLastOrder() {return orderDao.findLast();}public List<Order> findAllOrders() {return orderDao.findAll();}
}

测试代码

package test.net.gongjing.shop.service;import net.gongjing.shop.bean.Order;
import net.gongjing.shop.dao.OrderDao;
import net.gongjing.shop.dao.impl.OrderDaoImpl;
import org.junit.Test;import java.util.Date;
import java.util.List;public class TestOrderService {@Testpublic void testFindAllOrders(){OrderDao orderDao = new OrderDaoImpl();List<Order> orders = orderDao.findAll();if (orders.size() > 0 ){for (Order order: orders){System.out.println(order);}}else {System.out.println("没有订单!");}}@Testpublic void testUpdateOrder(){OrderDao orderDao = new OrderDaoImpl();Order order = orderDao.findById(1);//       order.setUsername("ZZJJYY");
//if (order == null){System.out.println("恭喜,用户更新成功");}else {System.out.println("遗憾,用户更新失败");}}//插入@Testpublic void testAddOrder(){OrderDao orderDao = new OrderDaoImpl();Order order = new Order();order.setUsername("YUK");order.setDeliveryAddress("China");order.setOrderTime(new Date());order.setTelephone("123336333");int count = orderDao.insert(order);if (count > 0){System.out.println("恭喜,订单插入成功");}else {System.out.println("遗憾,订单插入失败");}}//删除@Testpublic void testDeleteOrderById(){OrderDao orderDao = new OrderDaoImpl();int count = orderDao.deleteById(2);if (count > 0){System.out.println("恭喜,订单删除成功");}else {System.out.println("遗憾,订单删除失败");}}//按id查询@Testpublic void testFindOrderById(){OrderDao orderDao = new OrderDaoImpl();Order order  = orderDao.findById(1);if (order== null){System.out.println("查询失败");}else {System.out.println("查询成功");System.out.println(order);}}@Testpublic void testFindLastOrder(){OrderDao orderDao = new OrderDaoImpl();Order order = orderDao.findLast();if (order== null){System.out.println("查询失败");}else {System.out.println("查询成功");System.out.println(order);}}
}

四、实现步骤

(八)控制层(XXXServlet)

在src里创建net.hw.shop.servlet包,在里面创建各种控制处理类。

1、登录处理类LoginServlet

package net.gongjing.shop.servlet;
/*** 功能:登录处理类* 作者:gongjing* 日期:2019年12月9日*/import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import net.gongjing.shop.bean.User;
import net.gongjing.shop.service.UserService;@WebServlet("/login")
public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 设置请求对象的字符编码request.setCharacterEncoding("utf-8");// 获取会话对象HttpSession session = request.getSession();// 获取用户名String username = request.getParameter("username");// 获取密码String password = request.getParameter("password");// 定义用户服务对象UserService userService = new UserService();// 执行登录方法,返回用户实体User user = userService.login(username, password);// 判断用户登录是否成功if (user != null) {// 设置session属性session.setMaxInactiveInterval(5 * 60);session.setAttribute("username", username);session.removeAttribute("loginMsg");// 根据用户权限跳转到不同页面if (user.getPopedom() == 0) {System.out.println("用户登录成功,进入后台管理!");response.sendRedirect(request.getContextPath() + "/backend/management.jsp");} else if (user.getPopedom() == 1) {System.out.println("用户登录成功,进入前台显示类别!");response.sendRedirect(request.getContextPath() + "/showCategory");}} else {System.out.println("用户名或密码错误,用户登录失败!");// 设置session属性loginMsgsession.setAttribute("loginMsg", "用户名或密码错误!");response.sendRedirect(request.getContextPath() + "/login.jsp");}}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
}

测试如下
在地址栏里localhost:8080/simonshop/之后输入login?username=admin&password=12345之后敲回车:


登录失败

2、注销处理类LogoutServlet

package net.gongjing.shop.servlet;
/*** 功能:注销处理类* 作者:龚敬* 日期:2019年12月9日*/import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 让session失效request.getSession().invalidate();// 重定向到登录页面response.sendRedirect(request.getContextPath() + "/login.jsp");System.out.println("用户注销成功!");}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
}
下面我们来进行测试。启动服务器,先要登录成功,然后再测试注销功能。

先以普通用户身份登录成功登录系统
login?username=gongjing&password=88888888


重启服务器,再测试一下:



此时,测试用户注销功能:


3、注册处理类RegisterServlet

package net.gongjing.shop.servlet;
/*** 功能:处理用户注册* 作者:gongjing* 日期:2019年12月9日*/import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Timestamp;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import net.gongjing.shop.bean.User;
import net.gongjing.shop.service.UserService;@WebServlet("/register")
public class RegisterServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 设置请求对象的字符编码request.setCharacterEncoding("utf-8");// 获取session对象HttpSession session = request.getSession();// 获取用户名String username = request.getParameter("username");// 获取密码String password = request.getParameter("password");// 获取电话号码String telephone = request.getParameter("telephone");// 设置注册时间(时间戳对象)Timestamp registerTime = new Timestamp(System.currentTimeMillis());// 设置用户为普通用户int popedom = 1;// 创建用户对象User user = new User();// 设置用户对象信息user.setUsername(username);user.setPassword(password);user.setTelephone(telephone);user.setRegisterTime(registerTime);user.setPopedom(popedom);// 创建UserService对象UserService userService = new UserService();// 调用UserService对象的添加用户方法int count = userService.addUser(user);// 判断是否注册成功if (count > 0) {// 设置session属性session.setAttribute("registerMsg", "恭喜,注册成功!");// 重定向到登录页面response.sendRedirect(request.getContextPath() + "/login.jsp");// 在控制台输出测试信息System.out.println("恭喜,注册成功,跳转到登录页面!");} else {// 设置session属性session.setAttribute("registerMsg", "遗憾,注册失败!");// 重定向到注册页面response.sendRedirect(request.getContextPath() + "/frontend/register.jsp");// 在控制台输出测试信息System.out.println("遗憾,注册失败,跳转到注册页面!");}}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
}

下面我们来进行测试。启动服务器,访问http://localhost:8080/simonshop/register?username=萌萌哒&password=55555&telephone=15896961234,敲回车,查看结果:



此时,我们去NaviCat查看用户表,看看是否插入了新的用户记录?

大家可以看到telephone字段长度为11,那么我们重启服务器再测试,让telephone的值超过11位,看看结果如何。



我们去服务器端控制台查看信息:

确实在控制台输出了“遗憾,注册失败,跳转到注册页面!”信息,但是还抛出了一个异常:com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column ‘telephone’ at row 1,显示方式不是我们喜欢的,当然问题出在模型层,大家去修改UserDaoImpl里的insert方法。
很简单,只需要将catch字句里的e.printStackTrace();改成System.err.println(“SQL异常:” + e.getMessage());:


4、显示类别处理类ShowCategoryServlet

package net.gongjing.shop.servlet;
/*** 功能:显示类别控制程序* 作者:gongjing* 日期:2019年12月9日*/import java.io.IOException;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import net.gongjing.shop.bean.Category;
import net.gongjing.shop.service.CategoryService;@WebServlet("/showCategory")
public class ShowCategoryServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 创建类别服务对象CategoryService categoryService = new CategoryService();// 获取全部商品类别List<Category> categories = categoryService.findAllCategories();// 获取session对象HttpSession session = request.getSession();// 把商品类别列表以属性的方式保存到session里session.setAttribute("categories", categories);// 重定向到显示商品类别页面(showCategory.jsp)response.sendRedirect(request.getContextPath() + "/frontend/showCategory.jsp");// 在服务器控制台输出测试信息for (Category category: categories) {System.out.println(category);}        }protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
}

下面我们来进行测试。
重启服务器,访问http://localhost:8080/simonshop/showCategory:


5、显示商品处理类ShowProductServlet

package net.gongjing.shop.servlet;
/*** 功能:显示商品列表的控制程序*     通过业务层访问后台数据,*     然后将数据返回给前台页面* 作者:gongjing* 日期:2019年12月9日*/import java.io.IOException;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import net.gongjing.shop.bean.Product;
import net.gongjing.shop.service.CategoryService;
import net.gongjing.shop.service.ProductService;@WebServlet("/showProduct")
public class ShowProductServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取类别标识符int categoryId = Integer.parseInt(request.getParameter("categoryId"));// 创建商品类别服务对象CategoryService categoryService = new CategoryService();// 由类别标识符获取类别名String categoryName = categoryService.findCategoryById(categoryId).getName();// 创建商品服务对象ProductService productService = new ProductService();// 获取指定商品类别的商品列表List<Product> products = productService.findProductsByCategoryId(categoryId);// 获取session对象HttpSession session = request.getSession();// 把商品列表对象以属性的方式保存到session里session.setAttribute("products", products);// 重定向到显示商品信息页面response.sendRedirect(request.getContextPath() + "/frontend/showProduct.jsp?categoryName=" + categoryName);// 在服务器端控制台输出测试信息for (int i = 0; i < products.size(); i++) {System.out.println(products.get(i));}}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
}

下面我们来进行测试。
重启服务器,访问http://localhost:8080/simonshop/showProduct?categoryId=1:


没有类别会报错

ps:数据库版本不同虽然也可以连接成功,但是控制台依旧会报错,这是jdbc驱动和当前数据库版本不匹配所造成的,解决方法就是去官网下载当前数据库版本所匹配的jdbc文件

修改之后的代码

package net.gongjing.shop.servlet;
/*** 功能:显示商品列表的控制程序*     通过业务层访问后台数据,*     然后将数据返回给前台页面* 作者:gongjing* 日期:2019年12月9日*/import java.io.IOException;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import net.gongjing.shop.bean.Product;
import net.gongjing.shop.service.CategoryService;
import net.gongjing.shop.service.ProductService;@WebServlet("/showProduct")
public class ShowProductServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取类别标识符int categoryId = Integer.parseInt(request.getParameter("categoryId"));// 创建商品类别服务对象CategoryService categoryService = new CategoryService();if (categoryService.findCategoryById(categoryId) != null) {// 由类别标识符获取类别名String categoryName = categoryService.findCategoryById(categoryId).getName();// 创建商品服务对象ProductService productService = new ProductService();// 获取指定商品类别的商品列表List<Product> products = productService.findProductsByCategoryId(categoryId);// 获取session对象HttpSession session = request.getSession();// 把商品列表对象以属性的方式保存到session里session.setAttribute("products", products);// 重定向到显示商品信息页面response.sendRedirect(request.getContextPath() + "/frontend/showProduct.jsp?categoryName=" + categoryName);// 在服务器端控制台输出测试信息for (int i = 0; i < products.size(); i++) {System.out.println(products.get(i));}} else {System.out.println("类别表里没有id为" + categoryId + "的记录!");}}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
}

完整servlet代码

四,实现步骤

(九)准备图片资源

在web目录里创建images目录,存放项目所需图片文件:

图片素材下载链接:https://pan.baidu.com/s/1XH4Z7iQ01uZCS1LEmADZAw
提取码:v7rx

(十)CSS样式文件

在web目录里常见css子目录,在里面创建main.css文件:

/* 样式 */
body {margin: 0px;text-align: center;background: url("../images/frontBack.jpg") no-repeat;background-size: 100%
}table {margin: 0 auto;font-size: 14px;color: #333333;border-width: 1px;border-color: khaki;border-collapse: collapse;
}table th {border-width: 1px;padding: 8px;border-style: solid;border-color: gainsboro;background-color: honeydew;
}table td {border-width: 1px;padding: 8px;border-style: solid;border-color: gainsboro;background-color: #ffffff;
}/*登录页面样式*/
.login {width: 400px;height: 340px;background-color: honeydew;border: solid 2px darkgrey;left: 50%;top: 50%;position: absolute;margin: -170px 0 0 -200px;
}.login .websiteTitle, .title {border: solid 1px floralwhite;
}/*注册页面样式*/
.register {width: 400px;height: 350px;background-color: honeydew;border: solid 2px darkgrey;left: 50%;top: 50%;position: absolute;margin: -175px 0 0 -200px;
}/*显示类别页面样式*/
.showCategory {width: 400px;height: 350px;background-color: honeydew;border: solid 2px darkgrey;left: 50%;top: 50%;position: absolute;margin: -150px 0 0 -200px;
}/*生成订单页面样式*/
.makeOrder {width: 400px;height: 400px;background-color: honeydew;border: solid 2px darkgrey;left: 50%;top: 50%;position: absolute;margin: -200px 0 0 -200px;
}/*显示订单页面样式*/
.showOrder {width: 400px;height: 400px;background-color: honeydew;border: solid 2px darkgrey;left: 50%;top: 50%;position: absolute;margin: -200px 0 0 -200px;
}

(十一)JavaScript脚本文件

在web目录里创建scripts子目录,在里面创建check.js文件:

/*** 检验登录表单** @returns {Boolean}*/
function checkLoginForm() {var username = document.getElementById("username");var password = document.getElementById("password");if (username.value == "") {alert("用户名不能为空!");username.focus();return false;}if (password.value == "") {alert("密码不能为空!");password.focus();return false;}return true;
}/*** 检验注册表单** @returns {Boolean}*/
function checkRegisterForm() {var username = document.getElementById("username");var password = document.getElementById("password");var telephone = document.getElementById("telephone");if (username.value == "") {alert("用户名不能为空!");username.focus();return false;}if (password.value == "") {alert("密码不能为空!");password.focus();return false;}var pattern = "/^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/";if (!pattern.exec(telephone)) {alert("非法手机号!");telephone.focus();return false;}return true;
}

(十二)添加JSTL的jar包

在WEB-INF\lib目录里添加支持jstl的jar包:
jar包下载地址:http://tomcat.apache.org/taglibs/standard/

(十三)展现层页面(XXX.jsp)

1、登录页面login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>用户登录</title><base href="${basePath}"><script src="scripts/check.js" type="text/javascript"></script><link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body><div class="login"><div class="websiteTitle"><h1>西蒙购物网</h1></div><div class="title"><h3>用户登录</h3></div><div class="main"><form id="frmLogin" action="login" method="post"><table><tr><td align="center">账号</td><td><input id="username" type="text" name="username"/></td></tr><tr><td align="center">密码</td><td><input id="password" type="password" name="password"/></td></tr><tr align="center"><td colspan="2"><input type="submit" value="登录" οnclick="return checkLoginForm();"/><input type="reset" value="重置"/></td></tr></table></form></div><div class="footer"><p>如果你不是本站用户,单击<a href="frontend/register.jsp">此处</a>注册。</p></div>
</div><c:if test="${registerMsg!=null}"><script type="text/javascript">alert("${registerMsg}")</script><c:remove var="registerMsg"/>
</c:if><c:if test="${loginMsg!=null}"><script type="text/javascript">alert("${loginMsg}")</script><c:remove var="loginMsg"/>
</c:if>
</body>
</html>

在web.xml文件里将login.jsp设置为首页文件:


重启服务器:

不输入用户名与密码,单击【登录】按钮:

输入用户名,但不输入密码,单击【登录】按钮:

输入管理员用户名与密码:admin,12345


重启服务器,再以普通用户登录:郑晓红,11111

重启服务器,输入错误的用户名或密码:李文丽,12340


单击【确定】按钮,返回登录页面:

2、注册页面register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>用户注册</title><base href="${basePath}"><link href="css/main.css" rel="stylesheet" type="text/css"/><script src="scripts/check.js" type="text/javascript"></script>
</head>
<body><div class="register"><div class="websiteTitle"><h1>西蒙购物网</h1></div><div class="title"><h3>用户注册</h3></div><div class="main"><form action="register" method="post"><table><tr><td>账号</td><td><input id="username" type="text" name="username"/></td></tr><tr><td>密码</td><td><input id="password" type="password" name="password"/></td></tr><tr><td align="center">电话</td><td><input id="telephone" type="text" name="telephone"/></td></tr><tr align="center"><td colspan="2"><input type="submit" value="注册" onclick="return checkRegisterForm();"/><input type="reset" value="重置"/></td></tr></table></form></div><div class="footer"><p><a href="login.jsp">切换到登录页面</a></p></div>
</div><c:if test="${registerMsg!=null}"><script type="text/javascript">alert("${registerMsg}")</script><c:set var="registerMsg" value=""/>
</c:if>
</body>
</html>

启动服务器:


什么也不输入,单击【注册】按钮:

输入用户名,单击【注册】按钮

输入用户名、密码和电话,单击【注册】按钮:

打开用户表,查看新添加的用户:

3、显示商品类别页面showCategory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>显示商品类别</title><base href="${basePath}"><link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body><div class="showCategory"><div class="websiteTitle"><h1>西蒙购物网</h1></div><div>登录用户:<span style="color: red;">${username}</span><c:forEach var="i" begin="1" end="5">             </c:forEach><a href="logout">注销</a></div><div class="title"><h3>商品类别</h3></div><div class="main"><table><tr><th>类别编号</th><th>商品类别</th></tr><c:forEach var="category" items="${categories}"><tr align='center'><td>${category.id}</td><td width="150"><a href="showProduct?categoryId=${category.id}">${category.name}</a></td></tr></c:forEach></table></div>
</div>
</body>
</html>

启动服务器,显示登录页面,输入普通用户:郑晓红,11111


单击【家用电器】超链接:

我们去服务器端控制台查看输出信息:

返回到刚才显示商品类别页面

单击【注销】超链接,返回登录页面:

4、显示购物车页面showCart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>显示购物车</title><base href="${basePath}">
</head>
<body>
<h3>${username}的购物车</h3>
<table><tr><th>商品编号</th><th>商品名称</th><th>销售价格</th><th>购买数量</th><th>合计金额</th><th>用户操作</th></tr><c:forEach var="shoppingItem" items="${shoppingTable}"><tr><td>${shoppingItem.id}</td><td>${shoppingItem.name}</td><td>¥${shoppingItem.price}</td><td>${shoppingItem.amount}</td><td>¥${shoppingItem.sum}</td><td><a href="operateCart?id=${shoppingItem.id}&operation=delete">删除</a></td></tr></c:forEach><tr><th>总金额</th><td></td><td></td><td></td><c:choose><c:when test="${totalPrice==null}"><th style="color: red">¥0.00</th></c:when><c:otherwise><th style="color: red">¥${totalPrice}</th></c:otherwise></c:choose><td></td></tr>
</table>
<hr width="800px">
<c:choose><c:when test="${totalPrice==null}"><a href="frontend/makeOrder.jsp?totalPrice=0.00">生成订单</a></c:when><c:otherwise><a href="frontend/makeOrder.jsp?totalPrice=${totalPrice}">生成订单</a></c:otherwise>
</c:choose>
<c:if test="${orderMsg!=null}"><script type="text/javascript">alert("${orderMsg}")</script><c:remove var="orderMsg"/>
</c:if>
</body>
</html>

这个页面要包含在显示商品页面里,因此没有导入CSS样式文件。
重启服务器,以普通用户登录后,访问http://localhost:8080/simonshop/frontend/showCart.jsp:

5、显示商品页面showProduct.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>显示商品信息</title><base href="${basePath}"><link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>西蒙购物网</h1>
<hr width="700px">
登录用户:<span style="color: red;">${username}</span>
<c:forEach var="i" begin="1" end="5">
</c:forEach>
<a href="logout">注销</a></td>
<hr width="700px">
欢迎选购【<span style="color: blue; font-weight: bold;">${categoryName}</span>】类商品
<hr width="700px">
<table border="0"><c:forEach varStatus="status" var="product" items="${products}"><c:if test="${status.count%5==0}"><tr></c:if><td><table border="0"><tr><img src="data:images/product${product.id}.jpg" width="60px" height="60px"></tr><tr><td><b>商品编号:</b></td><td>${product.id}</td></tr><tr><td><b>商品名称:</b></td><td>${product.name}</td></tr><tr><td><b>销售价格:</b></td><td>${product.price}</td></tr><tr><td><b>上架时间:</b></td><td><fmt:formatDate value="${product.addTime}" pattern="yyyy-MM-dd"/></td></tr><tr><td><b>用户操作:</b></td><td><a href="operateCart?id=${product.id}&operation=add">加入购物车</a></td></tr></table></td><c:if test="${status.count%4==0}"></tr></c:if></c:forEach>
</table>
<hr width="700px">
<a href="showCategory">返回商品类别页面</a>
<hr width="700px">
<jsp:include page="showCart.jsp"/>
</body>
</html>

启动服务器,显示登录页面,输入普通用户:郑晓红,11111

单击【家用电器】超链接:

有点小问题,类别名没有显示出来,页面跳转了,但是类别名没有传递成功。
修改ShowProductServlet,将类别名放在session里,而不是通过url传递参数。

重启服务器,登录成功后,选择【家用电器】类别:

下面测试加入购物车操作:

同一件商品可以多次加入购物车,也可以从购物车删除掉选购的商品。如果一件商品加入购物车的数量大于1,那么执行一次删除操作就是让购物车该商品数量减少1,直到减为0,即购物车里删除掉该商品。

6、生成订单页面makeOrder.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>生成订单</title><base href="${basePath}"><link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="makeOrder"><div class="websiteTitle"><h1>西蒙购物网</h1></div><div>登录用户:<span style="color: red;">${username}</span><c:forEach var="i" begin="1" end="5"></c:forEach><a href="logout">注销</a></div><div class="title"><h3>生成订单</h3></div><div class="main"><form action="makeOrder" method="post"><table><tr><td>用户名</td><td><input type="text" name="username" readonly="readonly"value="${username}"/></td></tr><tr><td>联系电话</td><td><input type="text" name="telephone"/></td></tr><tr><td>总金额</td><td><input type="text" name="totalPrice" readonly="readonly"value="${totalPrice}"/></td></tr><tr><td>送货地址</td><td><input type="text" name="deliveryAddress"/></td></tr><tr align="center"><td colspan="2"><input type="submit" value="生成订单"/> <inputtype="reset" value="重置"/></td></tr></table></form></div><div class="footer"><p><a href="showCategory">返回商品类别页面</a></p></div>
</div>
</body>
</html>

7、显示订单页面showOrder.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>显示订单</title><base href="${basePath}"><link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="showOrder"><div class="websiteTitle"><h1>西蒙购物网</h1></div><div>登录用户:<span style="color: red;">${username}</span><c:forEach var="i" begin="1" end="5">             </c:forEach><a href="logout">注销</a></div><div class="title"><h3>生成订单</h3></div><div class="main"><table border="1" cellspacing="0"><tr><th>订单编号</th><td>${lastOrder.id}</td></tr><tr><th>用户名</th><td>${lastOrder.username}</td></tr><tr><th>联系电话</th><td>${lastOrder.telephone}</td></tr><tr><th>总金额</th><td>${lastOrder.totalPrice}</td></tr><tr><th>送货地址</th><td>${lastOrder.deliveryAddress}</td></tr></table></div><div class="footer"><p><a href="pay" οnclick="alert('${lastOrder.username},支付成功!');">支付</a></p></div>
</div>
</body>
</html>

下面我们来测试生成订单与显示订单页面。
重启服务器,以普通用户登录,选择【家用电器】类商品,在显示商品页面,将一些商品加入购物车,查看购物车情况

单击【生成订单】超链接,跳转到【生成订单】页面

输入联系电话与送货地址:

单击【生成订单】按钮,跳转到【显示订单】页面:

单击【支付】按钮,提示支付成功

单击【确定】按钮,返回登录页面:

8、后台管理主页面management.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>西蒙购物网站后台管理</title><base href="${basePath}">
</head>
<frameset rows="30%,70%" cols="*"><frame src="backend/top.jsp" name="top_frame" scrolling="no"><frameset rows="*" cols="25%,75%"><frame src="backend/left.jsp" name="left_frame" scrolling="yes"><frame src="backend/main.jsp" name="main_frame" scrolling="yes"></frameset>
</frameset>
</html>

9、后台管理主页面左面板页面left.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>后台管理左面板</title><base href="${basePath}"><link rel="stylesheet" type="text/css"><script type="text/javascript">function show(id) {var obj = document.getElementById('c_' + id);if (obj.style.display == 'block') {obj.style.display = 'none';} else {obj.style.display = 'block';}}</script>
</head><body>
<table cellSpacing=0 cellPadding=0 width='100%' border=0><tbody><tr><td class=catemenu> <astyle='CURSOR: pointer' οnclick=show(1)><img src="data:images/folder.png">用户管理</a></td></tr><tbody id=c_1><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="showUser" target="main_frame">查看用户</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">添加用户</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">更新用户</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">删除用户</a></td></tr></tbody><tbody><tr><td class=catemenu> <astyle='CURSOR: pointer' οnclick=show(2)><img src="data:images/folder.png">类别管理</a></td></tr><tbody id=c_2 style='DISPLAY: none'><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">查看类别</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">添加类别</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">更新类别</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">删除类别</a></td></tr></tbody><tbody><tr><td class=catemenu> <astyle='CURSOR: pointer' οnclick=show(3)><img src="data:images/folder.png">商品管理</a></td></tr><tbody id=c_3 style='DISPLAY: none'><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">查看商品</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">添加商品</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">更新商品</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">删除商品</a></td></tr></tbody><tbody><tr><td class=catemenu> <astyle='CURSOR: pointer' οnclick=show(4)><img src="data:images/folder.png">订单管理</a></td></tr><tbody id=c_4 style='DISPLAY: none'><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">查看订单</a></td></tr><tr><td class=bar2 height=20>  <img src="data:images/file.png"> <a href="backend/todo.jsp" target="main_frame">删除订单</a></td></tr></tbody>
</table>
</body>
</html>

10、后台管理主页面顶面板页面top.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>后台管理顶面板</title><base href="${basePath}">
</head>
<body style="margin:0px">
<img src="data:images/title.png" width="100%" height="100%">
</body>
</html>

11、后台管理主页面主面板页面main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>后台管理主面板</title><base href="${basePath}">
</head>
<body>
<img src="data:images/mainBack.gif" width="100%" height="100%"/>
</body>
</html>

重启服务器,以管理员身份登录(admin:12345)进入后台管理页面:

12、查看用户页面showUser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head><title>显示用户信息</title><base href="${basePath}"><link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<hr>
<table width="90%" border="0px"><tr><td align="left">登录用户:<span style="color: red;">${username}</span></td><td align="right"><a href="user/logout" target="_parent">注销</a></td></tr>
</table>
<hr>
<h3>用户列表</h3>
<hr>
<table border="1" width="90%" cellspacing="0"><tr><th>编号</th><th>用户名</th><th>密码</th><th>电话</th><th>注册时间</th><th>权限</th></tr><c:forEach var="user" items="${users}"><tr align="center"><td>${user.id}</td><td>${user.username}</td><td>${user.password}</td><td>${user.telephone}</td><td><fmt:formatDate value="${user.registerTime}" pattern="yyyy-MM-dd hh:mm:ss"/></td><td><c:choose><c:when test="${user.popedom==0}">管理员</c:when><c:otherwise>普通用户</c:otherwise></c:choose></td></tr></c:forEach>
</table>
<hr>
</body>
</html>

重启服务器,以管理员身份登录,进入后台管理页面,查看用户:

13、待做页面todo.jsp


重启服务器,以管理员身份登录,单击【添加用户】:

五、实训总结

本项目采用MVC模式,视图层采用JSP页面(使用了核心标签库JSTL,2016年的没有采用核心标签库,采用纯粹的JSP脚本<% … %>,同学们可以做个对比),控制层采用Servlet(获取页面提交数据,连接后台数据库进行处理,根据处理结果进行页面跳转),模型层采用JDBC操作后台数据库(建议采用数据源方式获取数据库连接)。

后台管理只完成了用户管理的【查看用户】功能,其余的,类别管理、商品管理与订单管理,留待同学们自行完成,通过实战提高代码编写能力。

Java Web实训项目:西蒙购物园相关推荐

  1. Java Web实训项目:西蒙购物网(Simonshop)

    一.功能需求 1.只有注册用户成功登录之后才可查看商品类别,查看商品,选购商品,生成订单.查看订单. 2.只有管理员才有权限进入购物网后台管理,进行用户管理.类别管理.商品管理与订单管理. 二.设计思 ...

  2. Java Web实训项目:西蒙购物网(下)

    文章目录 四.实现步骤 (九)准备图片资源 (十)CSS样式文件 (十一)JavaScript脚本文件 (十二)添加JSTL的jar包 (十三)展现层页面(XXX.jsp) 1.登录页面login.j ...

  3. Java Web实训项目:西蒙购物网(中)

    文章目录 四.实现步骤 (八)控制层(XXXServlet) 1.登录处理类LoginServlet 2.注销处理类LogoutServlet 3.注册处理类RegisterServlet 4.显示类 ...

  4. Java Web实训项目:西蒙购物网(上)

    文章目录 一.功能需求 1.普通用户 2.管理员用户 二.设计思路 (一)采用MVC设计模式

  5. Java Web实训项目:西蒙购物网(2016)

    目录 一.功能需求 1.普通用户 2.管理员用户 二.设计思路

  6. java程序设计实训项目_Java程序设计教程与项目实训

    本书以现代教育理念为指导,在讲授方式上注意结合应用开发实例,注重培养学生理解面向对象程序设计思想,以提高分析问题和解决实际问题的能力.采用由浅入深.理论与实践相结合的教学思路,通过大量的实例阐述Jav ...

  7. java swing实训项目(图书管理系统)

    1.项目布局(供新手参考) 学校老师任务,因为我也是新手所以写的不是特别的好,所以可以提供参考. package GUI_Object.GUI;import GUI_Object.mysql.Data ...

  8. Java实训项目--小型书店管理系统(ssm框架)

    系列文章目录 MyBatis专栏: 一:Java实训项目–小型图书管理系统(ssm框架) 二:"spring与mybatis整合"考试题目测试与解析 三:"SSM框架整合 ...

  9. java 实训项目_实训方案(JavaWeb项目实训)-

    实训方案(JavaWeb项目实训)- 2012-2013学年第一学期 <Java Web项目开发实训>课程实施方案 课程名称(英文):Training of Java Web Projec ...

最新文章

  1. R语言ggplot2可视化:使用geom_smooth函数基于lm方法为每个分组的部分数据(subset data)拟合趋势关系曲线、对指定范围的数据拟合曲线
  2. 华为鸿蒙系统支持智慧多屏吗,搭载鸿蒙OS!华为宣布企业智慧屏:多屏协同、底座带轮子...
  3. 浅谈 CTR 预估模型发展史
  4. 【数据结构与算法】【算法思想】Dijkstra算法
  5. 《设计模式详解》行为型模式 - 中介者模式
  6. 教程-Delphi7 自带控件安装对应表
  7. Python爬虫编程思想(92):项目实战:抓取京东图书评价
  8. 【硬刚大数据之面试篇】2021年从零到大数据专家面试篇之ClickHouse篇
  9. 国开大学计算机实操,国开大学计算机实操答案一 .pdf
  10. win10电脑用命令行关机
  11. MySQL创建数据库 easyShopping,包括area表、goods表、customer表、orders表、ordersdetall表、test表
  12. 基于SSM实现的艺术品鉴定管理系统+App
  13. Nagios监控服务器与客户端的安装
  14. AURIX TC397 CAN MCMCAN
  15. 【计算机基础】-2万字总结《计算机速成课》全集笔记
  16. 点到线段直线的距离, 直线与直线的关系 直线与线段的关系
  17. 北美独立战争: 美国人编出来的神话
  18. 1. 英文SCI论文引言写作四步走模型学习笔记
  19. 新静安二手房房价依旧上涨
  20. 几个简单实用的vbs命令

热门文章

  1. eja变送器故障代码al01_eja变送器表头常见错误代码代表含义你造吗?
  2. Nginx转发https
  3. 学物理难还是学计算机难,数学专业,物理专业和计算机专业怎么选择?哪一个未来前景比较好呢?...
  4. Python用 selenium 模块控制Firefox浏览器
  5. 合格前端系列第十一弹-初探 Nuxt.js 秘密花园
  6. DIBL vs. 源漏穿通 vs.
  7. HTML中bgcolor与background-color的区别
  8. 视频宽高比和分辨率的关系(转)
  9. 易优cms忘记网站后台密码如何获取的方法 Eyoucms快速入门
  10. 金融风控特征工程小结