天天看点

MVC简易购物车项目--购物大厅

前面用户验证成功以后跳转到hall.jsp,展示商品

hall.jsp

<%@ page language="java" import="java.util.*,com.wxh.domain.*"  contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body style="text-align:center; margin:0 auto; ">
    <h1>欢迎来到购物大厅</h1>
     <table style="border-collapse: collapse; width: 500px"  align="center">
    <tr><th>书名</th><th>价格</th><th>出版社</th><th>点击购买</th></tr>
    
    <%
    //取出request中的那个Araylist
    ArrayList al=(ArrayList)request.getAttribute("books");
    for(int i=0;i<al.size();i++){
    Book book=(Book)al.get(i);
    %>    
  
    <tr><td><%=book.getName()%></td><td><%=book.getPrice() %></td><td><%=book.getPublishHouse() %></td>
   	<td>
     <a href="/shopping/ShoppingClServlet?type=add&id=<%=book.getId()%>" target="_blank" rel="external nofollow"  >点击购买</a> 
    </td>
    </tr>    
    <%
        }    
    %>   
   
    <tr align="center"><td colspan="4"><input type="button" value="查看购物车"  οnclick="window.location.href='/shopping/ShoppingClServlet?type=show';"></td></tr>    
    </table>
    <hr/>
    <a href="/shopping/" target="_blank" rel="external nofollow" >返回重新登录</a>
  </body>
</html>
           

在GoHallUI中已经给下一个页面hall.jsp准备要了显示的数据

调用了BookService类

首先

Book.java

package com.wxh.domain;

public class Book {
	private int id;
	private String name;
	private String publishHouse;
	private double price;
	private int nums; //该书的库存
	private int shoppingNum=1;	//购买的数量
	private String author;	
	
