一、功能需求
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
(三)创建实体类
在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;
}
@Override
public 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;
}
@Override
public 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;
}
@Override
public 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;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", username='" + username + '\'' +
", telephone='" + telephone + '\'' +
", totalPrice=" + totalPrice +
", deliveryAddress='" + deliveryAddress + '\'' +
", orderTime=" + orderTime +
'}';
}
}
(四)创建数据库工具类ConnectionManager
1、在web\WEB-INF目录下创建lib子目录,添加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 {
/**
* 插入用户
*/
@Override
public 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;
}
/**
* 删除用户记录
*/
@Override
public 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;
}
/**
* 更新用户
*/
@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 = ?, 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;
}
/**
* 按标识符查询用户
*/
@Override
public 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;
}
@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 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;
}
@Override
public 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;
}
/**
* 登录方法
*/
@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 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 {
@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("遗憾,登录失败!");
}
}
@Test
public 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);
}
//插入
@Test
public 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("遗憾,用户插入失败");
}
}
//删除
@Test
public void testDeleteById(){
UserDao userDao = new UserDaoImpl();
int count = userDao.deleteById(2);
if (count > 0){
System.out.println("恭喜,用户删除成功");
}else {
System.out.println("遗憾,用户删除失败");
}
}
//按用户名查询
@Test
public 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("查询失败");
}
}
//查询全部
@Test
public void testFindAll(){
UserDao userDao = new UserDaoImpl();
List<User> users = userDao.findAll();
if (!users.isEmpty()){
System.out.println("查询成功");
}else {
System.out.println("查询失败");
}
}
@Test
public 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 {
/**
* 插入类别
*/
@Override
public 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;
}
/**
* 删除类别
*/
@Override
public 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;
}
/**
* 更新类别
*/
@Override
public 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;
}
/**
* 按标识符查询类别
*/
@Override
public 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;
}
/**
* 查询全部类别
*/
@Override
public 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 {
@Test
public 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("没有商品类别!");
}
}
@Test
public 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);
}
}
@Test
public 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("更新失败");
}
}
@Test
public void testDelete(){
CategoryDao categoryDao = new CategoryDaoImpl();
int count = categoryDao.deleteById(2);
if (count > 0){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
}
@Test
public 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 {
/**
* 插入商品
*/
@Override
public 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;
}
/**
* 删除商品
*/
@Override
public 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;
}
/**
* 更新商品
*/
@Override
public 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;
}
/**
* 按标识符查找商品
*/
@Override
public 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;
}
/**
* 按类别查询商品
*/
@Override
public 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;
}
/**
* 查询全部商品
*/
@Override
public 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 {
@Test
public 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("遗憾,用户更新失败");
}
}
//按类别
@Test
public 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 + "]不存在!");
}
;
}
@Test
public 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("没有商品类别!");
}
}
@Test
public 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("插入失败");
}
}
@Test
public 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);
}
}
@Test
public 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 {
/**
* 插入订单
*/
@Override
public 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;
}
/**
* 删除订单
*/
@Override
public 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;
}
/**
* 更新订单
*/
@Override
public 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;
}
/**
* 查询最后一个订单
*/
@Override
public 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;
}
/**
* 按标识符查询订单
*/
@Override
public 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;
}
/**
* 查询全部订单
*/
@Override
public 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 {
@Test
public 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("没有订单!");
}
}
@Test
public 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("遗憾,用户更新失败");
}
}
//插入
@Test
public 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("遗憾,订单插入失败");
}
}
//删除
@Test
public 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查询
@Test
public 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);
}
}
@Test
public 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 {
@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("遗憾登陆失败");
}
}
@Test
public 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("遗憾,用户更新失败");
}
}
//插入
@Test
public 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("遗憾,用户插入失败");
}
}
//删除
@Test
public void testDeleteUserById(){
UserDao userDao = new UserDaoImpl();
int count = userDao.deleteById(2);
if (count > 0){
System.out.println("恭喜,用户删除成功");
}else {
System.out.println("遗憾,用户删除失败");
}
}
//按用户名查询
@Test
public 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("查询失败");
}
}
//查询全部
@Test
public 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("查询失败");
}
}
@Test
public 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 {
@Test
public 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("插入失败");
}
}
@Test
public void testDeleteCategoryById(){
CategoryDao categoryDao = new CategoryDaoImpl();
int count = categoryDao.deleteById(2);
if (count > 0){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
}
@Test
public 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("更新失败");
}
}
@Test
public 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);
}
@Test
public 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 {
@Test
public void testUpdateProduct(){
ProductDao productDao = new ProductDaoImpl();
Product product = productDao.findById(2);
//product.setName("Yss");
if (product == null){
System.out.println("恭喜,用户更新成功");
}else {
System.out.println("遗憾,用户更新失败");
}
}
//按类别
@Test
public 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 + "]不存在");
}
;
}
@Test
public 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("没有商品类别!");
}
}
@Test
public 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("插入失败");
}
}
@Test
public 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);
}
@Test
public 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 {
@Test
public 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("没有订单!");
}
}
@Test
public void testUpdateOrder(){
OrderDao orderDao = new OrderDaoImpl();
Order order = orderDao.findById(1);
// order.setUsername("ZZJJYY");
//
if (order == null){
System.out.println("恭喜,用户更新成功");
}else {
System.out.println("遗憾,用户更新失败");
}
}
//插入
@Test
public 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("遗憾,订单插入失败");
}
}
//删除
@Test
public void testDeleteOrderById(){
OrderDao orderDao = new OrderDaoImpl();
int count = orderDao.deleteById(2);
if (count > 0){
System.out.println("恭喜,订单删除成功");
}else {
System.out.println("遗憾,订单删除失败");
}
}
//按id查询
@Test
public 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);
}
}
@Test
public 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属性loginMsg
session.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);
}
}
四,实现步骤
(九)准备图片资源
在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="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="生成订单"/> <input
type="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> <a
style='CURSOR: pointer' οnclick=show(1)><img src="images/folder.png">用户管理</a>
</td>
</tr>
<tbody id=c_1>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="showUser" target="main_frame">查看用户</a></td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">添加用户</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">更新用户</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">删除用户</a>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class=catemenu> <a
style='CURSOR: pointer' οnclick=show(2)><img src="images/folder.png">
类别管理</a></td>
</tr>
<tbody id=c_2 style='DISPLAY: none'>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">查看类别</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">添加类别</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">更新类别</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">删除类别</a>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class=catemenu> <a
style='CURSOR: pointer' οnclick=show(3)><img src="images/folder.png">
商品管理</a></td>
</tr>
<tbody id=c_3 style='DISPLAY: none'>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">查看商品</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">添加商品</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">更新商品</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">删除商品</a>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class=catemenu> <a
style='CURSOR: pointer' οnclick=show(4)><img src="images/folder.png">
订单管理</a></td>
</tr>
<tbody id=c_4 style='DISPLAY: none'>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="backend/todo.jsp" target="main_frame">查看订单</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="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="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="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操作后台数据库(建议采用数据源方式获取数据库连接)。
后台管理只完成了用户管理的【查看用户】功能,其余的,类别管理、商品管理与订单管理,留待同学们自行完成,通过实战提高代码编写能力。