日期:2014-05-16  浏览次数:20434 次

jsp课程(7)---jsp+servlet+javabean 实现的简单网上购物车

简单购物车案例(附源码)

下面具体流程,很多功能都还未完善,之后会实现更多功能,例如分页,付款等 敬请期待

使用jspMVC模型开发购物车(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
p