	public int getShoppingNum() {
		return shoppingNum;
	}
	public void setShoppingNum(int shoppingNum) {
		this.shoppingNum = shoppingNum;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	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 String getPublishHouse() {
		return publishHouse;
	}
	public void setPublishHouse(String publishHouse) {
		this.publishHouse = publishHouse;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public int getNums() {
		return nums;
	}
	public void setNums(int nums) {
		this.nums = nums;
	}	
}
           

BookService.java

package com.wxh.service;
import java.util.ArrayList;
import com.wxh.domain.Book;
import com.wxh.utils.SqlHelper;

//这是一个业务逻辑类,用于处理与book表相关的业务,各司其职
public class BookService {	
	
	//根据书的编号,返回一个Book
	public Book getBookById(String id){
		Book book=new Book();
		String sql="select * from book where id=?";
		String paras[]={id};
		ArrayList al=new SqlHelper().executeQuery(sql, paras);
		if(al.size()==1){
			Object[] obj=(Object[])al.get(0);			
			book.setId(Integer.parseInt(obj[0].toString()));
			book.setName(obj[1].toString());
			book.setAuthor(obj[2].toString());
			book.setPublishHouse(obj[3].toString());
			book.setPrice(Float.parseFloat(obj[4].toString()));
			book.setNums(Integer.parseInt(obj[5].toString()));					
		}
		return book;
	}
	
	
	//得到所有的书籍信息(分页)
	public ArrayList getAllBook(){
		String sql="select * from book where 1=?";
		String paras[]={"1"};
		ArrayList al=new SqlHelper().executeQuery(sql, paras);
		ArrayList<Book> newAl=new ArrayList<Book>();
		//二次业务封装
		for(int i=0;i<al.size();i++){			
			Object obj[]=(Object[])al.get(i);
			Book book=new Book();
			book.setId(Integer.parseInt(obj[0].toString()));
			book.setName(obj[1].toString());
			book.setAuthor(obj[2].toString());
			book.setPublishHouse(obj[3].toString());
			book.setPrice(Float.parseFloat(obj[4].toString()));
			book.setNums(Integer.parseInt(obj[5].toString()));
			newAl.add(book);
		}
		return newAl;		
	}
}
           

购买功能的实现

在GOHallUI中已经创建了一个购物车

MyCart.java

package com.wxh.service;
import java.util.*; 
import com.wxh.domain.Book;

//这个表示我的购物车
public class MyCart {	
	HashMap<String,Book> hm=new HashMap<String,Book>();
	
	//添加书的第二个方法
	public void addBook2(String id){
		if(hm.containsKey(id)){
			//hm已经有这个书
			Book book=hm.get(id);
			int shoppingNum=book.getShoppingNum();
			book.setShoppingNum(shoppingNum+1);
		}else{
			hm.put(id, new BookService().getBookById(id));
		}
	}
	
	//返回该购物车的总价格
	public float getTotalPrice(){
		float totalPrice=0.0f;
		
		//得到总价格
		ArrayList<Book> al=new ArrayList<Book>();
		Iterator it=hm.keySet().iterator();
		while(it.hasNext()){
			//取出书号
			String bookId=(String)it.next();
			//取出书号对应的Book
			Book book=hm.get(bookId);
			totalPrice+=book.getPrice()*book.getShoppingNum();
			
		}
		
		return totalPrice;
	}
	
	//添加书籍
	public void addBook(String id,Book book){
		if(hm.containsKey(id)){
			book=hm.get(id);
			//如果这本书已经购买过,shoppingNum数量+1
			int shoppingNum=book.getShoppingNum();
			book.setShoppingNum(shoppingNum+1);
			//hm.put(id, book);
		}else{		
		   hm.put(id, book);
		}
		
	}
	//删除书籍
	public void delBook(String id){
		hm.remove(id);
	}
	
	//更新书籍(对于购物车,更新所买书籍的数量)
	public void updateBook(String id,String nums){
		//取出id对应的Book
		Book book=hm.get(id);
		book.setShoppingNum(Integer.parseInt(nums));	
		
	}
	//显示该购物车中的所有商品信息
	public ArrayList showMyCart(){
		ArrayList<Book> al=new ArrayList<Book>();
		
		//遍历HashMap		
		Iterator it=hm.keySet().iterator();
		while(it.hasNext()){
			//取出key
			String id=(String)it.next();
			//取出Book
			Book book=hm.get(id);
			al.add(book);			
		}
		return al;
	}
	
	
	//清空书,清空购物车
	public void clearBook(){
		hm.clear();
	}

}
           

当点击 点击购买 链接时 提交给ShoppingClServlet处理

ShoppingClServlet.java

//该控制器处理用户购买商品的请求
public class ShoppingClServlet extends HttpServlet {	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		//接收type值,区分用户希望做什么,del,update,add
		String type=request.getParameter("type");
		if(type.equals("del")){
			//说明用户要删除商品
			//接收用户想购买的商品的id
			String id=request.getParameter("id");
			//得到购物车(从session中取得购物车)
			MyCart myCart=(MyCart)request.getSession().getAttribute("myCart");
			myCart.delBook(id);
			//把要显示的商品信息放入request
			request.setAttribute("bookList", myCart.showMyCart());
			
			//跳回showMyCart.jsp
			request.getRequestDispatcher("/WEB-INF/showMyCart.jsp").forward(request, response);
			
		}else if(type.equals("add")){
			//接收用户想购买的商品的id		
			String id=request.getParameter("id");
			System.out.println(id);
			
			//什么时候创建购物车对象(当用户登录成功后,为他创建一个购物车)
			//取出购物车,并添加书到购物车中
			MyCart myCart=(MyCart)request.getSession().getAttribute("myCart");			
			//相当于把商品加到购物车
			myCart.addBook2(id);		
			/*
			//把要显示的数据放入request,准备显示。
			request.setAttribute("bookList", myCart.showMyCart());
			
			request.setAttribute("totalPrice", myCart.getTotalPrice()+"");
			//跳转到显示我的购物车去
			request.getRequestDispatcher("/WEB-INF/showMyCart.jsp").forward(request, response);
			*/
			//为了防止某个页面刷新,我们可以用sendredirect()
			response.sendRedirect("/shopping/GoShowMyCart");
			
			
		}else if(type.equals("update")){
			//更新
			//判断有没有书籍		
			
			//得到用户希望更新的书号和数量
			String bookIds[]=request.getParameterValues("id");
			//得到每本书的数量
			String nums[]=request.getParameterValues("booknum");
			MyCart myCart=(MyCart)request.getSession().getAttribute("myCart");
			for(int i=0;i<bookIds.length;i++){
				//更新购物车
				myCart.updateBook(bookIds[i], nums[i]);
			}
			//跳转回我的购物车
			//把要显示的数据放入request,准备显示。
			request.setAttribute("bookList", myCart.showMyCart());
			
			request.setAttribute("totalPrice", myCart.getTotalPrice()+"");
			//跳转到显示我的购物车去
			request.getRequestDispatcher("/WEB-INF/showMyCart.jsp").forward(request, response);	
		}	
	}	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
           

————摘自《韩顺平细说jsp》