JSP+Servlet实现购物车功能

最近期末的JSP要交大作业,我选择的是做一个在线购物书店,实现登陆注册购物车结算的功能。
一.项目总览以及使用的JS组件框架:

JSP+Servlet实现购物车功能
文章图片
捕获.JPG
根据项目结构 知道用的是DAO设计模式,然后使用了 JS组件库SUI,然后看看项目完成以后大概是这样.
引导页
引导页.gif
注册

注册.gif
登陆

JSP+Servlet实现购物车功能
文章图片
登陆.gif
图书列表

图书列表 (1).gif
图书详情以及购物车

JSP+Servlet实现购物车功能
文章图片
图书详情以及购物车.gif
结算

JSP+Servlet实现购物车功能
文章图片
结算.gif
二.数据库设计以及代码实现
user_profile表:实现登陆注册

JSP+Servlet实现购物车功能
文章图片
user_profile表.JPG book_details表:实现图书列表以及图书详情

JSP+Servlet实现购物车功能
文章图片
book_details表.JPG payment表:实现结算

JSP+Servlet实现购物车功能
文章图片
payment表.JPG 然后是代码:首先是根据数据库表生成的实体类:
UserProfile:

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pack; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author sl */ @Entity @Table(name = "user_profile") @XmlRootElement @NamedQueries({ @NamedQuery(name = "UserProfile.findAll", query = "SELECT u FROM UserProfile u") , @NamedQuery(name = "UserProfile.findByIdUserProfile", query = "SELECT u FROM UserProfile u WHERE u.idUserProfile = :idUserProfile") , @NamedQuery(name = "UserProfile.findByUsername", query = "SELECT u FROM UserProfile u WHERE u.username = :username") , @NamedQuery(name = "UserProfile.findByPassword", query = "SELECT u FROM UserProfile u WHERE u.password = :password") , @NamedQuery(name = "UserProfile.findByFirstname", query = "SELECT u FROM UserProfile u WHERE u.firstname = :firstname") , @NamedQuery(name = "UserProfile.findByMiddlename", query = "SELECT u FROM UserProfile u WHERE u.middlename = :middlename") , @NamedQuery(name = "UserProfile.findByLastname", query = "SELECT u FROM UserProfile u WHERE u.lastname = :lastname") , @NamedQuery(name = "UserProfile.findByAddress1", query = "SELECT u FROM UserProfile u WHERE u.address1 = :address1") , @NamedQuery(name = "UserProfile.findByAddress2", query = "SELECT u FROM UserProfile u WHERE u.address2 = :address2") , @NamedQuery(name = "UserProfile.findByCity", query = "SELECT u FROM UserProfile u WHERE u.city = :city") , @NamedQuery(name = "UserProfile.findByState", query = "SELECT u FROM UserProfile u WHERE u.state = :state") , @NamedQuery(name = "UserProfile.findByPincode", query = "SELECT u FROM UserProfile u WHERE u.pincode = :pincode") , @NamedQuery(name = "UserProfile.findByEmail", query = "SELECT u FROM UserProfile u WHERE u.email = :email") , @NamedQuery(name = "UserProfile.findByPhone", query = "SELECT u FROM UserProfile u WHERE u.phone = :phone")}) public class UserProfile implements Serializable {@OneToMany(cascade = CascadeType.ALL, mappedBy = "username") private Collection paymentCollection; private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idUser_Profile") private Integer idUserProfile; @Basic(optional = false) @Column(name = "username") private String username; @Basic(optional = false) @Column(name = "password") private String password; @Basic(optional = false) @Column(name = "firstname") private String firstname; @Basic(optional = false) @Column(name = "middlename") private String middlename; @Basic(optional = false) @Column(name = "lastname") private String lastname; @Basic(optional = false) @Column(name = "address1") private String address1; @Basic(optional = false) @Column(name = "address2") private String address2; @Basic(optional = false) @Column(name = "city") private String city; @Basic(optional = false) @Column(name = "state") private String state; @Basic(optional = false) @Column(name = "pincode") private String pincode; @Basic(optional = false) @Column(name = "email") private String email; @Basic(optional = false) @Column(name = "phone") private int phone; public UserProfile() { }public UserProfile(Integer idUserProfile) { this.idUserProfile = idUserProfile; }public UserProfile(Integer idUserProfile, String username, String password, String firstname, String middlename, String lastname, String address1, String address2, String city, String state, String pincode, String email, int phone) { this.idUserProfile = idUserProfile; this.username = username; this.password = password; this.firstname = firstname; this.middlename = middlename; this.lastname = lastname; this.address1 = address1; this.address2 = address2; this.city = city; this.state = state; this.pincode = pincode; this.email = email; this.phone = phone; }public Integer getIdUserProfile() { return idUserProfile; }public void setIdUserProfile(Integer idUserProfile) { this.idUserProfile = idUserProfile; }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 getFirstname() { return firstname; }public void setFirstname(String firstname) { this.firstname = firstname; }public String getMiddlename() { return middlename; }public void setMiddlename(String middlename) { this.middlename = middlename; }public String getLastname() { return lastname; }public void setLastname(String lastname) { this.lastname = lastname; }public String getAddress1() { return address1; }public void setAddress1(String address1) { this.address1 = address1; }public String getAddress2() { return address2; }public void setAddress2(String address2) { this.address2 = address2; }public String getCity() { return city; }public void setCity(String city) { this.city = city; }public String getState() { return state; }public void setState(String state) { this.state = state; }public String getPincode() { return pincode; }public void setPincode(String pincode) { this.pincode = pincode; }public String getEmail() { return email; }public void setEmail(String email) { this.email = email; }public int getPhone() { return phone; }public void setPhone(int phone) { this.phone = phone; }@Override public int hashCode() { int hash = 0; hash += (idUserProfile != null ? idUserProfile.hashCode() : 0); return hash; }@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof UserProfile)) { return false; } UserProfile other = (UserProfile) object; if ((this.idUserProfile == null && other.idUserProfile != null) || (this.idUserProfile != null && !this.idUserProfile.equals(other.idUserProfile))) { return false; } return true; }@Override public String toString() { return "pack.UserProfile[ idUserProfile=" + idUserProfile + " ]"; }@XmlTransient public Collection getPaymentCollection() { return paymentCollection; }public void setPaymentCollection(Collection paymentCollection) { this.paymentCollection = paymentCollection; }}

BookDetails:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pack; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author sl */ @Entity @Table(name = "book_details") @XmlRootElement @NamedQueries({ @NamedQuery(name = "BookDetails.findAll", query = "SELECT b FROM BookDetails b") , @NamedQuery(name = "BookDetails.findByIdBookDetails", query = "SELECT b FROM BookDetails b WHERE b.idBookDetails = :idBookDetails") , @NamedQuery(name = "BookDetails.findByCategoryName", query = "SELECT b FROM BookDetails b WHERE b.categoryName = :categoryName") , @NamedQuery(name = "BookDetails.findByBookId", query = "SELECT b FROM BookDetails b WHERE b.bookId = :bookId") , @NamedQuery(name = "BookDetails.findByTitle", query = "SELECT b FROM BookDetails b WHERE b.title = :title") , @NamedQuery(name = "BookDetails.findByAuthor", query = "SELECT b FROM BookDetails b WHERE b.author = :author") , @NamedQuery(name = "BookDetails.findByPublisher", query = "SELECT b FROM BookDetails b WHERE b.publisher = :publisher") , @NamedQuery(name = "BookDetails.findByIsbn", query = "SELECT b FROM BookDetails b WHERE b.isbn = :isbn") , @NamedQuery(name = "BookDetails.findByPrice", query = "SELECT b FROM BookDetails b WHERE b.price = :price") , @NamedQuery(name = "BookDetails.findByDescription", query = "SELECT b FROM BookDetails b WHERE b.description = :description")}) public class BookDetails implements Serializable {@Basic(optional = false) @Column(name = "pic") private String pic; private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idBook_Details") private Integer idBookDetails; @Basic(optional = false) @Column(name = "category_name") private String categoryName; @Basic(optional = false) @Column(name = "book_id") private int bookId; @Basic(optional = false) @Column(name = "title") private String title; @Basic(optional = false) @Column(name = "author") private String author; @Basic(optional = false) @Column(name = "publisher") private String publisher; @Basic(optional = false) @Column(name = "isbn") private String isbn; @Basic(optional = false) @Column(name = "price") private int price; @Column(name = "description") private String description; @OneToMany(cascade = CascadeType.ALL, mappedBy = "bookId") private Collection billTableCollection; public BookDetails() { }public BookDetails(Integer idBookDetails) { this.idBookDetails = idBookDetails; }public BookDetails(Integer idBookDetails, String categoryName, int bookId, String title, String author, String publisher, String isbn, int price) { this.idBookDetails = idBookDetails; this.categoryName = categoryName; this.bookId = bookId; this.title = title; this.author = author; this.publisher = publisher; this.isbn = isbn; this.price = price; }public Integer getIdBookDetails() { return idBookDetails; }public void setIdBookDetails(Integer idBookDetails) { this.idBookDetails = idBookDetails; }public String getCategoryName() { return categoryName; }public void setCategoryName(String categoryName) { this.categoryName = categoryName; }public int getBookId() { return bookId; }public void setBookId(int bookId) { this.bookId = bookId; }public String getTitle() { return title; }public void setTitle(String title) { this.title = title; }public String getAuthor() { return author; }public void setAuthor(String author) { this.author = author; }public String getPublisher() { return publisher; }public void setPublisher(String publisher) { this.publisher = publisher; }public String getIsbn() { return isbn; }public void setIsbn(String isbn) { this.isbn = isbn; }public int getPrice() { return price; }public void setPrice(int price) { this.price = price; }public String getDescription() { return description; }public void setDescription(String description) { this.description = description; }@XmlTransient public Collection getBillTableCollection() { return billTableCollection; }public void setBillTableCollection(Collection billTableCollection) { this.billTableCollection = billTableCollection; }@Override public int hashCode() { int hash = 0; hash += (idBookDetails != null ? idBookDetails.hashCode() : 0); return hash; }@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof BookDetails)) { return false; } BookDetails other = (BookDetails) object; if ((this.idBookDetails == null && other.idBookDetails != null) || (this.idBookDetails != null && !this.idBookDetails.equals(other.idBookDetails))) { return false; } return true; }@Override public String toString() { return "pack.BookDetails[ idBookDetails=" + idBookDetails + " ]"; }public String getPic() { return pic; }public void setPic(String pic) { this.pic = pic; }}

Payment:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pack; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author sl */ @Entity @Table(name = "payment") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Payment.findAll", query = "SELECT p FROM Payment p") , @NamedQuery(name = "Payment.findByIdPayment", query = "SELECT p FROM Payment p WHERE p.idPayment = :idPayment") , @NamedQuery(name = "Payment.findByTotalAmount", query = "SELECT p FROM Payment p WHERE p.totalAmount = :totalAmount") , @NamedQuery(name = "Payment.findByCreditcardNum", query = "SELECT p FROM Payment p WHERE p.creditcardNum = :creditcardNum") , @NamedQuery(name = "Payment.findByCreditcardType", query = "SELECT p FROM Payment p WHERE p.creditcardType = :creditcardType")}) public class Payment implements Serializable {private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "idPayment") private Integer idPayment; @Basic(optional = false) @Column(name = "total_amount") private int totalAmount; @Basic(optional = false) @Column(name = "creditcard_num") private int creditcardNum; @Basic(optional = false) @Column(name = "creditcard_type") private int creditcardType; @JoinColumn(name = "bill_num", referencedColumnName = "bill_num") @ManyToOne(optional = false) private BillTable billNum; @JoinColumn(name = "username", referencedColumnName = "username") @ManyToOne(optional = false) private UserProfile username; public Payment() { }public Payment(Integer idPayment) { this.idPayment = idPayment; }public Payment(Integer idPayment, int totalAmount, int creditcardNum, int creditcardType) { this.idPayment = idPayment; this.totalAmount = totalAmount; this.creditcardNum = creditcardNum; this.creditcardType = creditcardType; }public Integer getIdPayment() { return idPayment; }public void setIdPayment(Integer idPayment) { this.idPayment = idPayment; }public int getTotalAmount() { return totalAmount; }public void setTotalAmount(int totalAmount) { this.totalAmount = totalAmount; }public int getCreditcardNum() { return creditcardNum; }public void setCreditcardNum(int creditcardNum) { this.creditcardNum = creditcardNum; }public int getCreditcardType() { return creditcardType; }public void setCreditcardType(int creditcardType) { this.creditcardType = creditcardType; }public BillTable getBillNum() { return billNum; }public void setBillNum(BillTable billNum) { this.billNum = billNum; }public UserProfile getUsername() { return username; }public void setUsername(UserProfile username) { this.username = username; }@Override public int hashCode() { int hash = 0; hash += (idPayment != null ? idPayment.hashCode() : 0); return hash; }@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Payment)) { return false; } Payment other = (Payment) object; if ((this.idPayment == null && other.idPayment != null) || (this.idPayment != null && !this.idPayment.equals(other.idPayment))) { return false; } return true; }@Override public String toString() { return "pack.Payment[ idPayment=" + idPayment + " ]"; }}

工具类util包下的数据库连接类BaseDao:
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author sl */ public class BaseDao { private static String driver="com.mysql.jdbc.Driver"; private static String url="jdbc:mysql://localhost/mydb"; private static String user="***"; private static String password="******"; //这里数据库账号密码就不贴了/*** 22* 连接数据库的方法 23* @return 24* @throws ClassNotFoundException 25* @throws SQLException 26*/ public static Connection getCon() throws ClassNotFoundException, SQLException{ Class.forName(driver); //加载数据库驱动 System.out.println("测试加载数据库成功"); Connection con=DriverManager.getConnection(url, user, password); System.out.println("测试数据库链接成功"); return con; }/*** 36* 关闭数据库的方法 37* @param con 38* @param ps 39* @param rs 40*/ public static void close(Connection con,PreparedStatement ps,ResultSet rs){ if(rs!=null){//关闭资源,避免出现异常 try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(con!=null){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }/*** 69* 同意增删改的方法 70* @param sql 71* @param arr 72* @return 73*/ public static boolean addUpdateDelete(String sql,Object[] arr){ Connection con=null; PreparedStatement ps=null; try { con=BaseDao.getCon(); //第一步 :连接数据库的操作 ps=con.prepareStatement(sql); //第二步:预编译 //第三步:设置值 if(arr!=null && arr.length!=0){ for(int i=0; i0){ return true; }else{ return false; } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } //测试用例 //public static void main(String[] args) { //try { //BaseDao.getCon(); //} catch (ClassNotFoundException e) { //// TODO Auto-generated catch block //e.printStackTrace(); //} catch (SQLException e) { //// TODO Auto-generated catch block //e.printStackTrace(); //} //} }

然后书DAO数据层的Book类以及User类的接口以及回调方法实现:
BookDao:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import java.util.List; import pack.BookDetails; /** * * @author sl */ public interface BookDao { /*** 15* 图书的查询的方法 16* @param sql 17* @param arr 18* @return 19*/ public List select(String sql,Object[] arr); /*** 23* 按照图书编号进行查询 24* @param id 25* @return 26*/ public BookDetails getBook(Integer id); public List getBooks(String category); public List queryAll(); }

BookDaoImpl:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import pack.BookDetails; import util.BaseDao; /** * * @author sl */ public class BookDaoImpl implements BookDao{ @Override public List select(String sql, Object[] arr) { Connection con=null; PreparedStatement ps=null; ResultSet rs=null; try { con=BaseDao.getCon(); //第一步连接数据库 ps=con.prepareStatement(sql); //第二步:预编译 if(arr!=null){ for(int i=0; i list=new ArrayList(); while(rs.next()){ BookDetails book=new BookDetails(); book.setBookId(rs.getInt("book_id")); book.setTitle(rs.getString("title")); book.setAuthor(rs.getString("author")); book.setPublisher(rs.getString("publisher")); book.setIsbn(rs.getString("isbn")); book.setPrice(rs.getInt("price")); book.setPic(rs.getString("pic")); book.setCategoryName("category_name"); list.add(book); } return list; } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //关闭资源,避免出现异常 BaseDao.close(con, ps, rs); }return null; }//根据书的ID查找书本 @Override public BookDetails getBook(Integer id) { Connection con=null; PreparedStatement ps=null; ResultSet rs=null; try { con=BaseDao.getCon(); //第一步连接数据库 String sql="select * from book_details where book_id = ? "; ps=con.prepareStatement(sql); //第二步:预编译 ps.setInt(1, id); //第四步执行sql rs=ps.executeQuery(); while(rs.next()){ BookDetails books=new BookDetails(); books.setBookId(rs.getInt("book_id")); books.setTitle(rs.getString("title")); books.setAuthor(rs.getString("author")); books.setPublisher(rs.getString("publisher")); books.setIsbn(rs.getString("isbn")); books.setPrice(rs.getInt("price")); books.setPic(rs.getString("pic")); books.setCategoryName("category_name"); return books; } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //关闭资源,避免出现异常 BaseDao.close(con, ps, rs); }return null; } //根据书的类型查找书本 @Override public List getBooks(String category) { Connection con=null; PreparedStatement ps=null; ResultSet rs=null; try { con=BaseDao.getCon(); //第一步连接数据库 String sql="select * from book_details where category_name = ? "; ps=con.prepareStatement(sql); //第二步:预编译 ps.setString(1, category); //第四步执行sql rs=ps.executeQuery(); List list=new ArrayList(); while(rs.next()){ BookDetails books=new BookDetails(); books.setBookId(rs.getInt("book_id")); books.setTitle(rs.getString("title")); books.setAuthor(rs.getString("author")); books.setPublisher(rs.getString("publisher")); books.setIsbn(rs.getString("isbn")); books.setPrice(rs.getInt("price")); books.setPic(rs.getString("pic")); books.setCategoryName("category_name"); list.add(books); } return list; } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //关闭资源,避免出现异常 BaseDao.close(con, ps, rs); }return null; }@Override public List queryAll() { Connection con=null; PreparedStatement ps=null; ResultSet rs=null; try { con=BaseDao.getCon(); //第一步连接数据库 String sql="select * from book_details"; ps=con.prepareStatement(sql); //第二步:预编译//第四步执行sql rs=ps.executeQuery(); List list=new ArrayList(); while(rs.next()){ BookDetails books=new BookDetails(); books.setBookId(rs.getInt("book_id")); books.setTitle(rs.getString("title")); books.setAuthor(rs.getString("author")); books.setPublisher(rs.getString("publisher")); books.setIsbn(rs.getString("isbn")); books.setPrice(rs.getInt("price")); books.setPic(rs.getString("pic")); books.setCategoryName("category_name"); list.add(books); } return list; } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //关闭资源,避免出现异常 BaseDao.close(con, ps, rs); }return null; }}

UserDao:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import java.util.List; import pack.UserProfile; /** * * @author sl */ public interface UserDao { //用户登陆方法声明/回调声明 查询的方法都是返回的对象 返回查询的对象 或者是list对象或者是VO类对象 public UserProfile login(UserProfile user); //用户注册方法声明/回调声明 //增加更新删除的方法 插入的方法都是返回一个布尔值 成功或者失败 public boolean register(UserProfile user); //查询用户的信息 public ListselectUser(String sql,Object[]arr); }

UserDaoImpl:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import pack.UserProfile; import util.BaseDao; /** * * @author sl */ public class UserDaoImpl implements UserDao{ //数据库的连接都要try catch 不同的是 查询的方法要在数据层DAO层写 增删改则可以借助工具类中 封装好的try catch //回调方法 登陆 @Override public UserProfile login(UserProfile user) {//传入一个有用户名和密码的对象 如果查询到了 就返回 没有对象为null Connection connection=null; //数据库连接类 PreparedStatement ps=null; //执行sql语句 ResultSet rs=null; //返回的结果 try { //1.获取数据库连接 connection=BaseDao.getCon(); //2.书写sql语句 String sql="SELECT * FROM user_profile WHERE username=? AND password=?"; //3.预编译 ps=connection.prepareStatement(sql); //4.设置查询条件 ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); //5.执行sql语句 返回结果集 rs=ps.executeQuery(); UserProfile users=null; if(rs.next()){ //数据库返回的数据与vo类进行交互 users=new UserProfile(); users.setUsername(rs.getString("username")); users.setPassword(rs.getString("password")); users.setPhone(rs.getInt("phone")); //....还有一些值 return users; }else{ returnnull; }} catch (Exception e) { e.printStackTrace(); }finally{ //关闭资源 避免出现异常 BaseDao.close(connection, ps, rs); } return null; }//回调方法 注册 @Override public boolean register(UserProfile user) { String sql = "INSERT INTO user_profile(username, password, firstname, middlename, lastname, address1, address2, city, state, pincode, email, phone) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; List list=new ArrayList(); list.add(user.getUsername()); list.add(user.getPassword()); list.add(user.getFirstname()); list.add(user.getMiddlename()); list.add(user.getLastname()); list.add(user.getAddress1()); list.add(user.getAddress2()); list.add(user.getCity()); list.add(user.getState()); list.add(user.getPincode()); list.add(user.getEmail()); list.add(user.getPhone()); boolean flag=BaseDao.addUpdateDelete(sql,list.toArray()); if(flag){ return true; }else{ return false; } }@Override public List selectUser(String sql, Object[] arr) { //这个是还要在业务层调用的 上面两个方法直接可以进行数据层和JSP的交互 由于我们这里不需要根据名字什么的来查询对象 //所以这里就不写了 return null; }}
业务层service包下的Book类代码:
BookService:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package service; import java.util.List; import pack.BookDetails; /** * * @author sl */ public interface BookService { /*** 15* 图书信息查询的方法 16* @return 17*/ public List select(BookDetails book); public List getBooks(BookDetails book); /*** 21* 根据id进行查询 22* @param id 23* @return 24*/ public BookDetails getBook(BookDetails book); public List queryAll(); }

BookServiceImpl:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package service; import dao.BookDao; import dao.BookDaoImpl; import java.util.ArrayList; import java.util.List; import pack.BookDetails; /** * * @author sl */ public class BookServiceImpl implements BookService{ private BookDao dao=new BookDaoImpl(); public List select(BookDetails book){ //String sql="select * from book "; StringBuilder sql=new StringBuilder("select * from book_details where 1=1 "); //sql语句 List list=new ArrayList(); if(book!=null){if( book.getBookId()!=0){ sql.append(" and book_id=? "); list.add(book.getBookId()); } /*list.add(book.getBookname()); 32list.add(book.getPrice()); 33list.add(book.getAuthor()); 34list.add(book.getPic()); 35list.add(book.getPublish()); */ }return dao.select(sql.toString(), list.toArray()); } @Override public BookDetails getBook(BookDetails book) { if(book!=null && book.getBookId()!=0){ return dao.getBook(book.getBookId()); } return null; }@Override public List getBooks(BookDetails book) { if(book!=null && !book.getCategoryName().equals("")){ return dao.getBooks(book.getCategoryName()); } else{ return null; }}@Override public List queryAll() { return dao.queryAll(); }}
然后把上述准备工作做完以后,我们根据JSP页面上的步骤流程 一步步调用代码:
首先是引导页,
index.html:
New Tech在线购物商店 - 锐客网 //导入样式以及JS组件库 body{background:url(3.jpg)}


欢迎来到New Tech在线购物商店




注册            登陆展示操作

然后我们点击注册,跳转到register.html:
注册 - 锐客网 body{background:url(3.jpg)}
  • 引导页
  • 注册

使用registerBean处理注册的逻辑:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pack; import dao.UserDao; import dao.UserDaoImpl; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import pack.UserProfile; /** * * @author sl */ public class registerBean extends HttpServlet {String username; String password; String firstname; String middlename; String lastname; String address1; String address2; String city; String state; String pincode; String email; int phone; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doGet(request, response); }/** * * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //405错误这里 不要加super response.setContentType("text/html; charset=UTF-8"); //获取register的JSP页面提交的数据 username= request.getParameter("username"); password=request.getParameter("password"); firstname=request.getParameter("firstname"); middlename=request.getParameter("middlename"); lastname=request.getParameter("lastname"); address1=request.getParameter("address1"); address2=request.getParameter("address2"); city=request.getParameter("city"); state=request.getParameter("state"); pincode=request.getParameter("pincode"); email=request.getParameter("email"); try { phone=Integer.parseInt(request.getParameter("phone")); //这个int类型的需要加try catch } catch (NumberFormatException e) { e.printStackTrace(); }UserProfile user=new UserProfile(); //将数据与VO类进行交互 user.setUsername(username); user.setPassword(password); user.setFirstname(firstname); user.setMiddlename(middlename); user.setLastname(lastname); user.setAddress1(address1); user.setAddress2(address2); user.setCity(city); user.setState(state); user.setPincode(pincode); user.setEmail(email); user.setPhone(phone); //与数据层进行交互 UserDao dao=new UserDaoImpl(); boolean flag=dao.register(user); if(flag){ response.sendRedirect("registersuccess.html"); }else{ response.sendRedirect("register.jsp"); }}}

回到引导页,点击登陆,进入login.html:
登陆 - 锐客网 body{background:url(3.jpg)}
  • 引导页
  • 登陆

使用loginBean处理登陆的逻辑:
package pack; import dao.UserDao; import dao.UserDaoImpl; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import pack.UserProfile; /** * * @author sl */ public class loginBean extends HttpServlet {@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); //int userId = Integer.parseInt(request.getParameter("username")); String userId = request.getParameter("username"); String password=request.getParameter("password"); UserProfile user=new UserProfile(); user.setUsername(userId); user.setPassword(password); //与VO层进行交互 UserDao dao=new UserDaoImpl(); UserProfile userBack=dao.login(user); if(userBack!=null){ HttpSession session=request.getSession(); session.setAttribute("username",userBack.getUsername()); response.sendRedirect("selectcategory.jsp"); }else if(userBack==null){ response.sendRedirect("faillogin.html"); }}@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); //To change body of generated methods, choose Tools | Templates. }}

登陆成功以后进入图书列表页面selectcategory.jsp,我们可以通过表单刷新Book_Details类的category字段属性,再根据这个字段来查询刷新图书列表在book.jsp中显示:
selectcategory.jsp:
购物页面 - 锐客网td{border:1px solid green; } body{background:url(33_4.jpg)}
书本封面 书名
JSP+Servlet实现购物车功能
文章图片

book.jsp:
图书列表的页面 - 锐客网 body{background:url(33_4.jpg)} 我的购物车
书本封面 书名
JSP+Servlet实现购物车功能
文章图片

然后根据我们在book.jsp中点击的响应书本的链接 将其id传入给dobook.jsp,我们根据这个书本的id,调用数据层业务层的代码,查询出书本的全部信息,在detail.jsp页面显示出来:
dobook.jsp:
JSP Page - 锐客网

detail.jsp:
图书详细信息的页面 - 锐客网 body{background:url(33_4.jpg)} 我的购物车
图书封面 图书名称 图书作者 图书出版社 图书编号 图书价格
JSP+Servlet实现购物车功能
文章图片
添加到购物车 图书列表

然后我们如果点击了添加到购物车,那么就有了购物结算的逻辑,我们准备好购物车的模型代码cart.jsp以及购物车添加书本以及计算书本总价的docart.jsp:
cart.jsp:
添加到购物车 - 锐客网

docart.jsp:
我的购物车的页面 - 锐客网 body{background:url(33_4.jpg)}          
书本编号 书本名称 书本单价 书本数量 书本小计
价格总计
返回图书列表 结算

然后我们点击结算,跳转到payment.html:
新建待办事项 - 锐客网 body{background:url(33_4.jpg)}

我们通过paymentInfoServlet来进行信用卡的验证,通过vo类与数据库交互:
package pack; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import pack.Payment; public class paymentInfoServlet extends HttpServlet { Connection conn; PrintWriter out; ResultSet rs; Boolean isUserBoolean; @Override public void init() throws ServletException { super.init(); //To change body of generated methods, choose Tools | Templates. conn=null; out=null; rs=null; isUserBoolean=Boolean.FALSE; }@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); out=response.getWriter(); //int userId = Integer.parseInt(request.getParameter("username")); int num = Integer.parseInt(request.getParameter("creditcard_num")); int type=Integer.parseInt(request.getParameter("creditcard_type")); try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); conn=DriverManager.getConnection("jdbc:mysql://localhost/mydb","****","*******"); //数据库用户名密码略 List all=new ArrayList(); all=findAll(); out.println(num); out.println(type); for(int i = 0 ; i < all.size() ; i++) {//我们只需要知道 有没有这个用户名和密码的用户存在 改变boolean值 而不需要知道所有的匹配方式 //if(userId==all.get(i).getUserId()&&password.equals(all.get(i).getUserPassword())) //out.println(all.get(i).getUserPassword()); out.println(all.get(i).getCreditcardNum()); out.println(all.get(i).getCreditcardType()); if(num==all.get(i).getCreditcardNum()&&type==all.get(i).getCreditcardType()) { isUserBoolean=true; //out.println("登陆成功"); } //else{ //out.println("登陆失败"); //} }//循环结束就为真 }catch(Exception e){ e.printStackTrace(); } if(isUserBoolean==Boolean.TRUE){ //out.println("登陆成功"); HttpSession session=request.getSession(); session.setAttribute("creditcard_num",num ); response.sendRedirect("success.html"); }else if(isUserBoolean==Boolean.FALSE){ //out.println("登陆失败"); response.sendRedirect("fail.html"); } isUserBoolean=Boolean.FALSE; //这里不要忘记重新置空 destroy中置空无用 因为页面没有被销毁 }@Override public void destroy() { super.destroy(); //To change body of generated methods, choose Tools | Templates. try{ conn.close(); out.close(); rs.close(); }catch(SQLException se){ out.println(se.toString()); } }@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); //To change body of generated methods, choose Tools | Templates. }//查询全部数据 数据查询 public List findAll() throws Exception { PreparedStatement pstmt=null; String query=null; List all=new ArrayList(); query="SELECT creditcard_num,creditcard_type FROM payment"; pstmt=this.conn.prepareStatement(query); ResultSet rs=pstmt.executeQuery(); //对数据库进行查询 有结果返回 while(rs.next()){//逐行读数据 虽然只有一行 Payment vo=new Payment(); ; vo.setCreditcardNum(rs.getInt(1)); //逐列读出 vo.setCreditcardType(rs.getInt(2)); all.add(vo); //将从数据库返回的数据保存在底层媒介后 往泛型集合中加一个实例化对象 } return all; }}

【JSP+Servlet实现购物车功能】以上就完成了我们的项目啦~以下github项目地址:Ricardo_L_Song

    推荐阅读