按照上篇文章的分析来具体实现:
定义所需包名来分工:
功能一:显示所有图书:
1、数据层:用双列集合来保存数据,用静态方法来添加数据里嵌套Book类(在实体类包domain里来创建,代码在下面)的构造方法,
public class DB {
private static Map map=new LinkedHashMap();
static
{
map.put("1", new Book("1","java","A",20));
map.put("2", new Book("2","c++","B",21));
map.put("3", new Book("3","PHP","C",22));
map.put("4", new Book("4",".NET","D",23));
map.put("4", new Book("5","Python","E",23));
map.put("6", new Book("6","C#","F",23));
}
/*按照实施过程来创建查找方法,通过类名来调用该静态方法。返回map对象。即上篇文章的
实施过程,可返回参考*/
//注意map的key和value对应
public static Map findAllBook()
{
return map;
}
public static Book findBookById(String id)
{
return DB.findBookById(id);
}
}
2、实体层
public class Book {
private String id;
private String name;
private String author;
private double price;
private int num=1;
public Book() {
}
//即对应DB类里的new Book("1","java","A",20)
public Book(String id, String name, String author, int price) {
super();
this.id = id;
this.name = name;
this.author = author;
this.price = price;
}
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(int price) {
this.price = price;
}
}
3、访问层
//访问层/持久层
public class BookDao {
//查询所有的图书
private DB db=new DB();
public Map findAllBook()
{
return DB.findAllBook();
}
public static Book findBookById(String id){
return DB.findBookById(id);
}
}
4、业务层
public class BookService {
private BookDao bookDao = new BookDao();
// 查询所有图书
public Map findAllBook() {
return bookDao.findAllBook();
}
// 购买图书
public void buyBook(String id, Car car) {
// 取得图书列表
Map map = car.getMap();
// 根据id获得图书
Item item = map.get(id);
if (item == null) {
Book book = bookDao.findBookById(id);
// 加入购物车
item = new Item();
// Book book =new Book();
item.setBook(book);
item.setNum(1);
map.put(id, item);
} else {
item.setNum(item.getNum() + 1);
}
}
public void deleteBook(String id, Car car) {
Map map = car.getMap();
map.remove(id);
}
public void clearCar(Car car) {
Map map = car.getMap();
map.clear();
}
public void updateBook(String id, int num, Car car) {
Map map = car.getMap();
Item item = map.get(id);
item.setNum(num);
}
}
public class ListBookServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BookService bookservice=new BookService();
Map map=bookservice.findAllBook();
request.setAttribute("map", map);
//请求转发:
request.getRequestDispatcher("/view/listAllBook.jsp").forward(request, response);
}
}
6、显示层
listAllBook.jsp
图书列表
编号
书名
作者
单价
${entry.value.id}
${entry.value.name}
${entry.value.auther}
${entry.value.price}
购买