》》src结构
dao模型层,负责数据库查询。
util数据库工具层,负责连接数据库和关闭数据库。
entitiy实体层,内涵购物车对象以及物体对象。
Servlet控制层,负责对用户提交的请求做出响应,里面包含删除购物车和显示购物车的跳转方向。
》》代码
》实体类Items
注意点:
>务必重写toString方法方便ItemsDAO返回list对象的时候能正确存储数据以及 取出对象
>重写的hashcode()和object()是为了重新定义对item存储在Hashmap里的判断是否重复的规则,用于添加重复商品进购物车不会变成两个对象
package com_yiki_entitiy;
public class Items {
private int id;
private String name;
private double price;
private int number;
private String picture;
private String city;
public Items(int id, String name, double price, int number, String picture, String city) {
this.id = id;
this.name = name;
this.price = price;
this.number = number;
this.picture = picture;
this.city = city;
}
public Items() {
}
// @Override
// // Object类的toString()方法总是返回对象的所属类的类名 + @ +
// //
// hashCode值,代表对象在内存的位置。这显然不能满足我们通常的需求。像这里,我们是希望能打印出p的全名出来,这时,就需要重写toString()方法,因为重写了toString()之后,那么p在调用toString()方法的时候,会优先调用自己类里的toString()方法。
// public String toString() {
// return "商品编号:" + this.getId() + ",商品名称:" + this.getName();
// }
@Override
public String toString() {
return "Items [id=" + id + ", name=" + name + ", price=" + price + ", number=" + number + ", picture=" + picture
+ ", city=" + city + "]";
}
@Override
public int hashCode() {// 重新定义对hashmap内存储对象判断是否重复的方法
return this.getId() + this.getName().hashCode();// 如4+名字的哈希码32=36
// 哈希表的存储规则就改变了
}
@Override
public boolean equals(Object obj) {
if (this == obj) {// 判断是否等于自身
return true;
}
if (obj instanceof Items) {// 判断 Items 是否为obj类型的对象
Items i = (Items) obj;// 比较Items类中你自定义的数据域,id和name
if (this.getId() == i.getId() && this.getName().equals(i.getName())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
}
》》购物车类
package com_yiki_entitiy;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class Cart {
private HashMap<Items, Integer> goods;
private Double totalPrice;
public Cart() {
setGoods(new HashMap<Items, Integer>());
setTotalPrice(0.0);
}
public boolean addToCart(Items item, int number) {
if (goods.containsKey(item)) {//键:商品对象,值:数量
goods.put(item, goods.get(item) + number);
} else {
goods.put(item, number);
}
countPrice();
return true;
}
public boolean removeToCart(Items item) {
goods.remove(item);
countPrice();//每次添加进购物车都要重新计算总金额
return true;
}
public Double countPrice() {
double sum = 0.0;
Set<Items> keys = goods.keySet();//获得键的集合
Iterator<Items> iterator = keys.iterator();
while (iterator.hasNext()) {
Items i = iterator.next();//每次遍历出来都是一个商品对象
sum += i.getPrice() * goods.get(i);//单价*值 goods.get(通过键来取出值,键本身就是i)
}
this.setTotalPrice(sum);
return this.getTotalPrice();
}
@Override
public String toString() {
return "Cart [goods=" + goods + ", totalPrice=" + totalPrice + "]";
}
public HashMap<Items, Integer> getGoods() {
return goods;
}
public void setGoods(HashMap<Items, Integer> goods) {
this.goods = goods;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
}
》数据库工具类
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DButil {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
driver = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://localhost:3306/mvc?useUnicode=true&characterEncoding=utf-8";
username = "root";
password = "******";
}
public static Connection open() {
try {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
System.out.println("连接错误");
}
return null;
}
public static void close(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
》查询数据库
package com_yiki_dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import com_yiki_entitiy.Items;
import util.DButil;
//商品的业务逻辑类
public class ItemsDAO {
// 获得所有的商品信息
public ArrayList<Items> getAllItems() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
try {
conn = DButil.open();
String sql = "select * from items;"; // SQL语句
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
list.add(item);// 把一个商品加入集合
}
System.out.print(list);
return list; // 返回集合。
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// 根据商品编号获得商品资料
public Items getItemsById(int id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DButil.open();
String sql = "select * from items where id=?;"; // SQL语句
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
rs = stmt.executeQuery();
if (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
return item;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
//获取最近浏览的前五条商品信息
public ArrayList<Items> getViewList(String list)
{
System.out.println("list:"+list);
ArrayList<Items> itemlist = new ArrayList<Items>();
int iCount=5; //每次返回前五条记录
if(list!=null&&list.length()>0)
{
String[] arr = list.split(",");
System.out.println("arr.length="+arr.length);
//如果商品记录大于等于5条
if(arr.length>=5)
{
for(int i=arr.length-1;i>=arr.length-iCount;i--)
{
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
else
{
for(int i=arr.length-1;i>=0;i--)
{
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
return itemlist;
}
else
{
return null;
}
}
}
》Servlet类
注意点:details.jsp页面点击【放进购物车】和【查看购物车时】会在JS函数中生成请求连接,将请求发送到servlet里,servlet根据action判断执行各自的方法,如【放进购物车】将执行本servlet里的addToCart方法,在这个方法里得到Cart对象,再将请求放进Cart里addToCart方法
package com_yiki_Servlet;
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_yiki_dao.ItemsDAO;
import com_yiki_entitiy.Cart;
import com_yiki_entitiy.Items;
public class CartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String action;
private ItemsDAO dao = new ItemsDAO();
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
if (request.getParameter("action") != null) {
this.action = request.getParameter("action");
if (action.equals("add")) {
try {
if (addToCart(request, response)) {
request.getRequestDispatcher("/success.jsp").forward(request, response);
} else {
request.getRequestDispatcher("/failure.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (action.equals("show")) {
try {
showCart(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (action.equals("delete")) {
if (deleteCart(request, response)) {
request.getRequestDispatcher("/cart.jsp").forward(request, response);
} else {
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
}
}
}
//删除商品
private boolean deleteCart(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("id");
Cart cart = (Cart) request.getSession().getAttribute("cart");
Items item = dao.getItemsById(Integer.parseInt(id));
if (cart.removeToCart(item)) {
return true;
} else {
return false;
}
}
private void showCart(HttpServletRequest request, HttpServletResponse response) throws Exception, IOException {
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
// 添加进购物车
private boolean addToCart(HttpServletRequest request, HttpServletResponse response) throws Exception, IOException {
String id = request.getParameter("id");
String number = request.getParameter("num");
Items item = dao.getItemsById(Integer.parseInt(id));
// 是否是第一次给购物车添加商品
if (request.getSession().getAttribute("cart") == null) {// 创建对象放进session里
Cart cart = new Cart();
request.getSession().setAttribute("cart", cart);
}
Cart cart = (Cart) request.getSession().getAttribute("cart");// 获取现有购物车对象
if (cart.addToCart(item, Integer.parseInt(number))) {
return true;
} else {
return false;
}
}
}
》》jsp页面结构
主页
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="com_yiki_entitiy.*" %>
<%@ page import="com_yiki_dao.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<style type="text/css">
hr{
border-color:FF7F00;
}
div{
float:left;
margin: 10px;
}
div dd{
margin:0px;
font-size:10pt;
}
div dd.dd_name
{
color:blue;
}
div dd.dd_city
{
color:#000;
}
</style>
</head>
<body>
<h1>商品展示</h1>
<hr>
<center>
<table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<!-- 商品循环开始 -->
<%
ItemsDAO itemsDao = new ItemsDAO();
ArrayList<Items> list = itemsDao.getAllItems();
if(list!=null&&list.size()>0)
{
for(int i=0;i<list.size();i++)
{
Items item = list.get(i);
%>
<div>
<dl>
<dt>
<a href="details.jsp?id=<%=item.getId()%>"><img src="images/<%=item.getPicture()%>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=item.getName() %></dd>
<dd class="dd_city">产地:<%=item.getCity() %> 价格:¥ <%=item.getPrice() %></dd>
</dl>
</div>
<!-- 商品循环结束 -->
<%
}
}
%>
</td>
</tr>
</table>
</center>
</body>
</html>
商品详情
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ page import="com_yiki_entitiy.*" %>
<%@ page import="com_yiki_dao.*" %>
<%
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%>">
<link href="css/main.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/lhgcore.js"></script>
<script type="text/javascript" src="js/lhgdialog.js"></script>
<script type="text/javascript">
function selflog_show(id)
{
var num = document.getElementById("number").value;
J.dialog.get({id: 'haoyue_creat',title: '购物成功',width: 600,height:400, link: '<%=path%>/servlet/CartServlet?id='+id+'&num='+num+'&action=add', cover:true});
}
function add()//增加数量+
{
var num = parseInt(document.getElementById("number").value);
if(num<100)
{
document.getElementById("number").value = ++num;
}
}
function sub()//减少数量图标-
{
var num = parseInt(document.getElementById("number").value);
if(num>1)
{
document.getElementById("number").value = --num;
}
}
</script>
<style type="text/css">
hr{
border-color:FF7F00;
}
div{
float:left;
margin-left: 30px;
margin-right:30px;
margin-top: 5px;
margin-bottom: 5px;
}
div dd{
margin:0px;
font-size:10pt;
}
div dd.dd_name
{
color:blue;
}
div dd.dd_city
{
color:#000;
}
div #cart
{
margin:0px auto;
text-align:right;
}
span{
padding:0 2px;border:1px #c0c0c0 solid;cursor:pointer;
}
a{
text-decoration: none;
}
</style>
</head>
<body>
<h1>商品详情</h1>
<a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a>
<hr>
<center>
<table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
<tr>
<!-- 商品详情 -->
<%
ItemsDAO itemDao = new ItemsDAO();
Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
if(item!=null)
{
%>
<td width="70%" valign="top">
<table>
<tr>
<td rowspan="5"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
</tr>
<tr>
<td><B><%=item.getName() %></B></td>
</tr>
<tr>
<td>产地:<%=item.getCity()%></td>
</tr>
<tr>
<td>价格:<%=item.getPrice() %>¥</td>
</tr>
<tr>
<td>购买数量:<span id="sub" οnclick="sub();">-</span><input type="text" id="number" name="number" value="1" size="2"/><span id="add" οnclick="add();">+</span></td>
</tr>
</table>
<div id="cart">
<img src="images/buy_now.png">
<a href="javascript:selflog_show(<%=item.getId()%>)"> <img src="images/in_cart.png"></a>
<a href="servlet/CartServlet?action=show"><img src="images/view_cart.jpg"/></a>
</div>
</td>
<%
}
%>
<%
String list ="";
//从客户端获得Cookies集合
Cookie[] cookies = request.getCookies();
//遍历这个Cookies集合
if(cookies!=null&&cookies.length>0)
{
for(Cookie c:cookies)
{
if(c.getName().equals("ListViewCookie"))
{
list = c.getValue();
}
}
}
list+=request.getParameter("id")+",";
//如果浏览记录超过1000条,清零.
String[] arr = list.split(",");
if(arr!=null&&arr.length>0)
{
if(arr.length>=1000)
{
list="";
}
}
Cookie cookie = new Cookie("ListViewCookie",list);
response.addCookie(cookie);
%>
<!-- 浏览过的商品 -->
<td width="30%" bgcolor="#EEE" align="center">
<br>
<b><font color="#FF7F00">您浏览过的商品</font></b><br>
<!-- 循环开始 -->
<%
ArrayList<Items> itemlist = itemDao.getViewList(list);
if(itemlist!=null&&itemlist.size()>0 )
{
System.out.println("itemlist.size="+itemlist.size());
for(Items i:itemlist)
{
%>
<div>
<dl>
<dt>
<a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=i.getName() %></dd>
<dd class="dd_city">产地:<%=i.getCity() %> 价格:<%=i.getPrice() %> ¥ </dd>
</dl>
</div>
<%
}
}
%>
<!-- 循环结束 -->
</td>
</tr>
</table>
</center>
</body>
</html>
购物车
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="com_yiki_entitiy.*" %>
<%@ page import="com_yiki_dao.*" %>
<%
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%>">
<link type="text/css" rel="stylesheet" href="css/style1.css" />
<script language="javascript">
function delcfm() {
if (!confirm("确认要删除?")) {
window.event.returnValue = false;
}
}
</script>
</head>
<body>
<h1>我的购物车</h1>
<a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a>
<hr>
<div id="shopping">
<form action="" method="POST">
<table>
<tr>
<th>商品名称</th>
<th>商品单价</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<%
//首先判断session中是否有购物车对象
if(request.getSession().getAttribute("cart")!=null)
{
%>
<!-- 循环的开始 -->
<%
Cart cart = (Cart)request.getSession().getAttribute("cart");
HashMap<Items,Integer> goods = cart.getGoods();
Set<Items> items = goods.keySet();
Iterator<Items> it = items.iterator();
while(it.hasNext())
{
Items i = it.next();
%>
<tr name="products" id="product_id_1">
<td class="thumb"><img src="images/<%=i.getPicture()%>" /><a href="details.jsp?id=<%=i.getId()%>">
<%=i.getName()%></a></td>
<td class="number"><%=i.getPrice() %></td>
<td class="price" id="price_id_1">
<span><%=i.getPrice()*goods.get(i) %></span>
<input type="hidden" value="" />
</td>
<td class="number">
<%=goods.get(i)%>
</td>
<td class="delete">
<a href="servlet/CartServlet?action=delete&id=<%=i.getId()%>" οnclick="delcfm();">删除</a>
</td>
</tr>
<%
}
%>
<!--循环的结束-->
</table>
<div class="total"><span id="total">总计:<%=cart.getTotalPrice() %>¥</span></div>
<%
}
%>
<div class="number"><input type="submit" value="结算" /></div>
</form>
</div>
</body>
</html>
购买成功dialog填充
<%@ page language="java" import="java.util.*"
contentType="text/html; charset=utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<center>
<img src="../images/add_cart_success.jpg" />
<hr>
<%
String id = request.getParameter("id");
String num = request.getParameter("num");
%>
您成功购买了<%=num%>件商品编号为<%=id%>的商品 <br> <br>
<br>
</center>
</body>
</html>