三层架构模式(MVC)案例:购物车实现

1.搭建开发环境
    1.1 导开发包
        jstl开发包
    1.2 建立程序开发包
    ...
    
2、开发实体

 2.1 创建封装实体的Javabean,

  2.1.1Book.java

 

public class Book {

    private String id;
    private String name;
    private String author;
    private double price;
    private String description;
    
    public Book() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Book(String id, String name, String author, double price,
            String description) {
        super();
        this.id = id;
        this.name = name;
        this.author = author;
        this.price = price;
        this.description = description;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

    2.1.1购物车Cart对象,Cart.java

import java.util.LinkedHashMap;
import java.util.Map;

//代表购物车
public class Cart {

    //用于保存购物车中所有商品
    private Map<String,CartItem> map = new LinkedHashMap();
    private double price;  //0
    
    public void add(Book book){  //javaweb
        
        CartItem item = map.get(book.getId());
        if(item!=null){
            item.setQuantity(item.getQuantity()+1);
        }else{
            item = new CartItem();
            item.setBook(book);
            item.setQuantity(1);
            map.put(book.getId(), item);
        }
        
    }
    
    
    public Map<String, CartItem> getMap() {
        return map;
    }
    public void setMap(Map<String, CartItem> map) {
        this.map = map;
    }
    public double getPrice() {
        double totalprice = 0;
        for(Map.Entry<String,CartItem> me : map.entrySet()){
            CartItem item = me.getValue();
            totalprice += item.getPrice();
        }
        return totalprice;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    
    
    
}

    2.1.3CartItem.java 完成购买哪本书,购买数量 功能

//cartItem代表某本书,并表示书出现多少次
public class CartItem {

    private Book book;
    private int quantity;
    private double price;
    
    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 double getPrice() {
        return book.getPrice()*this.quantity;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    
    
    
}

 2.2 创建一个类模拟数据库MyDb.java

import java.util.LinkedHashMap;
import java.util.Map;

import cn.itcast.domain.Book;


//模似数据库
public class MyDb {

    private static Map<String,Book> map = new LinkedHashMap();
    
    static{
        map.put("1", new Book("1","javaweb开发","老张",20,"一本经典的书"));
        map.put("2", new Book("2","jdbc开发","李勇",30,"一本jdbc的书"));
        map.put("3", new Book("3","spring开发","老黎",50,"一本相当经典的书"));
        map.put("4", new Book("4","hibernate开发","老佟",56,"一本佟佟的书"));
        map.put("5", new Book("5","struts开发","老毕",40,"一本经典的书"));
        map.put("6", new Book("6","ajax开发","老张",50,"一本老张的书"));
    }
    
    public static Map getAll(){
        return map;
    }
    
    
}

  2.3 实现Dao类,获取数据库数据BookDao.java

import java.util.Map;
import cn.itcast.db.MyDb;
import cn.itcast.domain.Book;

public class BookDao {

    public Map getAll(){    
        return MyDb.getAll();
    }
    
    public Book find(String id){
        return (Book) MyDb.getAll().get(id);
    }
    
}

3,开发Service 层

  3.1开发BusinessService.java完成业务处理功能

 

package cn.itcast.service;

import java.util.Map;

import cn.itcast.dao.BookDao;
import cn.itcast.domain.Book;
import cn.itcast.domain.Cart;
import cn.itcast.domain.CartItem;
import cn.itcast.exception.CartNotFoundException;

public class BusinessService {
    
    BookDao dao = new BookDao();
    
    //列出所有书的服务
    public Map getAllBook(){
        return dao.getAll();
    }

    public void buybook(String bookid, Cart cart) {
        Book book = dao.find(bookid);
        cart.add(book);
    }

    public void deleteBook(String bookid, Cart cart) throws CartNotFoundException {
        
        if(cart==null){
            throw new CartNotFoundException("购物车为空!!");
        }
        
        Map map = cart.getMap();
        map.remove(bookid);
    }

    public void clearCart(Cart cart) throws CartNotFoundException {
        if(cart==null){
            throw new CartNotFoundException("购物车为空!!");
        }
        
        cart.getMap().clear();
        
    }

    public void updateCart(Cart cart, String bookid, int quantity) throws CartNotFoundException {

        if(cart==null){
            throw new CartNotFoundException("购物车为空!!");
        }
        CartItem item = cart.getMap().get(bookid);
        item.setQuantity(quantity);
        
    }
    
}

  3.2 开发自定义异常类 CartNotFoundException.java

package cn.itcast.exception;

public class CartNotFoundException extends Exception {

    public CartNotFoundException() {
        // TODO Auto-generated constructor stub
    }

    public CartNotFoundException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public CartNotFoundException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    public CartNotFoundException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

}

4,Web层开发Servlet与用户界面层

  4.1 实现购买功能的Servlet :BuyServlet.java

package cn.itcast.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.domain.Cart;
import cn.itcast.service.BusinessService;
//完成购买操作
public class BuyServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String bookid = request.getParameter("bookid");
        
        //把用户买的书加到购物车中
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if(cart==null){
            cart = new Cart();
            request.getSession().setAttribute("cart", cart);
        }
        
        
        BusinessService service = new BusinessService();
        service.buybook(bookid,cart);
        
        request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
        
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

}

  4.2 实现清空购物车Servlet:ClearCartServlet.java

package cn.itcast.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.domain.Cart;
import cn.itcast.exception.CartNotFoundException;
import cn.itcast.service.BusinessService;

public class ClearCartServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Cart cart = (Cart) request.getSession().getAttribute("cart");
        BusinessService service = new BusinessService();
        try {
            service.clearCart(cart);
            request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
        } catch (CartNotFoundException e) {
            request.setAttribute("message", "对不起,您还没有购买任何商品!!!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

}

  4.3 删除购买书的Servlet:DeleteServlet.java

package cn.itcast.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.domain.Cart;
import cn.itcast.exception.CartNotFoundException;
import cn.itcast.service.BusinessService;

public class DeleteServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String bookid = request.getParameter("bookid");
        
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        
        BusinessService service = new BusinessService();
        try {
            service.deleteBook(bookid,cart);
            request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
            
        } catch (CartNotFoundException e) {
            request.setAttribute("message", "对不起,您还没有购买任何商品!!!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
        
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

}

  4.4 实现购买首页书本列表Servlet;ListBookServlet.java

package cn.itcast.web.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.service.BusinessService;

//列出所有书
public class ListBookServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        BusinessService service = new BusinessService();
        Map map = service.getAllBook();
        request.setAttribute("map", map);    
        request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

}

  4.5 更新修改购买书本数量Servlet: UpdateCartServlet.java

package cn.itcast.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.domain.Cart;
import cn.itcast.exception.CartNotFoundException;
import cn.itcast.service.BusinessService;

public class UpdateCartServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String bookid = request.getParameter("bookid");
        int quantity = Integer.parseInt(request.getParameter("quantity"));
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        
        BusinessService service = new BusinessService();
        
        try {
            service.updateCart(cart,bookid,quantity);
            request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
            
        } catch (CartNotFoundException e) {
            request.setAttribute("message", "对不起,您还没有购买任何商品!!!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
        
    }
    
    

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

}

5. 购物车JSP显示页面

  5.1 listbook.jsp  用到jstl.jar  

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>为 JSTL 中导入标签库的taglib导入,这个需要注意,不能忘记!!
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>书籍列表页面</title>
  </head>
  
  <body style="text-align: center;">
    <br/>
    <h2>书籍列表</h2>
    <br/><br/>
    <table border="1" width="80%">
        <tr>
            <td>书籍编号</td>
            <td>书名</td>
            <td>作者</td>
            <td>售价</td>
            <td>描述</td>
            <td>操作</td>
        </tr>
        
        <%-- Set<Map.Entry<String,Book>> --%> 
        <c:forEach var="me" items="${map}">
            <tr>
                <td>${me.key }</td>
                <td>${me.value.name }</td>
                <td>${me.value.author }</td>
                <td>${me.value.price }</td>
                <td>${me.value.description }</td>
                <td>
                    <a href="${pageContext.request.contextPath }/servlet/BuyServlet?bookid=${me.key }">购买</a>
                </td>
            </tr>
        </c:forEach>
        
    
    </table>
    
    
  </body>
</html>

  5.2 listcart.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'listcart.jsp' starting page</title>
    <script type="text/javascript">
        function clearcart(){
            var b = window.confirm("您确定要清空购物车吗??");
            if(b){
                window.location.href="${pageContext.request.contextPath}/servlet/ClearCartServlet";
            }
        }
        
        function updateCart(input,id,oldvalue){
            var quantity = input.value;
            //alert(quantity);
            if(quantity.match(/^[0-9]*[1-9][0-9]*$/)){
                var b = window.confirm("请确认改为:" + quantity);
                if(b){
                window.location.href="${pageContext.request.contextPath}/servlet/UpdateCartServlet?bookid="+id + "&quantity=" + quantity;
                }else{
                input.value=oldvalue;  //发现用户取消的话,把input输入值改为原始值
                }
            }else{
                alert("请输入正确购买数量");
                input.value=oldvalue;
            }
            
        }
    </script>
    
  </head>
  
  <body style="text-align: center;">
    <br/>
    <h2>购物车列表</h2>
    <br/><br/>
    
   <c:if test="${!empty(cart.map)}">
    
    <table border="1" width="80%">
        <tr>
            <td>书名</td>
            <td>作者</td>
            <td>单价</td>
            <td>数量</td>
            <td>小计</td>
            <td>操作</td>
        </tr>
        
        <c:forEach var="me" items="${cart.map }">
            
            <tr>
                <td>${me.value.book.name }</td>
                <td>${me.value.book.author }</td>
                <td>${me.value.book.price }</td>
                <td>
                    <input type="text" name="quantity" value="${me.value.quantity }" style=" 30px" 
            onchange
="updateCart(this,${me.value.book.id },${me.value.quantity })"> </td> <td>${me.value.price }</td> <td> <a href="${pageContext.request.contextPath }/servlet/DeleteServlet?bookid=${me.value.book.id }">删除</a> </td> </tr> </c:forEach> <tr> <td colspan="2"> <a href="javascript:clearcart()">清空购物车</a> </td> <td colspan="2">合计</td> <td colspan="2">${cart.price }</td> </tr> </table> </c:if> <c:if test="${empty(cart.map)}"> 对不起,您还没有购买任何商品 </c:if> </body> </html>

  5.3 全局消息处理页面 message.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>全局消息显示</title>
  </head>
  
  <body>
    ${message }
  </body>
</html>

6,界面效果

ListBookServlet 首页

购物车界面

原文地址:https://www.cnblogs.com/lichone2010/p/3143269.html