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 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 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 list = new ArrayList();

			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 map=new LinkedHashMap();
	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 getMap() {
		return map;
	}
	public void setMap(Map map) {
		this.map = map;
	}
	public double getPrice() {
		double totalprice=0;
		for(Map.Entry 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 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 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 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+"/";
%>



  
    
    
    My JSP 'listbook.jsp' starting page
    
	

  
  
  
    

渊博书店

编号 书名 作者 价格 描述 操作
${book.id} ${book.name} ${book.author} ${book.price} ${book.description} 加入购物车
//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+"/"; %> My JSP 'listbook.jsp' starting page购物显示页面

您的购物车

您购买了如下商品

您的购物车还是空的哦!!
您可以 点击此处进入购买页面
编号 书名 单价 数量 小计 操作
${me.key} ${me.value.book.name} ${me.value.book.price}¥ 在此修改数量 ${me.value.price}¥ 删除
总价(totalprice) ${cart.price }¥ 清空购物车 去结算
返回继续购物
//index.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> 网上购物首页 想要你的书架上再多几本书吗?
点击图片进入


//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

你可能感兴趣的:(java,数据库,javascript,ViewUI)