日期:2014-05-16 浏览次数:20434 次
下面具体流程,很多功能都还未完善,之后会实现更多功能,例如分页,付款等 敬请期待
使用jsp的MVC模型开发购物车(jsp+servlet+javabean)
必须有三层架构思想:web层负责与用户打交道 业务处理层(服务层 service)数据访问层(dao)
//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