jsp课程(7)---jsp+servlet+javabean 实现的简单网上购物车
简单购物车案例(附源码)
下面具体流程,很多功能都还未完善,之后会实现更多功能,例如分页,付款等 敬请期待
使用jsp的MVC模型开发购物车(jsp+servlet+javabean)
必须有三层架构思想:web层负责与用户打交道业务处理层(服务层service)数据访问层(dao)
1.搭建开发环境
1)导入开发包:jdbc驱动(jstl的jar包)
2)创建程序所在的包,如下:
3)在MYSQL下创建库和表字段有:book,name,author,price,description
2.编码
1)开发实体类bean:Book
2)开发dao(创建工具类)
3)开发service
4)web层
3.实现效果如下:
1)在浏览器输入:http://localhost:8080/bookstore/后如下图:
2)进入后显示图书列表
3)加入两种书进入购物车后
4)当点击删除后
5)点击清空购物车后
6)结算功能还未实现
4.附源码:
//BookDao.java
package com.hbsi.dao;
import java.util.List;
import com.hbsi.domain.Book;
public interface BookDao {
//获取所有的书
public List<Book> getAll();
//根据id获取书
public Book find(String id);
}
//BookDaoImpl.java
package com.hbsi.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
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 pt = null;
ResultSet rs = null;
try {
conn = DBManager.getConnection();
String sql = "select * from book where id=?";
pt = conn.prepareStatement(sql);
pt.setString(1, id);
rs = pt.executeQuery();
//Book b = null;
if(rs.next()){
Book b = new Book();
b.setId(rs.getString("id"));
b.setName(rs.getString("name"));
b.setAuthor(rs.getString("author"));
b.setPrice(rs.getDouble("price"));
b.setDescription(rs.getString("description"));
return b;
}
return null;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
DBManager.closeDB(conn, pt, rs);
}
}
@Override
public List<Book> getAll() {
Connection conn = null;
PreparedStatement pt = null;
ResultSet rs = null;
try {
conn = DBManager.getConnection();
String sql = "select id,name,author,price,description from book";
pt = conn.prepareStatement(sql);
rs = pt.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.setAuthor(rs.getString("author"));
b.setPrice(rs.getDouble("price"));
b.setDescription(rs.getString("description"));
list.add(b);
}
return list;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
DBManager.closeDB(conn, pt, rs);
}
}
}
//Book.java
package com.hbsi.domain;
public class Book {
private String id;
private String name;
private String author;
private double price;
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 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;
}
}
//Cart.java
package com.hbsi.domain;
import java.util.LinkedHashMap;
import java.util.Map;
public class Cart {
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集合中
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();
}
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;
}
}
//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();
//获取指定id的书
public Book findBook(String id);
//删除购物项
public void deleteCartItem(String sid, Cart cart);
//清空购物车
public void clearCart(Cart cart);
//改变数量
public void changeQuantity(String sid, String quantity, Cart cart);
}
//BusinessServiceImpl.java
package com.hbsi.service;
import java.util.List;
import com.hbsi.dao.BookDao;
import com.hbsi.dao.BookDaoImpl;
import com.hbsi.domain.Book;
import com.hbsi.domain.Cart;
import com.hbsi.domain.CartItem;
public class BusinessServiceImpl implements BusinessService{
BookDao dao=new BookDaoImpl();
@Override
public List<Book> getAllBook() {
return dao.getAll();
}
@Override
public void deleteCartItem(String sid, Cart cart) {
cart.getMap().remove(sid);
}
@Override
public Book findBook(String id) {
return dao.find(id);
}
@Override
public void clearCart(Cart cart) {
cart.getMap().clear();
}
@Override
public void changeQuantity(String sid, String quantity, Cart cart) {
CartItem item=cart.getMap().get(sid);
item.setQuantity(Integer.parseInt(quantity));
}
}
//db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bookdb
username=root
password=root
//BuyServlet.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.Book;
import com.hbsi.domain.Cart;
import com.hbsi.service.BusinessServiceImpl;
public class BuyServlet extends HttpServlet {
BusinessServiceImpl service=new BusinessServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.获取要买的书
String sid=request.getParameter("id");
Book book =service.findBook(sid);
//2.得到购物车
Cart cart=(Cart)request.getSession().getAttribute("cart");
if(cart==null){
cart=new Cart();
request.getSession().setAttribute("cart", cart);
}
//3.把数添加到购物车中
cart.add(book);
response.sendRedirect("./ListCartServlet");
//request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//ChangeQuantitySevlet.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.BusinessServiceImpl;
public class ChangeQuantitySevlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String sid = request.getParameter("id");
String quantity = request.getParameter("quantity");
Cart cart = (Cart) request.getSession().getAttribute("cart");
BusinessService service = new BusinessServiceImpl();
service.changeQuantity(sid,quantity,cart);
request.getRequestDispatcher("/WEB-INF/jsp/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 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.BusinessServiceImpl;
public class ClearCartServlet extends HttpServlet {
BusinessService service=new BusinessServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cart cart=(Cart) request.getSession().getAttribute("cart");
service.clearCart(cart);
request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//DeleteItemServlet.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.BusinessServiceImpl;
public class DeleteItemServlet extends HttpServlet {
//调服务类里边的方法从购物项里删除想要删除的书
BusinessService service=new BusinessServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取到购物项
String sid=request.getParameter("id");
Cart cart=(Cart)request.getSession().getAttribute("cart");
service.deleteCartItem(sid,cart);
request.getRequestDispatcher("/WEB-INF/jsp/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.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.BusinessServiceImpl;
public class ListBookServlet extends HttpServlet {
BusinessService service=new BusinessServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Book> list=service.getAllBook();
request.setAttribute("books", list);
request.getRequestDispatcher("../WEB-INF/jsp/listbook.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//ListCartServlet.java
package com.hbsi.web.ui;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ListCartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/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>
<title>My JSP 'listbook.jsp' starting page</title>
</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>
<title>My JSP 'listbook.jsp' starting page购物显示页面</title>
<script type="text/javascript">
function deleteItem(id){
var b = window.confirm("确定要删除吗?");
if(b){
window.location.href="${pageContext.request.contextPath}/servlet/DeleteItemServlet?id="+id;
}
}
function clearcart(){
var b = window.confirm("确定要清空您当前所选的商品吗?");
if(b){
window.location.href="${pageContext.request.contextPath}/servlet/ClearCartServlet";
}
}
function changequantity(input,id,oldvalue){
//得到修改的数量
var quantity = input.value;
//判断是否是正整数
if(quantity<0 || quantity!=parseInt(quantity)){
alert("请输入正整数!!");
input.value=oldvalue;
return;
}
var b = window.confirm("确定要将数量修改为:"+quantity);
if(b){
window.location.href="${pageContext.request.contextPath}/servlet/ChangeQuantitySevlet?id="+id+"&quantity="+quantity;
}
}
</script>
</head>
<body style="text-align:center">
<h1> 您的购物车</h1>
<h2>您购买了如下商品</h2>
<c:if test="${empty cart.map}">
<font color="red">您的购物车还是空的哦!!</font><br/>
<img src="../images/gouwuche.jpg" width="350" height="350"/>
您可以
<a href="${pageContext.request.contextPath}/servlet/ListBookServlet">点击此处进入购买页面</a>
</c:if>
<c:if test="${!empty cart.map}">
<table border="1" width="80%" bordercolor="blue">
<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" name="quantity" value="${me.value.quantity}" onchange="changequantity(this,${me.key},${me.value.quantity})"/>
在此修改数量
</td>
<td>${me.value.price}¥</td>
<td>
<a href="javascript:deleteItem(${me.key })" >删除</a>
<!--<a href="javascript:void(0)" onclick="deleteItem(${me.key })">删除</a>-->
<!--<a href="${pageContext.request.contextPath}/servlet/DeleteItemServlet?id=${me.key}">删除</a>-->
</td>
</tr>
</c:forEach>
<tr>
<td colspan="3">总价(totalprice)</td>
<td colspan="1">${cart.price }¥</td>
<td>
<!--<a href="${pageContext.request.contextPath}/servlet/ClearCartServlet">清空购物车</a>-->
<a href="javascript:clearcart()">清空购物车</a>
</td>
<td> <a href="javascript:pay()">去结算</a></td>
</tr>
</table>
<a href="${pageContext.request.contextPath}/servlet/ListBookServlet">返回继续购物</a>
</c:if>
</body>
</html>
//index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>
</head>
<body>
<font color="red" size="15px"> 想要你的书架上再多几本书吗?</font><br/>点击图片进入
<a href="${pageContext.request.contextPath}/servlet/ListBookServlet"> <img src="./images/book.jpg" width="350" height="350"/> </a>
</body>
</html>
//DBConn.java
package com.hbsi.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBConn {
private static Connection conn=null;
public static Connection getConn(){
if(conn==null){
try {
Class.forName("com.mysql.jdbc.Driver");
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/bookdb?user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conn;
}
public static void realse(ResultSet rs, PreparedStatement pstmt) {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//DBManager.java
package com.hbsi.utils;
import java.io.IOException;
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;
public class DBManager {
/**
* @param args
*/
static String driver;
static String url;
static String username;
static String password;
static{
InputStream in=DBManager.class.getClassLoader().getResourceAsStream("db.properties");
Properties pro=new Properties();
try {
pro.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver = pro.getProperty("driver");
url = pro.getProperty("url");
username = pro.getProperty("username");
password = pro.getProperty("password");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection con=null;
try {
con=DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static void closeDB(Connection con,Statement st,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
getConnection();
}
}
声明:此博客内容和百度文库中的内容一样都是我自己的点击打开链接,百度文库中没有DBConn.java和DBManager.java