文章目录
本项目采用MVC模式进行开发,整合JSP+Servlet+DB(DAO).
一.功能需求
1.普通用户
只有注册用户登录成功之后才可查看商品类别,查看商品,选购商品、生成订单、查看订单.
2.管理员用户
只有管理员才有权限进入购物网后台管理,进行用户管理
二.设计思路
(一)采用MVC设计模式
分层架构:展现层(JSP)<——>控制层(Servlet)<——>业务层(Service)<——>模型层(Dao)<——>数据库(DB)
(二)前台购物
1.购物流程
登录-------显示商品类别------显示某类商品信息------查看购物车------生成订单------支付
2.用户注册
系统只有一个管理员,在注册页面注册的都是普通用户.
(三)后台管理
1.用户管理
用户的增删改查
2.类别管理
商品类别的增删改查
3.商品管理
商品的增删改查
4.订单管理
订单的查看与删除
三.实现步骤
(一)创建数据表
创建MySQL数据库shop,包含四张表:用户表(t_user)、类别表(t_category)、商品表(t_product)和订单表(t_order).
(二)创建Web项目
1.创建Web项目shop
2.在项目结构窗口设置Artifacts名词:shop
3.配置服务器(Server)
4.设置部署(Deployment)
(三)创建实体类
1.用户实体类User
package net.ysy.shop.bean;
import java.util.Date;
public class User {
/**
* 用户表示符
*/
private int id;
/**
*用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 电话号码
*/
private String telephone;
/**
* 注册时间
*/
private Date registerTime;
/**
* 权限(0:管理员;1:普通用户)
*/
private int popedom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
public int getPopedom() {
return popedom;
}
public void setPopedom(int popedom) {
this.popedom = popedom;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
", popedom=" + popedom +
'}';
}
}
2.类别实体类Category
package net.ysy.shop.bean;
public class Category {
/**
* 类别标识符
*/
private int id;
/**
* 类别名称
*/
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
3.商品实体类Product
package net.ysy.shop.bean;
import java.util.Date;
public class Product {
/**
* 商品标识符
*/
private int id;
/**
* 商品名称
*/
private String name;
/**
* 商品上架时间
*/
private Date addTime;
/**
* 商品所属类别标识符
*/
private int categoryId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", addTime=" + addTime +
", categoryId=" + categoryId +
'}';
}
}
4.订单实体类Order
package net.ysy.shop.bean;
import javafx.scene.chart.PieChart;
import javax.xml.crypto.Data;
public class Order {
/**
* 订单标识符
*/
private int id;
/**
* 用户名
*/
private String username;
/**
* 联系电话
*/
private String telephone;
/**
* 订单总金额
*/
private String totalPric;
/**
* 送货地址
*/
private String deliveryAddrrss;
/**
* 下单时间
*/
private Data orderTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getTotalPric() {
return totalPric;
}
public void setTotalPric(String totalPric) {
this.totalPric = totalPric;
}
public String getDeliveryAddrrss() {
return deliveryAddrrss;
}
public void setDeliveryAddrrss(String deliveryAddrrss) {
this.deliveryAddrrss = deliveryAddrrss;
}
public Data getOrderTime() {
return orderTime;
}
public void setOrderTime(Data orderTime) {
this.orderTime = orderTime;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", username='" + username + '\'' +
", telephone='" + telephone + '\'' +
", totalPric='" + totalPric + '\'' +
", deliveryAddrrss='" + deliveryAddrrss + '\'' +
", orderTime=" + orderTime +
'}';
}
}
(四)创建数据工具类ConnectionManager
1.在web\WEB-INF目录下创建lib子目录,添加MySQL驱动程序jar包
2.在src下创建net.ysy.shop.dbutil包,在里面加ConnectionManager类
package net.ysy.shop.dbutil;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
/**
* 数据库驱动程序
*/
private static final String DRIVER="com.mysql.jdbc.Driver";
/**
* 数据库统一标识符
*/
private static final String URL="jdbc:mysql://localhost:3306/simonshop";
/**
* 数据库用户名
*/
private static final String USERNAME="root";
/**
* 数据库密码
*/
private static final String PASSWORD="pASSWORD";
/**
* 私有构造方法,拒绝实例化
*/
private ConnectionManager(){
}
/**
* 获取数据库连接静态方法
* @return 数据库连接对象
*/
public static Connection getconnection(){
//定义数据库连接
Connection conn=null;
try{
//安装驱动程序
Class.forName(DRIVER);
//获取数据库连接
conn= DriverManager.getConnection(URL
+"?useUnicode=true&charaterEncoding=UTF8",USERNAME,PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
//返回数据库连接
return conn;
}
/**
* 关闭数据库连接静态方法
* @param conn
*/
public static void closeConnection(Connection conn){
//判断数据库连接是否为空
if (conn !=null){
//判断数据库连接是否关闭
try{
if (!conn.isClosed()){
//关闭数据库
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 测试数据库连接是否成功
*/
public static void main(String[] args) {
//获取数据库连接
Connection conn=getconnection();
//判断是否连接成功
if (conn !=null){
JOptionPane.showMessageDialog(null,"恭喜连接成功!");
}else {
JOptionPane.showMessageDialog(null,"遗憾,数据库连接失败!");
}
}
}
3.运行程序,查看结果
建议采用数据库连接池,效率更高,建议使用数据源方式获取数据连接.
(五)数据访问接口(XXXDao)
1.用户数据访问接口UserDao
package net.ysy.shop.dao;
import net.ysy.shop.bean.User;
import java.sql.SQLException;
import java.util.List;
public interface UserDao {
//插入用户
int insert(User user) throws SQLException;
//按标识符删除用户
int deleteById(int id);
//更新用户
int update(User user);
//按标识符查询用户
User findById(int id);
//按用户名查询用户
List<User> findByUsername(String username);
//查询全部用户
List<User> findAll();
//用户登录
User login(String username,String password);
}
2.类别数据访问接口CategoryDao
package net.ysy.shop.dao;
import net.ysy.shop.bean.Category;
import java.util.List;
public interface CategoryDao {
//插入类别
int insert(Category category);
//按标识符删除类别
int deletById(int id);
//更新类别
int update(Category category);
//按标识符查询类别
Category findById(int id);
//查询全部类别
List<Category> findAll();
}
3.商品数据访问接口ProductDao
package net.ysy.shop.dao;
import net.ysy.shop.bean.Product;
import java.util.List;
public interface ProductDao {
//插入商品
int insert(Product product);
//按标识符删除商品
int deletById(int id);
//更新商品
int update(Product product);
//按标识符查询商品
Product findById(int id);
//按类别查询商品
List<Product> findByCategoryId(int categoryId);
//查询全部商品
List<Product> findAll();
}
4.订单数据访问接口OrderDao
package net.ysy.shop.dao;
import net.ysy.shop.bean.Order;
import java.util.List;
public interface OrderDao {
//插入订单
int insert(Order order);
//按标识符删除订单
int deleteById(int id);
//更新订单
int update(Order order);
//按标识符查询订单
Order findById(int id);
//查询最后一个订单
Order findLast();
//查询全部订单
List<Order> findAll();
}
(六)数据访问接口实现类(XXXDaoImpl)
1.用户数据访问接口实现类UserDaoImpl
package net.ysy.shop.dao.impl;
import net.ysy.shop.bean.User;
import net.ysy.shop.dao.UserDao;
import net.ysy.shop.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements UserDao {
/**
* 插入用户
*/
@Override
public int insert(User user) throws SQLException {
//定义插入记录数
int count=0;
//获得数据库连接
Connection conn= ConnectionManager.getconnection();
//定义SQL字符串
String strSQL="INSERT INTO t_user(username,password,telephone,register_time,popedom)"+"VALUES(?,?,?,?,?)";
try {
//创建预备语句对象
PreparedStatement pstm=conn.prepareStatement(strSQL);
//设置占位符的值
pstm.setString(1,user.getUsername());
pstm.setString(2,user.getPassword());
pstm.setString(3,user.getTelephone());
pstm.setTimestamp(4,new Timestamp(user.getRegisterTime().getTime()));
pstm.setInt(5,user.getPopedom());
//执行更新操作,插入新记录
count=pstm.executeUpdate();
//关闭预备语句
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回插入记录数
return count;
}
@Override
public int deleteById(int id) {
//定义删除距离数
int count=0;
//获得数据库连接
Connection conn=ConnectionManager.getconnection();
//定义SQL字符串
String strSQL="DELETE FROM t_user WHERE id =? ";
try{
//创建预备语句
PreparedStatement pstm=conn.prepareStatement(strSQL);
//设置占位符的值
pstm.setInt(1,id);
//执行更新操作,删除记录
count=pstm.executeUpdate();
//关闭预备语句对象
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回删除距离数
return count;
}
/**
* 更新用户
*/
@Override
public int update(User user) {
//定义记录数
int count=0;
//获取数据库连接
Connection conn=ConnectionManager.getconnection();
//定义SQL字符串
String strSQL="UPDATE t_user SET username = ?,password = ?,telephone = ?,"
+"register_time = ? ,popem = ? WHERE id= ?";
try{
//创建预备语句对象
PreparedStatement pstm=conn.prepareStatement(strSQL);
//设置占位符的值
pstm.setString(1,user.getUsername());
pstm.setString(2,user.getPassword());
pstm.setString(3,user.getTelephone());
pstm.setTimestamp(4,new Timestamp(user.getRegisterTime().getTime()));
pstm.setInt(5,user.getPopedom());
pstm.setInt(6,user.getId());
//执行更新操作,更新记录
count=pstm.executeUpdate();
//关闭预备语句对象
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回更新记录数
return count;
}
@Override
public User findById(int id) {
//声明用户
User user=null;
//获取数据库连接对象
Connection conn=ConnectionManager.getconnection();
//定义字符串
String strSQL=" SELECT * FROM t_user WHERE id =?";
try{
//创建预备语句对象
PreparedStatement pstm=conn.prepareStatement(strSQL);
//设置占位符
pstm.setInt(1,id);
//执行SQL查询,返回结果集
ResultSet rs=pstm.executeQuery();
//判断结果集是否有记录
if (rs.next()){
//实例化用户
user=new User();
//利用当前记录字段去设置商品类别属性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
return user;
}
@Override
public List<User> findByUsername(String username) {
//声明用户列表
List<User> users=new ArrayList<User>();
//获取数据库连接对象
Connection conn=ConnectionManager.getconnection();
//定义SQL字符串
String strSQL="SELECT * FROM t_user WHERE username =? ";
try{
//创建预备语句
PreparedStatement pstm=conn.prepareStatement(strSQL);
//设置占位符的值
pstm.setString(1,username);
//执行SQl查询,返回结果集
ResultSet rs=pstm.executeQuery();
//遍历结果集
while (rs.next()){
//创建类别实体类
User user=new User();
//设置实体属性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
//将实体类添加到用户列表
users.add(user);
}
//关闭结果集
rs.close();
//关闭语句对象
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
return users;
}
@Override
public List<User> findAll() {
//声明用户列表
List<User> users=new ArrayList<>();
//获取数据库连接对象
Connection conn=ConnectionManager.getconnection();
//定义SQL字符串
String strSQL="SELECT * FROM t_user";
try{
//创建预备语句
Statement stmt=conn.createStatement();
//执行SQL,返回结果集
ResultSet rs=stmt.executeQuery(strSQL);
while (rs.next()){
//设置实体属性
User user=new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
//将实体类添加到用户列表
users.add(user);
}
//关闭结果集
rs.close();
//关闭语句对象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭数据库连接
ConnectionManager.closeConnection(conn);
}
//返回用户列表
return users;
}
/**
* 登录方法
* @param username
* @param password
* @return
*/
@Override
public User login(String username, String password) {
//定义用户对象
User user=null;
//获取数据库连接
Connection conn=ConnectionManager.getconnection();
//定义SQL字符
String strSQL="SELECT * FROM t_user WHERE username = ? AND password = ?";
try{
//创建预备语句
PreparedStatement pstm=conn.prepareStatement(strSQL);
//设置占位符的值
pstm.setString(1,username);
pstm.setString(2,password);
//执行查询,返回结果集
ResultSet rs=pstm.executeQuery();
//判断结果集是否有记录
if (rs.next()){
//实例化对象
user=new User();
//用户记录设置用户属性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getDate("register_time"));
user.setPopedom(rs.getInt("popedom"));
}
//关闭结果集
rs.close();
//关闭预备语句
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭数据库连接
ConnectionManager.closeConnection(conn);
}
//返回用户对象
return user;
}
}
我们需要对用户数据访问接口实现类的各个方法进行单元测试,采用JUnit来进行单元测试.
在项目根目录创建一个test文件夹,然后在项目结构窗口里将标记为"Tests",这样文件夹颜色将变为green.
在test文件夹里面创建net.ysy.shop.dao.impl包,在里面创建测试类TestUserDaoImpl
(1)编写测试登录方法testLogin()
将光标定位到@Test注解符,按组合键Alt+Enter:
package net.ysy.shop.dao.impl;
import net.ysy.shop.bean.User;
import net.ysy.shop.dao.UserDao;
import org.junit.Test;
public class TestUserDaoImpl {
@Test
public void testLogin(){
String username,password;
username="admin";
password="12345";
//父类接口指向子类对象
UserDao userDao=new UserDaoImpl();
//调用登录用户数据访问对象的登录方法
User user=userDao.login(username,password);
//判断用户是否登录成功
if (user !=null){
System.out.println("恭喜,登录成功!");
}else {
System.out.println("遗憾,登录失败!");
}
}
}
修改登录密码,在进行测试,看结构如何:
将用户[涂文艳]的密码改为"123456",电话改为"15883723523",涂文艳的用户id是4,进行测试.
实现删除用户方法,寻找用户id,进行删除.
2.类别数据访问接口实现类CategoryDaoImpl
package net.ysy.shop.dao.impl;
import net.ysy.shop.bean.Category;
import net.ysy.shop.dao.CategoryDao;
import net.ysy.shop.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
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 SET name = ? WHERE id = ? ";
try{
//创建预备语句
PreparedStatement pstm=conn.prepareStatement(strSQL);
//设置占位符的值
pstm.setString(1,category.getName());
pstm.setString(2,category.getName());
//执行更新操作,更新记录
count=pstm.executeUpdate();
//关闭预备语句对象
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回更新记录数
return count;
}
/**
* 按标识符查询类别
* @param id
* @return
*/
@Override
public int deletById(int id) {
//定义删除记录数
int count=0;
//获取数据库连接
Connection conn=ConnectionManager.getconnection();
//定义SQL字符串
String strSQL="DELETE FROM t_category WHERE id =? ";
try{
//创建预备语句对象
PreparedStatement pstm=conn.prepareStatement(strSQL);
//设置占位符的值
pstm.setInt(1,id);
//执行更新操作,删除记录
count=pstm.executeUpdate();
//关闭预备语句对象
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回记录删除数
return count;
}
/**
* 定义更新记录数
* @param category
* @return
*/
@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 pstm=conn.prepareStatement(strSQL);
//设置占位符的值
pstm.setString(1,category.getName());
pstm.setString(2,category.getId());
//执行更新操作,更新记录
count=pstm.executeUpdate();
//关闭预备语句操作
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭数据库
ConnectionManager.closeConnection(conn);
}
//返回更新记录数
return count;
}
/**
* 按标识符查找类别
* @param id
* @return
*/
@Override
public Category findById(int id) {
//声明商品类别
Category category=null;
//获取数据库连接
Connection conn=ConnectionManager.getconnection();
//定义SQL字符串
String strSQL="SELECT * FROM t_category WHERE id = ?";
try{
//创建预备语句
PreparedStatement pstm=conn.prepareStatement(strSQL);
//设置占位符的值
pstm.setInt(1,id);
//执行SQL查询,返回结果集
ResultSet rs=pstm.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;
}
/**
* 查询全部类别
* @return
*/
@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;
}
}
创建测试类TestCategoryDaoImpl,编写测试方法testFindAll():
如果数据库中没有商品,判断集合categories是否为空,可以有两种处理方式:
categories.size()>0
!categories.isEmpty()
创建测试类TestCategoryDaoImpl,编写测试方法testFindById():
3.商品数据访问接口实现类ProductDaoImpl``
package net.ysy.shop.dao.impl;
import net.ysy.shop.bean.Product;
import net.ysy.shop.dao.ProductDao;
import net.ysy.shop.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ProductDaoImpl implements ProductDao {
/**
* 插入商品
* @param product
* @return
*/
@Override
public int insert(Product product) {
//定义插入记录数
int count=0;
//获取数据库连接
Connection conn= ConnectionManager.getconnection();
//定义SQL字符串
String strSQL="INSTER 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;
}
/**
* 删除商品
* @param id
* @return
*/
@Override
public int deletById(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;
}
/**
* 删除商品
* @param product
* @return
*/
@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());
//执行更新操作,插入新记录
count=pstmt.executeUpdate();
//关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
//返回更新记录数
return count;
}
/**
* 按标识符查找商品
* @param id
* @return
*/
@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;
}
/**
* 按类别查询商品
* @param categoryId
* @return
*/
@Override
public List<Product> findByCategoryId(int categoryId) {
//定义商品列表
List<Product> products=new ArrayList<>();
//获取数据库连接
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()){
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;
}
}
创建测试类TestProductDaoImpl,编写测试方法testFindCategory():
4.订单数据访问接口实现类OrderDaoImpl
package net.ysy.shop.dao.impl;
import net.ysy.shop.bean.Order;
import net.ysy.shop.dao.OrderDao;
import net.ysy.shop.dbutil.ConnectionManager;
import javax.xml.crypto.Data;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class OrderDaoImpl implements OrderDao {
@Override
public int insert(Order order) {
//定义删除记录数
int count =0;
//获取数据库连接
Connection conn= ConnectionManager.getconnection();
//定义SQL字符串
String strSQL="INSERT INTO FROM t_order (username,telephone,total_price,delivery_address,order_time)";
try{
//创建预备语句
PreparedStatement pstmt=conn.prepareStatement(strSQL);
//设置占位符
pstmt.setString(1,order.getUsername());
pstmt.setString(2,order.getTelephone());
pstmt.setDouble(3, Double.parseDouble(order.getTotalPric()));
pstmt.setString(4,order.getDeliveryAddrrss());
//pstmt.setTimestamp(5,new Timestamp(order.getOrderTime().getTime()));
//执行更新记录操作
count=pstmt.executeUpdate();
//关闭创建预备语句
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
return count;
}
/**
* 删除订单
* @param id
* @return
*/
@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();
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回记录数
return count;
}
/**
* 更新订单
* @param order
* @return
*/
@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, Double.parseDouble(order.getTotalPric()));
pstmt.setString(4,order.getDeliveryAddrrss());
// pstmt.setTimestamp(5, new Timestamp(order.getOrderTime().getTime()));
pstmt.setInt(5, order.getId());
// 执行更新操作,更新记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭数据库连接
ConnectionManager.closeConnection(conn);
}
//返回插入记录数
return count;
}
@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.setDeliveryAddrrss(rs.getString("delivery_address"));
order.setOrderTime((Data) rs.getTimestamp("order_time"));
}}catch (SQLException e){
e.printStackTrace();
}finally {
ConnectionManager.closeConnection(conn);
}
//返回订单
return order;
}
@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.setTotalPric(String.valueOf(rs.getDouble("total_price")));
order.setDeliveryAddrrss(rs.getString("delivery_address"));
order.setOrderTime((Data) rs.getTimestamp("order_time"));
}
//关闭结果集
rs.close();
//关闭语句对象
stmt.close();
} 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.setDeliveryAddrrss(rs.getString("delivery_address"));
// order.setOrderTime((Data) rs.getTimestamp("order_time"));
// 将实体添加到订单列表
orders.add(order);
}
//关闭结果集
rs.close();
//关闭语句对象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭数据库连接
ConnectionManager.closeConnection(conn);
}
//返回用户列表
return orders;
}
}
编写测试类TestOrderDaoImpl,编写测试testFindAll())方法:
(七)数据访问接口实现类(XXXService)
在src里面创建net.ysy.shop.service包,在里面创建四个服务类:UserService、CategoryService、ProductService、OrderService.
1.用户服务类UserService
package net.ysy.shop.service;
import net.ysy.shop.bean.User;
import net.ysy.shop.dao.UserDao;
import net.ysy.shop.dao.impl.UserDaoImpl;
import java.sql.SQLException;
import java.util.List;
/**
* 功能:用户服务类
*/
public class UserService {
/**
* 声明用户访问对象
*/
private UserDao userDao=new UserDaoImpl();
public int addUser(User user) throws SQLException {
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> findUserByUsername(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);
}
}
2.类别服务类CategoryService
package net.ysy.shop.service;
import net.ysy.shop.bean.Category;
import net.ysy.shop.dao.CategoryDao;
import net.ysy.shop.dao.impl.CategoryDaoImpl;
import java.util.List;
/**
* 类别服务功能
*/
public class CategoryService {
/**
* 声明类别数据访问对象
*/
private CategoryDao categoryDao=new CategoryDaoImpl();
public int addCategory(Category category){
return categoryDao.insert(category);
}
public int deleteCategoryById(int id){
return categoryDao.deletById(id);
}
public int updateCategpry(Category category){
return categoryDao.update(category);
}
public Category findCategoryById(int id){
return categoryDao.findById(id);
}
public List<Category> findAllCategories(){
return categoryDao.findAll();
}
}
3.商品服务类ProductService
package net.ysy.shop.service;
import net.ysy.shop.bean.Product;
import net.ysy.shop.dao.ProductDao;
import net.ysy.shop.dao.impl.ProductDaoImpl;
import java.util.List;
public class ProductService {
/**
* 声明商品数据访问对象
*/
private ProductDao productDao=new ProductDaoImpl();
public int addProduct(Product product){
return productDao.insert(product);
}
public int deleteProduct(Product product){
return productDao.update(product);
}
public Product findProductById(int id){
return productDao.findById(id);
}
public List<Product> findProductByCategoryId(int category){
return productDao.findByCategoryId(category);
}
public List<Product> findAllProducts(){
return productDao.findAll();
}
}
4.订单服务类OrderService
package net.ysy.shop.service;
import net.ysy.shop.bean.Order;
import net.ysy.shop.dao.OrderDao;
import net.ysy.shop.dao.impl.OrderDaoImpl;
import java.util.List;
/**
* 订单服务类
*/
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();
}
}
模型层的工作告一个段落,现在弄控制层.
四、实现步骤
(八) 控制层(XXXServlet)
在src里创建net.ysy.shop.servlet包,在里面创建各种控制处理类.
1、登录处理类LoginServlet
package net.ysy.shop.servlet;
import net.ysy.shop.bean.User;
import net.ysy.shop.service.UserService;
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 java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID=1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
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");
}
}
}
在地址栏里输入敲回车:
我们管理员的用户用户名与密码登录,缺数跳转到后台管理页面/backend/management.jsp,当然该页面尚未编写,所以报404错误,我们去看一下服务器的控制台,结果如下:
我们再来测试:
我们去看一下服务器的控制台,结果如下:
我们再来测试:
我们去看一下服务器的控制台,j结果如下:
2、注销处理类LogoutServlet
package net.ysy.shop.servlet;
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 java.io.IOException;
@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);
}
}
下面我们来进行测试,启动服务器,先要登录成功,然后在测试注销功能.
此时,测试用户注销功能:
我们再去服务器控制台查看信息:
3、注册处理类RegisterServlet
package net.ysy.shop.servlet;
import net.ysy.shop.bean.User;
import net.ysy.shop.service.UserService;
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 java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID=1L;
@Override
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= 0;
try {
count = userService.addUser(user);
} catch (SQLException e) {
e.printStackTrace();
}
//判断是否注册成功
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("遗憾,注册失败,跳转到注册页面!");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
我们启动服务器,访问下面网址,敲回车,查看结果:
我们去服务器端查看信息:
此时我们去看NaviCat查看用户表,看看是否插入了新的用户记录?
4、显示类别处理类ShowCategoryServlet
package net.ysy.shop.servlet;
import net.ysy.shop.bean.Category;
import net.ysy.shop.service.CategoryService;
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 java.io.IOException;
import java.util.List;
/**
* 显示类别控制程序
*
*/
@WebServlet("/showCategory")
public class ShowCategoryServlet extends HttpServlet {
private static final long serialVersionUID=1L;
@Override
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);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
我们进行测试
重启服务器,访问http://localhost:8080/shop/showCategory
我们去控制台查看信息
5、显示商品处理类ShowProductServlet
package net.ysy.shop.servlet;
import net.ysy.shop.bean.Product;
import net.ysy.shop.service.CategoryService;
import net.ysy.shop.service.ProductService;
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 java.io.IOException;
import java.util.List;
/**
* 功能:显示商品列表的控制程序
* 通过业务层访问后台数据
* 然后将数据返回个前台页面
*
*/
@WebServlet("/showProduct")
public class ShowProductServlet extends HttpServlet {
private static final long serialVersionUID=1L;
@Override
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.findProductByCategoryId(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+"的记录!");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
重启服务器,我们访问http://localhost:8080/shop/showProduct?categoryId=1
我们在来找类别为categoryId=8:
6、显示购物车处理类(ShowCartServlet)
package net.ysy.shop.servlet;
import net.ysy.shop.bean.Product;
import net.ysy.shop.service.CategoryService;
import net.ysy.shop.service.ProductService;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
@WebServlet("/showCart")
public class ShowCartServlet extends HttpServlet {
private static final long serialVersionUID =1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取商品类别标识符
int categoryId =Integer.parseInt(request.getParameter("categoryId"));
//获取session对象
HttpSession session=request.getSession();
//获取购物车
LinkedHashMap<Integer,Integer> cart =(LinkedHashMap<Integer, Integer>) session.getAttribute("cart");
//判断购物车是否为空
if (cart != null){
//定义购物表
List<HashMap<String,Object>> shoppingTable =new ArrayList<HashMap<String, Object>>();
//创建商品服务对象
ProductService productService=new ProductService();
//购物总金额
double totalPrice =0.0;
//遍历购物车
for (Integer id:cart.keySet()){
//获取商品对象
Product product=productService.findProductById(id);
//生成购物表记录
HashMap<String,Object> shoppingItem=new HashMap<String,Object>();
shoppingItem.put("id",product.getId());
shoppingItem.put("name",product.getName());
shoppingItem.put("price",product.getPrice());
shoppingItem.put("amount",cart.get(id));
shoppingItem.put("sum",product.getPrice() * cart.get(id));
//将购物表记录添加到购物车中
shoppingTable.add(shoppingItem);
//累加购买总金额
totalPrice =totalPrice+ (Double) shoppingItem.get("sum");
}
//将购物车和购买总金额保存session里
session.setAttribute("shoppingTable",shoppingTable);
session.setAttribute("totalPrice",totalPrice);
//重定向到显示商品控制程序
response.sendRedirect(request.getContextPath()+"/showProduct?categoryId="+categoryId);
}else {
System.out.println("购物车里没有类别号为["+categoryId+"]的商品!");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
7、操作购物车处理类(OperateCartServlet)
8、生成订单处理类(MakeOrderServlet)
package net.ysy.shop.servlet;
import net.ysy.shop.bean.Order;
import net.ysy.shop.service.OrderService;
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.xml.crypto.Data;
import java.io.IOException;
import java.util.Date;
@WebServlet("/makeOrder")
public class MakeOrderServlet extends HttpServlet {
private static final long serialVersionUID=1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置请求对象的字符编码
request.setCharacterEncoding("utf-8");
//获取表单提交数据
String username=request.getParameter("username");
String telephone=request.getParameter("telephone");
Double totalPrice=Double.parseDouble(request.getParameter("totalPrice"));
String deliveryAddrrss=request.getParameter("deliveryAddrrss");
//创建订单对象
Order order=new Order();
//设置订单属性
order.setUsername(username);
order.setTotalPric(totalPrice);
order.setTelephone(telephone);
order.setDeliveryAddrrss(deliveryAddrrss);
order.setOrderTime((Data) new Date());
//创建订单服务
OrderService orderService=new OrderService();
//添加订单
orderService.addOrder(order);
//获取最后一个订单
Order lastOrder =orderService.findLastOrder();
//保存到session里
request.getSession().setAttribute("lastOrder",lastOrder);
//重定向到显示订单页面
response.sendRedirect(request.getContextPath()+"/frontend/showOrder.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
9、支付处理类(PayServlet)
10、显示用户处理类(ShowUserServlet)
我们去服务器控制台查看输出信息:
控制层我们告一段落,我们开始完成展示层的工作.