MVC模式购物车举例

一、视图层
 
买书页面
<%@ page Xlanguage="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>
 <base href="<%=basePath%>">
 
<title>My JSP 'listbook.jsp' starting page</title>
 
<meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 
</head>
 
<body>
 <table>
 <tr>
 <td> 编号</td> <td> 书名</td> <td> 作者</td> <td>售价 </td> <td>描述 </td> <td> 操作</td>
 </tr>
 
<c:forEach var="me" items="${books}" >
 <tr>
 <td> ${me.id }</td>
 <td> ${me.name }</td>
 <td> ${me.author }</td>
 <td> ${me.price}</td>
 <td> ${me.description}</td>
 <td>
 <a href="${pageContext.request.contextPath}/servlet/Buyservlet?id=${me.id}">购买</a>
 </td>
 </tr>
 </c:forEach>

</table>
 </body>
</html>
 
显示购买买书的页面
<%@ page Xlanguage="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>
 <base href="<%=basePath%>">
 
<title>My JSP 'listcart.jsp' starting page</title>
 
<meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 
<script>
 
function updateCart(input,bookid,oldvalue){
 var b = window.confirm("您确定修改吗??");
 if(b){
 var quantity = input.value;
 if(quantity==""){
 alert("请输入数字!!");
 input.value=oldvalue;
 return;
 }
 if(!quantity.match("\\d+")){
 alert("请输入数字!!");
 input.value=oldvalue;
 return;
 }
 if(quantity<1){
 alert("请输入有效数字!!");
 input.value=oldvalue;
 return;
 }
 


window.location.href='${pageContext.request.contextPath}/servlet/Update?bookid='+bookid+'&quantity='+quantity;
 }else{
 input.value=oldvalue;
 }
 }
 </script>
 </head>
 
<body>
 <h3>您购买了以下产品:</h3>
 <table>
 <tr>
 <td>
 编号
 </td>
 <td>
 书名
 </td>
 <td>
 数量
 </td>
 <td>
 单价
 </td>
 <td>
 小结
 </td>
 <td>
 操作
 </td>
 </tr>
 
<c:forEach var="me" items="${cart.map}">
 <tr>
 <td>
 ${me.value.book.id}
 </td>
 <td>
 ${me.value.book.name}
 </td>
 <td>
 <input type="text" value="${me.value.quantity }" Xοnchange="updateCart(this,${me.value.book.id },${me.value.quantity})"/>
 </td>
 <td>
 ${me.value.book.price}
 </td>
 <td>
 ${me.value.price}
</td>
 <td>
 <a href="${pageContext.request.contextPath}/servlet/remove?id=${me.value.book.id}">删除</a>
 </td>
 </tr>
 </c:forEach>
 <tr>
 <td colspan="2">
 <a href="${pageContext.request.contextPath}/servlet/removes">清空购物车</a>
 </td>
 <td colspan="2">
 <a href="${pageContext.request.contextPath}/servlet/listBookServlet">返回继续购物</a>
 </td>
 <td colspan="2">总价:${cart.price}</td>
 </tr>
 </table>
 </body>
</html>
 

二、控制层
查询所有的servlet的程序
package com.hbsi.csdn.cl;
 
import java.io.IOException;
import java.io.PrintWriter;
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.csdn.domain.Book;
import com.hbsi.csdn.servlet.Busine;
import com.hbsi.csdn.servlet.BusineImpi;
 
public class listBookServlet extends HttpServlet {
 

 

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
this.doPost(request, response);
 

}
 public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
response.setContentType("text/html;charset=utf-8");
 PrintWriter out = response.getWriter();
 Busine book = new BusineImpi();
 List<Book> list = book.getAll();
 request.setAttribute("books", list);
 request.getRequestDispatcher("/listbook.jsp").forward(request, response);
 }
 
}
 

修改的servlet的程序
package com.hbsi.csdn.cl;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.hbsi.csdn.domain.Cart;
import com.hbsi.csdn.servlet.Busine;
import com.hbsi.csdn.servlet.BusineImpi;
 
public class Update extends HttpServlet {
 

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
this.doPost(request, response);
 
}
 

public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
response.setContentType("text/html;charset=utf-8");
 PrintWriter out = response.getWriter();
 String id = request.getParameter("bookid");
 String uty1 =request.getParameter("quantity");
 int uty=Integer.valueOf(uty1);
 Cart cart=(Cart) request.getSession().getAttribute("cart");
 Busine b = new BusineImpi();
 b.update(cart, id, uty);
 request.getRequestDispatcher("/listcart.jsp").forward(request, response);
 
}
 
