您的位置:首页 > 编程语言

MVC中编写的购物车代码

2012-11-16 19:55 260 查看
BookDao.java

package com.bhsi.dao;

import java.util.List;

import java.util.Map;

import com.hbsi.domain.Book;

public interface BookDao {

public Book find(String id);

public List<Book> getALL();

}

BookDaoImpl.java

package com.hbsi.dao.impl;

import java.sql.*;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import com.bhsi.dao.BookDao;

import com.hbsi.domain.Book;

import com.hbsi.utils.DBManager;

public class BookDaoImpl implements BookDao{

@Override

public Book find(String id) {

Connection conn = null;

PreparedStatement st = null;

ResultSet rs = null;

try {

conn = DBManager.getConnection();

String sql = "select * from book where id=?";

st = conn.prepareStatement(sql);

st.setString(1, id);

rs = st.executeQuery();

if (rs.next()) {

Book b = new Book();

b.setId(rs.getString("id"));

b.setName(rs.getString("name"));

b.setPrice(rs.getDouble("price"));

b.setAuthor(rs.getString("author"));

b.setDescription(rs.getString("description"));

return b;

}

return null;

} catch (SQLException e) {

throw new RuntimeException(e);

} finally {

DBManager.colseDb(conn, st, rs);

}

}

@Override

public List<Book> getALL() {

Connection conn = null;

PreparedStatement st = null;

ResultSet rs = null;

try {

conn = DBManager.getConnection();

String sql = "select * from book";

st = conn.prepareStatement(sql);

rs = st.executeQuery();

List<Book> list = new ArrayList<Book>();

while (rs.next()) {

Book b = new Book();

b.setId(rs.getString("id"));

b.setName(rs.getString("name"));

b.setPrice(rs.getFloat("price"));

b.setAuthor(rs.getString("author"));

b.setDescription(rs.getString("description"));

list.add(b);

}

return list;

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

DBManager.colseDb(conn, st, rs);

}

}

}

Book.java

package com.hbsi.domain;

import java.io.Serializable;

public class Book implements Serializable{

/**

*

*/

private static final long serialVersionUID = 1L;

private String id;

private String name;

private double price;

private String author;

private String 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 double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

public String getAuthor() {

return author;

}

public void setAuthor(String author) {

this.author = author;

}

public String getDescription() {

return description;

}

public void setDescription(String description) {

this.description = description;

}

}

Cart.java

package com.hbsi.domain;

import java.util.LinkedHashMap;

import java.util.Map;

//购物车

public class Cart {

//private Map<String,Book> map = new LinkedHashMap<String, Book>();

//用户会买一本书多本,会出现重复的书,要使用购物项,避免重复书出现。

private Map<String,CartItem> map = new LinkedHashMap<String, CartItem>();

private double price; //总计

public void add(Book book){

//首先判断要买的书是否已经在购物车里

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()){

totalprice = totalprice+me.getValue().getPrice();

}

this.price=totalprice;

return price;

}

public void setPrice(double price) {

this.price = price;

}

}

CartItem .java

package com.hbsi.domain;

//用于封装某本书,并表示这本书买了多少次

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;

this.price = this.book.getPrice()*this.quantity;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

}

BusinessServiceImpl.java

package com.hbsi.service.impl;

import java.util.List;

import com.bhsi.dao.BookDao;

import com.hbsi.dao.impl.BookDaoImpl;

import com.hbsi.domain.Book;

import com.hbsi.domain.Cart;

import com.hbsi.domain.CartItem;

import com.hbsi.service.BusinessService;

public class BusinessServiceImpl implements BusinessService {

BookDao dao = new BookDaoImpl();

@Override

public List<Book> getAllBook() {

return dao.getALL();

}

@Override

public void buyBook(String id, Cart cart) {

Book book = dao.find(id);

cart.add(book);

}

@Override

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

CartItem item = cart.getMap().get(bookid);

item.setQuantity(Integer.parseInt(quantity));

}

@Override

public void deleteCartItem(Cart cart, String id) {

cart.getMap().remove(id);

}

@Override

public void clearCart(Cart cart) {

cart.getMap().clear();

}

}

BusinessService.java

package com.hbsi.service;

import java.util.List;

import com.hbsi.domain.Book;

import com.hbsi.domain.Cart;

public interface BusinessService {

//获取所有的书的服务

public List<Book> getAllBook();

//帮助用户完成书籍的购买

public void buyBook(String id,Cart cart);

//更新购物车中的书籍数量

public void updateCart(Cart cart, String bookid, String quantity);

//删除购物车中的书籍

public void deleteCartItem(Cart cart, String id);

//清空购物车中的书籍

public void clearCart(Cart cart);

}

DBManager.java

package com.hbsi.utils;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Properties;

import com.mysql.jdbc.Driver;

public class DBManager {

private static String username;

private static String password;

private static String url;

private static String driver;

static{

try{

InputStream in = DBManager.class.getClassLoader().getResourceAsStream("db.properties");

Properties prop = new Properties();

prop.load(in);

driver = prop.getProperty("driver");

url = prop.getProperty("url");

username = prop.getProperty("username");

password = prop.getProperty("password");

Class.forName(driver);

}catch (Exception e) {

throw new ExceptionInInitializerError(e);

}

}

public static Connection getConnection() throws SQLException{

return DriverManager.getConnection(url, username, password);

}

public static void colseDb(Connection conn,Statement st,ResultSet rs){

if(rs!=null){

try{

rs.close();

}catch (Exception e) {e.printStackTrace();}

rs = null;

}

if(st!=null){

try{

st.close();

}catch (Exception e) {e.printStackTrace();}

st = null;

}

if(conn!=null){

try{

conn.close();

}catch (Exception e) {e.printStackTrace();}

conn = null;

}

}

}

