Java servlet 實現的簡易購物車
阿新 • • 發佈:2018-11-22
首頁
2.購買頁
3.購物車頁
1. 首頁程式碼 傳送一個post請求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<img src="/img/bookcover/shoping.png" alt="購物">
<form action="goshop.do" method="post">
<p>歡迎您</p><br>
<input type="submit" value="進入購物">
</form>
</body>
</html>
2.處理首頁post請求的controler
package cc.openhome.controler;
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;
import java.util.LinkedHashMap;
@WebServlet("/goshop.do")
public class GoShop extends HttpServlet {
void processRequest(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
BookDb bs = new BookDb();
LinkedHashMap<String,Book> books = bs.getAll();
req.setAttribute("books",books);
req.getRequestDispatcher("shop.view").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp);
}
}
3 ,展示購物頁面
package cc.openhome.view;
import cc.openhome.controler.*;
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.io.PrintWriter;
import java.util.LinkedHashMap;
@WebServlet("/shop.view")
public class ShopView extends HttpServlet {
protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
String bookid = req.getParameter("bookid");
int count = 0;
HttpSession session = req.getSession();
// 在點選了購買之後書的數量在加一,否則只重新整理
if(session.getAttribute("count") != null && bookid != null){
Integer c = (Integer) session.getAttribute("count");
count = c + 1;
}
session.setAttribute("count",count);
//購物
Cart cart = (Cart) req.getSession().getAttribute("cart");
if(cart == null){
cart = new Cart();
req.getSession().setAttribute("cart",cart);
}
BusinessService bussiness = new BusinessService();
if(count > 0){
bussiness.buyBook(bookid,cart);
}
session.setAttribute("cart",cart);
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01'" +
"Transitional//EN");
out.println("<html>");
out.println("<head>");
out.println("<title>購物網頁</title>");
out.println("</head>");
out.println("<body>");
out.println("<form action='' method='post'>");
out.println("<table width='100%'>");
out.println("<td><img src='img/bookcover/shop.png' alt='小購物車' width='50'>" +
"<a href='cart.view'>已採購"+count+"書籍</a><td>");
out.println("</table>");
out.println("<table width='100%'>");
out.println("<tr>");
out.println("<td style='color:blue'>書籍編號<td>");
out.println("<td style='color:blue'>書名<td>");
out.println("<td style='color:blue'>圖片</td>");
out.println("<td style='color:blue'>價格<td>");
out.println("<td style='color:blue'>購買<td>");
out.println("</tr>");
int i = 0;
LinkedHashMap <String,Book> books = (LinkedHashMap <String,Book>) req.getAttribute("books");
for (String value : books.keySet()){
i++;
Book book = books.get(value);
out.println("<tr>");
out.println("<td>"+book.getId()+"<td>");
out.println("<td>"+book.getName()+"<td>");
out.println("<td><img src='/img/bookcover/book"+i+".jpeg'></td>");
out.println("<td>"+book.getPrice()+"<td>");
out.println("<td><a href='"+resp.encodeURL("goshop.do")+"?bookid="+book.getId()+"'>購買此書</a><td>");
out.println("<tr>");
}
/*
int i,j = 0,k = 0;
int len = books.size();
for(i = 0;i < len; i++,j++,k++){
if(j % 3 == 0){
out.println("<tr>");
}
out.println("<td>");
out.println("<img src='/img/bookcover/book"+i+".jpeg'>");
out.println("</td>");
if(k % 3 == 0){
out.println("</tr>");
}
}
j = 0;
k = 0;
for( i = 0;i < len; i++,j++,k++){
if(j % 3 == 0){
out.println("<tr>");
}
out.println("<td>");
out.println("<a href='#'>購買此書</a>");
out.println("</td>");
if(k % 3 == 0){
out.println("</tr>");
}
}
*/
out.println("</table>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
}
4.購物車頁面
package cc.openhome.controler;
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.io.PrintWriter;
import java.util.Map;
@WebServlet("/cart.view")
public class CartShow extends HttpServlet {
public void processRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html;charset=UTF-8");
HttpSession session = req.getSession();
Cart carts = (Cart) session.getAttribute("cart");
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01'" +
"Transitional//EN");
out.println("<html>");
out.println("<head>");
out.println("<title>購物結算</title>");
out.println("</head>");
out.println("<body>");
out.println("<form action='' method='post'>");
out.println("<table width='100%'>");
out.println("<td><img src='img/bookcover/shoping.png' alt='購物車' width='100'>");
out.println("</table>");
out.println("<table width='100%'>");
out.println("<tr>");
out.println("<td style='color:blue'>書籍編號<td>");
out.println("<td style='color:blue'>書名<td>");
out.println("<td style='color:blue'>圖片</td>");
out.println("<td style='color:blue'>單價<td>");
out.println("<td style='color:blue'>數量<td>");
out.println("<td style='color:blue'>單本書總價<td>");
out.println("</tr>");
int i = 0;
Map<String,CartItem> bookmap = carts.getBookMap();
for (String value : bookmap.keySet()){
i++;
CartItem citem = bookmap.get(value);
Book bk = citem.getBook();
out.println("<tr>");
out.println("<td>"+bk.getId()+"<td>");
out.println("<td>"+bk.getName()+"<td>");
out.println("<td><img src='/img/bookcover/book"+i+".jpeg'></td>");
out.println("<td>"+bk.getPrice()+"<td>");
out.println("<td>"+citem.getQuantity()+"<td>");
out.println("<td>"+citem.getPrice()+"<td>");
out.println("</tr>");
}
out.println("<tr>");
out.println("<td style='color:green';font-size:200%'>總價</td>");
out.println("<td style='color:green';font-size:200%'> "+carts.getPrice()+"</td>");
out.println("</tr>");
out.println("</table>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
}
5,書籍類
package cc.openhome.controler;
import java.util.ArrayList;
public class Book {
private String id;
private String name;
private double price;
public Book(){
}
public Book(String id,String name, double price){
this.id = id;
this.name = name;
this.price = price;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
6,單個購物車類
package cc.openhome.controler;
public class CartItem {
private Book book;
private int quantity;
private double price;
public double getPrice() {
return book.getPrice() * this.quantity;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setPrice(double price) {
this.price = price;
}
}
7,購物車類
package cc.openhome.controler;
import java.util.LinkedHashMap;
import java.util.Map;
public class Cart {
private Map<String,CartItem> bookMap = new LinkedHashMap<>();
private double price;
public void addBook(Book book){
CartItem cartItem = bookMap.get(book.getId());
if(cartItem == null){
cartItem = new CartItem();
cartItem.setBook(book);
cartItem.setQuantity(1);
bookMap.put(book.getId(),cartItem);
}else {
cartItem.setQuantity(cartItem.getQuantity() + 1);
}
}
public double getPrice() {
double totalPrice = 0;
for(Map.Entry<String,CartItem> me : bookMap.entrySet()){
CartItem cartItem = me.getValue();
totalPrice += cartItem.getPrice();
}
return totalPrice;
}
public Map<String, CartItem> getBookMap() {
return bookMap;
}
public void setBookMap(Map<String, CartItem> bookMap) {
this.bookMap = bookMap;
}
public void setPrice(double price) {
this.price = price;
}
}
8圖書資料來源
package cc.openhome.controler;
import java.util.LinkedHashMap;
public class BookDb {
private LinkedHashMap<String,Book> map = new LinkedHashMap<>();
public BookDb(){
map.put("1",new Book("1","java程式設計",10.00));
map.put("2",new Book("2","C++程式設計",10.00));
map.put("3",new Book("3","C程式設計",10.00));
}
public LinkedHashMap<String,Book> getAll(){
return map;
}
public Book findBook(String id){
return map.get(id);
}
}
總結:對於個人而言:難點在於
1.頁面資料的展示.
2.使用resp.encodeurl 在本頁面重新整理.
3.使用<a href> 重定向並且帶了一個引數,把書的id傳送給本頁面處理.
4.http session 來儲存傳送資料.
5.書籍,購物車類的設計.