/**
 * Initialization of the servlet. <br>
 *
 * @throws ServletException if an error occurs
 */
 public void init() throws ServletException {
 // Put your code here
 }
 
}
 
购买的servlet的程序
package com.hbsi.csdn.cl;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.hbsi.csdn.domain.Book;
import com.hbsi.csdn.domain.Cart;
import com.hbsi.csdn.servlet.Busine;
import com.hbsi.csdn.servlet.BusineImpi;
 
public class Buyservlet extends HttpServlet {
 

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
this.doPost(request, response);
 }
 

public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
response.setContentType("text/html;charset=utf-8");
 PrintWriter out = response.getWriter();
 String id=request.getParameter("id");
 
Cart cart=(Cart) request.getSession().getAttribute("cart");
 if(cart==null)
 {
 cart= new Cart();
 request.getSession().setAttribute("cart", cart);
 
}
 Busine b=new BusineImpi();
 b.buyBook(id, cart);
 request.getRequestDispatcher("/listcart.jsp").forward(request, response);
 

/*
 Busine b=new BusineImpi();
 Book book =b.find(request.getParameter("id"));
 request.setAttribute("book", book);*/
 
}
 

}
 

删除的servlet的程序
package com.hbsi.csdn.cl;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.hbsi.csdn.domain.Cart;
import com.hbsi.csdn.servlet.Busine;
import com.hbsi.csdn.servlet.BusineImpi;
 
public class remove extends HttpServlet {
 


public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
this.doPost(request, response);
 }
 
public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
response.setContentType("text/html;charset=utf-8");
 PrintWriter out = response.getWriter();
 String id = request.getParameter("id");
 Cart cart =(Cart) request.getSession().getAttribute("cart");
 if(cart!=null)
 {
 Busine b =new BusineImpi();
 b.remove( id, cart);
 request.getRequestDispatcher("/listcart.jsp").forward(request, response);
 }
 
}
 

}
 
清空购物车的servlet的程序
package com.hbsi.csdn.cl;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.hbsi.csdn.domain.Cart;
import com.hbsi.csdn.servlet.Busine;
import com.hbsi.csdn.servlet.BusineImpi;
 
public class removes extends HttpServlet {
 


public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
this.doPost(request, response);
 }
 

;public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
response.setContentType("text/html;charset=utf-8");
 
PrintWriter out = response.getWriter();
 Cart cart = (Cart) request.getSession().getAttribute("cart");
 
if(cart!=null)
 {
 Busine b = new BusineImpi();
 b.removes(cart);
 request.getRequestDispatcher("/listcart.jsp").forward(request, response);
 }else
 {
 request.getRequestDispatcher("/listcart.jsp").forward(request, response);
 }
 
}
 


}
 
返回购买页面的servlet的程序
package com.hbsi.csdn.cl;
 
import java.io.IOException;
import java.io.PrintWriter;
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.csdn.domain.Book;
import com.hbsi.csdn.servlet.Busine;
import com.hbsi.csdn.servlet.BusineImpi;
 
public class listBookServlet extends HttpServlet {
 

 

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
this.doPost(request, response);
 

}
 public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 
response.setContentType("text/html;charset=utf-8");
 PrintWriter out = response.getWriter();
 Busine book = new BusineImpi();
 List<Book> list = book.getAll();
 request.setAttribute("books", list);
 request.getRequestDispatcher("/listbook.jsp").forward(request, response);
 }
 
}
 
相关封装包
package com.hbsi.csdn.dao;
 
import java.util.List;
 
import com.hbsi.csdn.domain.Book;
 
public interface BookDao {
 //返回所用的书
 public List<Book> getAll();
 //根据id找到一本书
 public Book find(String id) ;
 
}
 

package com.hbsi.csdn.dao.impl;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
 
import com.hbsi.csdn.dao.BookDao;
import com.hbsi.csdn.domain.Book;
import com.hbsi.csdn.utils.DBger;
 