BuyServlet.java

package com.hbsi.web.controller;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.hbsi.domain.Cart;

import com.hbsi.domain.CartItem;

import com.hbsi.service.BusinessService;

import com.hbsi.service.impl.BusinessServiceImpl;

public class BuyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

String id = request.getParameter("id");

Cart cart = (Cart) request.getSession().getAttribute("cart");

if(cart==null){

cart = new Cart();

request.getSession().setAttribute("cart",cart);

}

BusinessServiceImpl service = new BusinessServiceImpl();

service.buyBook(id,cart);

//request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);

request.getRequestDispatcher("/listcart.jsp").forward(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

ClearCartServlet.java

package com.hbsi.web.controller;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.hbsi.domain.Cart;

import com.hbsi.service.impl.BusinessServiceImpl;

public class ClearCartServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

Cart cart = (Cart) request.getSession().getAttribute("cart");

BusinessServiceImpl service = new BusinessServiceImpl();

service.clearCart(cart);

// request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request,

// response);

request.getRequestDispatcher("/listcart.jsp")

.forward(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

DeleteBookServlet.java

package com.hbsi.web.controller;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.hbsi.domain.Cart;

import com.hbsi.service.impl.BusinessServiceImpl;

public class DeleteBookServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String id = request.getParameter("id");

Cart cart = (Cart) request.getSession().getAttribute("cart");

BusinessServiceImpl service = new BusinessServiceImpl();

service.deleteCartItem(cart, id);

// request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request,

// response);

request.getRequestDispatcher("/listcart.jsp")

.forward(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

ListBookServlet.java

package com.hbsi.web.controller;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.hbsi.domain.Book;

import com.hbsi.service.BusinessService;

import com.hbsi.service.impl.BusinessServiceImpl;

public class ListBookServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

BusinessService service = new BusinessServiceImpl();

List<Book> list = service.getAllBook();

request.setAttribute("books", list);

// request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp").forward(request,response);

request.getRequestDispatcher("/listbook.jsp")

.forward(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

UpdateCartServlet.java

package com.hbsi.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 com.hbsi.domain.Cart;

import com.hbsi.service.BusinessService;

import com.hbsi.service.impl.BusinessServiceImpl;

public class UpdateCartServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String bookid = request.getParameter("bookid");

String quantity = request.getParameter("quantity");

Cart cart = (Cart) request.getSession().getAttribute("cart");

BusinessServiceImpl service = new BusinessServiceImpl();

service.updateCart(cart, bookid, quantity);

// request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request,

// response);

request.getRequestDispatcher("/listcart.jsp")

.forward(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

listbook.jsp

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

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>显示所有的书</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body style="text-align:center">

<h2>我的书店</h2>

<table border="1" width="80%">

<tr>

<td>编号</td>

<td>书名</td>

<td>作者</td>

<td>价格</td>

<td>描述</td>

<td>操作</td>

</tr>

<c:forEach var="book" items="${books}">

<tr>

<td>${book.id}</td>

<td>${book.name}</td>

<td>${book.author}</td>

<td>${book.price}</td>

<td>${book.description}</td>

<td>

<a href="${pageContext.request.contextPath}/servlet/BuyServlet?id=${book.id}">购买</a>

</td>

</tr>

</c:forEach>

</table>

</body>

</html>

listcart.jsp

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

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>购物车显示页面</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

<script>

function doDelete(id){

var b = window.confirm("您确定删除吗??");

if(b){

window.location.href="${pageContext.request.contextPath }/servlet/DeleteBookServlet?id="+id;

}

}

function clearCart(){

var b = window.confirm("您确定清空吗??");

if(b){

window.location.href="${pageContext.request.contextPath }/servlet/ClearCartServlet";

}

}

function updateCart(input,bookid,oldvalue){

var b = window.confirm("您确定修改吗??");

if(b){

var quantity = input.value;

if(quantity==""){

alert("请输入数字!!");

input.value=oldvalue;

return;

}

if(!quantity.match("\\d+")){

alert("请输入数字!!");

input.value=oldvalue;

return;

}

if(quantity<1){

alert("请输入有效数字!!");

input.value=oldvalue;

return;

}

window.location.href='${pageContext.request.contextPath}/servlet/UpdateCartServlet?bookid='+bookid+'&quantity='+quantity;

}else{

input.value=oldvalue;

}

}

</script>

</head>

<body style="text-align:center">

<h2>您购买了如下商品</h2>

<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.key}</td>

<td>${me.value.book.name}</td>

<td>${me.value.book.price}</td>

<td>

<input type="text" value="${me.value.quantity}" onchange="updateCart(this,${me.key },${me.value.quantity})" style="width:35px;">

</td>

<td>${me.value.price}</td>

<td>

<a href="javascript:void(0)" onclick="doDelete(${me.key })">删除</a>

</td>

</tr>

</c:forEach>

<tr>

<td><a href="javascript:void(0)" onclick="clearCart()">清空购物车</a></td>

<td><a href="servlet/ListBookServlet">继续选书</a></td>

<td colspan="2">总价</td>

<td colspan="2">${cart.price }元</td>

</tr>

</table>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: