1:電商如此發達的如今,做爲一個web開發程序猿,若是不會寫購物車,真是有點很差意思找工做。因此抓緊練習啊,從上篇博客中抽離出如何實現購物車的功能。html
2:首先須要理解購物車實現的一些基本步驟。
2.1:首先考慮我購買的是哪一本書籍或者那一件商品,是否是,這裏可使用id傳參肯定購買的是那一件商品或者書籍,也可使用session中取出哪一本書籍,這裏採用從session的取出那一件商品或者書籍
代碼如:java
Book book=(Book)session.getAttribute("book");
2.2:第二考慮如何把書籍放到購物車中
2.1.1:首先考慮是否有購物車,若是沒有,則建立,若是有直接使用
2.1.2:其次先將購物車從session中拿出來,不存在就建立。
代碼如:mysql
Map<Integer,CartItem> cart=(Map<Integer,CartItem>)session.getAttribute("cart");
//若是沒有購物車,那麼建立,只有第一次訪問纔會操做
if(cart==null){
//new一個購物車
cart=new HashMap<>();
}
2.3:考慮如何把書籍放到購物車中
2.1.1:第一考慮購物車中是否有該書籍,因此先從購物車中獲取該書籍,若是爲空,那麼沒有該書籍
代碼如:web
CartItem item=(CartItem)cart.get(book.getBookid());
if(item==null){
//若是購物車中不存在該書籍,那麼建立,且數量默認爲1
item=new CartItem();
//將書籍放到購物車中
item.setBook(book);
//將書籍的默認數量爲1
item.setNumber(1);
}else{
//若是購物車中以及有該書籍,那麼數量加1
item.setNumber(item.getNumber()+1);
}
2.4:考慮如何把購物車項(即挑選的書籍是哪個和書本的數量)放到購物車中
代碼如:sql
cart.put(book.getBookid(),item);
2.5:將購物車放到session中,方便後面取出來
代碼如:數據庫
session.setAttribute("cart", cart);session
3:下面是具體的實現,從建立數據表開始,數據表book字段和數據名稱以下所示:
app
4:下面建立實體類book.java;jsp
1 package com.bie.po; 2 3 import java.io.Serializable; 4 5 /** 6 * @author BieHongLi 7 * @version 建立時間:2017年2月27日 上午10:07:21 8 * 圖書的實體類 9 */ 10 public class Book implements Serializable{ 11 12 //實體類實現序列化,避免後面出現異常 13 private static final long serialVersionUID = 1L; 14 private Integer bookid; 15 private String bookname; 16 private Double price; 17 private String author; 18 private String pic; 19 private String publish; 20 public Integer getBookid() { 21 return bookid; 22 } 23 public void setBookid(Integer bookid) { 24 this.bookid = bookid; 25 } 26 public String getBookname() { 27 return bookname; 28 } 29 public void setBookname(String bookname) { 30 this.bookname = bookname; 31 } 32 public Double getPrice() { 33 return price; 34 } 35 public void setPrice(Double price) { 36 this.price = price; 37 } 38 public String getAuthor() { 39 return author; 40 } 41 public void setAuthor(String author) { 42 this.author = author; 43 } 44 public String getPic() { 45 return pic; 46 } 47 public void setPic(String pic) { 48 this.pic = pic; 49 } 50 public String getPublish() { 51 return publish; 52 } 53 public void setPublish(String publish) { 54 this.publish = publish; 55 } 56 @Override 57 public String toString() { 58 return "Book [bookid=" + bookid + ", bookname=" + bookname + ", price=" + price + ", author=" + author 59 + ", pic=" + pic + ", publish=" + publish + "]"; 60 } 61 62 63 }
5:建立好實體類接下來是寫工具類BaseDao.java,用於鏈接數據庫的操做,這些代碼就不作多解釋了,都已經寫爛了。因此工具類必定要熟練書寫ide
1 package com.bie.utils; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 9 /** 10 * @author BieHongLi 11 * @version 建立時間:2017年2月27日 上午10:09:00 12 * 鏈接數據庫的工具類 13 */ 14 public class BaseDao { 15 16 private static String driver="com.mysql.jdbc.Driver"; 17 private static String url="jdbc:mysql:///test"; 18 private static String user="root"; 19 private static String password="123456"; 20 21 /*** 22 * 鏈接數據庫的方法 23 * @return 24 * @throws ClassNotFoundException 25 * @throws SQLException 26 */ 27 public static Connection getCon() throws ClassNotFoundException, SQLException{ 28 Class.forName(driver);//加載數據庫驅動 29 System.out.println("測試加載數據庫成功"); 30 Connection con=DriverManager.getConnection(url, user, password); 31 System.out.println("測試數據庫連接成功"); 32 return con; 33 } 34 35 /*** 36 * 關閉數據庫的方法 37 * @param con 38 * @param ps 39 * @param rs 40 */ 41 public static void close(Connection con,PreparedStatement ps,ResultSet rs){ 42 if(rs!=null){//關閉資源,避免出現異常 43 try { 44 rs.close(); 45 } catch (SQLException e) { 46 // TODO Auto-generated catch block 47 e.printStackTrace(); 48 } 49 } 50 if(ps!=null){ 51 try { 52 ps.close(); 53 } catch (SQLException e) { 54 // TODO Auto-generated catch block 55 e.printStackTrace(); 56 } 57 } 58 if(con!=null){ 59 try { 60 con.close(); 61 } catch (SQLException e) { 62 // TODO Auto-generated catch block 63 e.printStackTrace(); 64 } 65 } 66 } 67 68 /*** 69 * 贊成增刪改的方法 70 * @param sql 71 * @param arr 72 * @return 73 */ 74 public static boolean addUpdateDelete(String sql,Object[] arr){ 75 Connection con=null; 76 PreparedStatement ps=null; 77 try { 78 con=BaseDao.getCon();//第一步 :鏈接數據庫的操做 79 ps=con.prepareStatement(sql);//第二步:預編譯 80 //第三步:設置值 81 if(arr!=null && arr.length!=0){ 82 for(int i=0;i<arr.length;i++){ 83 ps.setObject(i+1, arr[i]); 84 } 85 } 86 int count=ps.executeUpdate();//第四步:執行sql語句 87 if(count>0){ 88 return true; 89 }else{ 90 return false; 91 } 92 } catch (ClassNotFoundException e) { 93 // TODO Auto-generated catch block 94 e.printStackTrace(); 95 } catch (SQLException e) { 96 // TODO Auto-generated catch block 97 e.printStackTrace(); 98 } 99 return false; 100 } 101 102 public static void main(String[] args) { 103 try { 104 BaseDao.getCon(); 105 } catch (ClassNotFoundException e) { 106 // TODO Auto-generated catch block 107 e.printStackTrace(); 108 } catch (SQLException e) { 109 // TODO Auto-generated catch block 110 e.printStackTrace(); 111 } 112 } 113 }
6:寫好工具類就能夠進行寫dao層(數據交互層),service層(業務邏輯層),先寫數據交互層dao層,使用先建立接口再實現接口的方法
1 package com.bie.dao; 2 3 import java.util.List; 4 5 import com.bie.po.Book; 6 7 /** 8 * @author BieHongLi 9 * @version 建立時間:2017年2月27日 上午10:11:21 10 * 11 */ 12 public interface BookDao { 13 14 /*** 15 * 圖書的查詢的方法 16 * @param sql 17 * @param arr 18 * @return 19 */ 20 public List<Book> select(String sql,Object[] arr); 21 22 /*** 23 * 按照圖書編號進行查詢 24 * @param id 25 * @return 26 */ 27 public Book getBook(Integer id); 28 }
1 package com.bie.dao.impl; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 import java.util.List; 9 10 import com.bie.dao.BookDao; 11 import com.bie.po.Book; 12 import com.bie.utils.BaseDao; 13 14 /** 15 * @author BieHongLi 16 * @version 建立時間:2017年2月27日 上午10:11:34 17 * 18 */ 19 public class BookDaoImpl implements BookDao{ 20 21 @Override 22 public List<Book> select(String sql, Object[] arr) { 23 Connection con=null; 24 PreparedStatement ps=null; 25 ResultSet rs=null; 26 try { 27 con=BaseDao.getCon();//第一步鏈接數據庫 28 ps=con.prepareStatement(sql);//第二步:預編譯 29 if(arr!=null){ 30 for(int i=0;i<arr.length;i++){ 31 ps.setObject(i+1, arr[i]); 32 } 33 } 34 //第四步執行sql 35 rs=ps.executeQuery(); 36 List<Book> list=new ArrayList<Book>(); 37 while(rs.next()){ 38 Book book=new Book(); 39 book.setBookid(rs.getInt("bookid")); 40 book.setBookname(rs.getString("bookname")); 41 book.setPrice(rs.getDouble("price")); 42 book.setAuthor(rs.getString("author")); 43 book.setPic(rs.getString("pic")); 44 book.setPublish(rs.getString("publish")); 45 46 list.add(book); 47 } 48 return list; 49 } catch (ClassNotFoundException e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } catch (SQLException e) { 53 // TODO Auto-generated catch block 54 e.printStackTrace(); 55 }finally{ 56 //關閉資源,避免出現異常 57 BaseDao.close(con, ps, rs); 58 } 59 60 return null; 61 } 62 63 @Override 64 public Book getBook(Integer id) { 65 Connection con=null; 66 PreparedStatement ps=null; 67 ResultSet rs=null; 68 try { 69 con=BaseDao.getCon();//第一步鏈接數據庫 70 String sql="select * from book where bookid = ? "; 71 ps=con.prepareStatement(sql);//第二步:預編譯 72 ps.setInt(1, id); 73 74 //第四步執行sql 75 rs=ps.executeQuery(); 76 while(rs.next()){ 77 Book books=new Book(); 78 books.setBookid(rs.getInt("bookid")); 79 books.setBookname(rs.getString("bookname")); 80 books.setPrice(rs.getDouble("price")); 81 books.setAuthor(rs.getString("author")); 82 books.setPic(rs.getString("pic")); 83 books.setPublish(rs.getString("publish")); 84 85 return books; 86 } 87 } catch (ClassNotFoundException e) { 88 // TODO Auto-generated catch block 89 e.printStackTrace(); 90 } catch (SQLException e) { 91 // TODO Auto-generated catch block 92 e.printStackTrace(); 93 }finally{ 94 //關閉資源,避免出現異常 95 BaseDao.close(con, ps, rs); 96 } 97 98 return null; 99 } 100 101 102 }
7:寫好dao層(數據交互層),就能夠寫service層(業務邏輯層),寫業務邏輯層service層,也是使用先建立接口再實現接口的方法
1 package com.bie.service; 2 3 import java.util.List; 4 5 import com.bie.po.Book; 6 7 /** 8 * @author BieHongLi 9 * @version 建立時間:2017年2月27日 上午10:13:38 10 * 11 */ 12 public interface BookService { 13 14 /*** 15 * 圖書信息查詢的方法 16 * @return 17 */ 18 public List<Book> select(Book book); 19 20 /*** 21 * 根據id進行查詢 22 * @param id 23 * @return 24 */ 25 public Book getBook(Book book); 26 }
1 package com.bie.service.impl; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import com.bie.dao.BookDao; 7 import com.bie.dao.impl.BookDaoImpl; 8 import com.bie.po.Book; 9 import com.bie.service.BookService; 10 11 /** 12 * @author BieHongLi 13 * @version 建立時間:2017年2月27日 上午10:13:52 14 * 15 */ 16 public class BookServiceImpl implements BookService{ 17 18 private BookDao dao=new BookDaoImpl(); 19 20 public List<Book> select(Book book){ 21 //String sql="select * from book "; 22 StringBuilder sql=new StringBuilder("select * from book where 1=1 "); 23 //sql語句 24 List<Object> list=new ArrayList<Object>(); 25 if(book!=null){ 26 27 if(book.getBookid()!=null && book.getBookid()!=0){ 28 sql.append(" and bookid=? "); 29 list.add(book.getBookid()); 30 } 31 /*list.add(book.getBookname()); 32 list.add(book.getPrice()); 33 list.add(book.getAuthor()); 34 list.add(book.getPic()); 35 list.add(book.getPublish());*/ 36 } 37 38 return dao.select(sql.toString(), list.toArray()); 39 } 40 41 @Override 42 public Book getBook(Book book) { 43 if(book.getBookid()!=null && book.getBookid()!=0){ 44 return dao.getBook(book.getBookid()); 45 } 46 return null; 47 } 48 49 50 }
8:最後按照正常開發的話就是servlet層,可是這裏將servlet層的代碼寫到了jsp裏面。因此下面jsp頁面纔是大戲
先建立一個book.jsp頁面,用於顯示從數據庫查詢到的圖書數據
1 <%@page import="java.util.List"%> 2 <%@page import="com.bie.service.impl.BookServiceImpl"%> 3 <%@page import="com.bie.po.Book"%> 4 <%@ page language="java" contentType="text/html; charset=UTF-8" 5 pageEncoding="UTF-8"%> 6 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 7 <html> 8 <head> 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 10 <title>圖書列表的頁面</title> 11 </head> 12 <body> 13 <% 14 //圖書的實體類建立一個對象 15 Book book=new Book(); 16 //圖書的業務邏輯層層 17 BookServiceImpl service=new BookServiceImpl(); 18 List<Book> list=service.select(book); 19 %> 20 <div style="text-align:right;font-size:36px;"> 21 <a href="docart.jsp">個人購物車</a> 22 </div> 23 <table align="center" width="100%"> 24 <tr> 25 <th>編號</th> 26 <th>書名</th> 27 <th>價格</th> 28 <th>做者</th> 29 <th>封皮</th> 30 <th>出版社</th> 31 </tr> 32 <% 33 for(Book b:list){ 34 %> 35 <tr align="center"> 36 <td><%=b.getBookid() %></td> 37 <td><a href="dobook.jsp?id=<%=b.getBookid()%>"><%=b.getBookname() %></a></td> 38 <td><%=b.getPrice() %></td> 39 <td><%=b.getAuthor() %></td> 40 <td><%=b.getPic() %></td> 41 <td><%=b.getPublish() %></td> 42 </tr> 43 <%} %> 44 </table> 45 46 </body> 47 </html>
9:當圖書顯示出來以後就能夠根據圖書編號查看圖書詳情了,接着寫dobook.jsp頁面和detail.jsp頁面,這個顯示圖書的詳細的信息的頁面
1 <%@page import="com.bie.service.impl.BookServiceImpl"%> 2 <%@page import="com.bie.service.BookService"%> 3 <%@page import="com.bie.po.Book"%> 4 <%@ page language="java" contentType="text/html; charset=UTF-8" 5 pageEncoding="UTF-8"%> 6 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 7 <html> 8 <head> 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 10 <title>處理圖書詳細信息的頁面</title> 11 </head> 12 <body> 13 <% 14 Book book=new Book(); 15 String sid=request.getParameter("id"); 16 Integer id=Integer.parseInt(sid); 17 BookService service=new BookServiceImpl(); 18 book.setBookid(id); 19 Book books=service.getBook(book); 20 21 session.setAttribute("book", books); 22 response.sendRedirect("detail.jsp"); 23 %> 24 </body> 25 </html>
1 <%@page import="com.bie.po.Book"%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>圖書詳細信息的頁面</title> 9 </head> 10 <body> 11 <% 12 Book book=(Book)session.getAttribute("book"); 13 %> 14 <div style="text-align:right;font-size:36px;"> 15 16 <a href="docart.jsp">個人購物車</a> 17 </div> 18 <table align="center" cellpadding="20" cellspacing="20"> 19 <tr> 20 <td>圖書編號</td> 21 <td>圖書名稱</td> 22 <td>圖書價格</td> 23 <td>圖書做者</td> 24 <td>圖書封皮</td> 25 <td>圖書出版社</td> 26 </tr> 27 <tr> 28 <td><%=book.getBookid() %></td> 29 <td><%=book.getBookname() %></td> 30 <td><%=book.getPrice() %></td> 31 <td><%=book.getAuthor() %></td> 32 <td><img src="images/<%=book.getPic() %>"></td> 33 <td><%=book.getPublish() %></td> 34 </tr> 35 <tr> 36 <td colspan="2"></td> 37 <td><a href="cart.jsp">添加到購物車</a></td> 38 <td><a href="book.jsp">圖書列表</a></td> 39 40 <td colspan="2"></td> 41 </tr> 42 </table> 43 </body> 44 </html>
10:寫好上面的detail.jsp而後就能夠在detail.jsp頁面點擊添加到購物車,下面實現購物車的功能,也是這個實現購物車的核心部分,參考的話是重點看的內容,固然在寫購物車以前還須要建立一個實體類CartItem.java,用於存放圖書的信息和購買的數量
1 package com.bie.po; 2 3 /** 4 * @author BieHongLi 5 * @version 建立時間:2017年2月27日 上午10:40:53 6 * 購物項 7 */ 8 public class CartItem { 9 10 private Book book;// 圖書對象的成員變量 11 private Integer number;// 購買的數量; 12 13 public Book getBook() { 14 return book; 15 } 16 17 public void setBook(Book book) { 18 this.book = book; 19 } 20 21 public Integer getNumber() { 22 return number; 23 } 24 25 public void setNumber(Integer number) { 26 this.number = number; 27 } 28 29 }
1 <%@page import="java.util.HashMap"%> 2 <%@page import="com.bie.po.CartItem"%> 3 <%@page import="java.util.Map"%> 4 <%@page import="com.bie.po.Book"%> 5 <%@ page language="java" contentType="text/html; charset=UTF-8" 6 pageEncoding="UTF-8"%> 7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 8 <html> 9 <head> 10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 11 <title>添加到購物車</title> 12 </head> 13 <body> 14 <% 15 //購物車功能 16 //1:首先考慮我購買的是哪一本書籍,這裏可使用id確認也可使用session中取出哪一本書籍 17 Book book=(Book)session.getAttribute("book"); 18 19 //2:考慮如何把書籍放到購物車中 20 //2.1:首先考慮是否有購物車,若是沒有,則建立,若是有直接使用 21 //2.2:其次先將購物車從session中拿出來,不存在就建立。 22 Map<Integer,CartItem> cart=(Map<Integer,CartItem>)session.getAttribute("cart"); 23 //若是沒有購物車,那麼建立,只有第一次訪問纔會操做 24 if(cart==null){ 25 //new一個購物車 26 cart=new HashMap<>(); 27 } 28 29 //3:考慮如何把書籍放到購物車中 30 //3.1:第一考慮購物車中是否有該書籍,因此先從購物車中獲取該書籍,若是爲空,那麼沒有該書籍 31 CartItem item=(CartItem)cart.get(book.getBookid()); 32 if(item==null){ 33 //若是購物車中不存在該書籍,那麼建立,且數量默認爲1 34 item=new CartItem(); 35 //將書籍放到購物車中 36 item.setBook(book); 37 //將書籍的默認數量爲1 38 item.setNumber(1); 39 }else{ 40 //若是購物車中以及有該書籍,那麼數量加1 41 item.setNumber(item.getNumber()+1); 42 } 43 44 //4:考慮如何把購物車項(即挑選的書籍是哪個和書本的數量)放到購物車中 45 cart.put(book.getBookid(),item); 46 47 //5:將購物車放到session中,方便後面取出來 48 session.setAttribute("cart", cart); 49 50 response.sendRedirect("book.jsp"); 51 %> 52 </body> 53 </html>
11:寫完上面的就能夠查看個人購物車了,在book.jsp頁面和detail.jsp頁面都有能夠點擊查看個人購物車的鏈接,而後就能夠查看個人購物車,完成購物車功能。
1 <%@page import="com.bie.po.CartItem"%> 2 <%@page import="java.util.Map"%> 3 <%@ page language="java" contentType="text/html; charset=UTF-8" 4 pageEncoding="UTF-8"%> 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6 <html> 7 <head> 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 9 <title>個人購物車的頁面</title> 10 </head> 11 <body> 12 <table width="100%" align="center" border="1px"> 13 <tr> 14 <th>書本編號</th> 15 <th>書本名稱</th> 16 <th>書本單價</th> 17 <th>書本數量</th> 18 <th>書本小計</th> 19 </tr> 20 <% 21 //1:將添加到購物車裏面的物品顯示出來 22 Map<Integer,CartItem> map=(Map<Integer,CartItem>)session.getAttribute("cart"); 23 //2:將購物車裏面的內容遍歷出來 24 double count=0;//顯示出總價格 25 for(Map.Entry<Integer,CartItem> entry : map.entrySet()){ 26 //計算出每同樣的書籍一共花了多少錢 27 double price=entry.getValue().getBook().getPrice() * entry.getValue().getNumber(); 28 //計算出一共花了多少錢 29 count=count+price; 30 %> 31 <tr align="center"> 32 <td><%=entry.getKey() %></td> 33 <td><%=entry.getValue().getBook().getBookname() %></td> 34 <td><%=entry.getValue().getBook().getPrice() %></td> 35 <td><%=entry.getValue().getNumber() %></td> 36 <td><%=entry.getValue().getBook().getPrice() * entry.getValue().getNumber()%></td> 37 38 </tr> 39 <%} %> 40 <tr> 41 <td colspan="4" align="right">價格總計</td> 42 <td><%=count %></td> 43 </tr> 44 </table> 45 <div style="text-align:center;font-size:36px;"> 46 <a href="book.jsp">圖書列表</a> 47 </div> 48 </body> 49 </html>
效果以下所示:
雖然簡陋,沒有徹底實現完,還待改善,繼續加油!!!