public class BookDaoImpl implements BookDao {
 
public Book find(String id) {
 Book b = new Book();
 Connection conn =null;
 PreparedStatement st=null;
 ResultSet rs= null ;
 try {
 conn=DBger.getConn();
 String sql="select * from book where id=? ";
 st=conn.prepareStatement(sql);
 st.setString(1, id);
 rs=st.executeQuery();
 if(rs.next())
 {
 b.setId(rs.getString("id"));
 b.setName(rs.getString("name"));
 b.setPrice(rs.getDouble("price"));
 b.setAuthor(rs.getString("author"));
 b.setDescription(rs.getString("description"));
 
}
 } catch (Exception e) {
 // TODO: handle exception
 }
 
return b ;
 }
 
public List<Book> getAll() {
 List<Book> list =new ArrayList<Book>();
 Connection conn =null;
 PreparedStatement st=null;
 ResultSet rs= null ;
 try {
 conn=DBger.getConn();
 String sql="select * from book";
 st=conn.prepareStatement(sql);
 rs=st.executeQuery();
 while(rs.next())
 {
Book b=new Book();
 b.setId(rs.getString("id"));
 b.setName(rs.getString("name"));
 b.setPrice(rs.getDouble("price"));
 b.setAuthor(rs.getString("author"));
 b.setDescription(rs.getString("description"));
 
list.add(b);
 

}
 } catch (Exception e) {
 // TODO: handle exception
 }
 return list;
 }
 
}
 

package com.hbsi.csdn.servlet;
 
import java.util.List;
 
import com.hbsi.csdn.domain.Book;
import com.hbsi.csdn.domain.Cart;
 
public interface Busine {
 
public List<Book> getAll();
 //根据id找到一本书
 public Book find(String id) ;
 
public void buyBook(String id, Cart cart);
 public void remove (String id, Cart cart);
 public void removes(Cart cart);
 public void update(Cart cart, String id ,int uty);
 
}
 

package com.hbsi.csdn.servlet;
 
import java.util.List;
 
import com.hbsi.csdn.dao.BookDao;
import com.hbsi.csdn.dao.impl.BookDaoImpl;
import com.hbsi.csdn.domain.Book;
import com.hbsi.csdn.domain.Cart;
import com.hbsi.csdn.domain.CartItem;
 
public class BusineImpi implements Busine{
 BookDao book = new BookDaoImpl();
 public Book find(String id) {
 
return book.find(id);
 }
 
public List<Book> getAll() {
 
return book.getAll();
 }
 
public void buyBook(String id, Cart cart) {
 Book books =book.find(id);
 cart.add(books);//把书放在购物车中
 
}
 public void remove(String id,Cart cart)
 {
 Book books =book.find(id);
 cart.remove(books);
 }
 public void removes(Cart cart)
 {
 cart.removes();
 }
 


public void update(Cart cart, String id, int uty) {
 int id1=Integer.valueOf(id);
 CartItem item=cart.getMap().get(id);
 item.setQuantity(uty);
 
}
 
}
 

package com.hbsi.csdn.utils;
 
import java.sql.*;
 

public class DBger {
 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/test?user=root&password=111&useUnicode=true&characterEocoding=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 clean(ResultSet rs,PreparedStatement ps)
 {
 if(ps!=null)
 {
 try {
 ps.close();
 } catch (SQLException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 if(rs!=null)
 {
 try {
 rs.close();
 } catch (SQLException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 
}
 }
 

}
 

三、模型层
 
Book的模型
package com.hbsi.csdn.domain;
 
import java.io.Serializable;
 
public class Book implements Serializable {
 
/**
 *
*/
 private static final long serialVersionUID = 1L;
 private String id;
 private String name;
 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 getDescription() {
 return description;
 }
 public void setDescription(String description) {
 this.description = description;
 }
 public double getPrice() {
 return price;
 }
 public void setPrice(double price) {
 this.price = price;
 }
 public String getAuthor() {
 return author;
 }
 public void setAuthor(String author) {
 this.author = author;
 }
 private double price;
 private String author;
}
 

购物车
package com.hbsi.csdn.domain;
 
import java.util.LinkedHashMap;
import java.util.Map;
 
import org.junit.Test;
 

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.put(book.getId(),item);
 
}
}
 public void remove(Book book)
 {
 map.remove(book.getId());
 }
 public void removes()
 {
 map.clear();
 }
 
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())
 {
 totalprice=totalprice+me.getValue().getPrice();
 }
 
return totalprice;
 }
 
}
 /*

*/
 


购物车项模型
package com.hbsi.csdn.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;
 }
 
}
 
如果你看时,十分费劲,说明我的封装良好,如果你看不懂,说明我的封装性十分良好。
 


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值