您的位置:首页 > 其它

使用Cookie实现商品的浏览记录功能

2014-12-18 21:36 836 查看
之前在前面一篇文章中简单的介绍了一下Cookie的来历与简单的用法,以及与Session两者之间的区别,然而理论终究还是要与实践相结合的,有了实践,理论才能得以更好的巩固。尤其是编程这种技术性操作性及其强的工作,更需要不断的去实践。

像很多购物网站、淘宝,京东等购物网站,细心的朋友都会发现页面的一侧都会有那种浏览过的商品历史记录信息,之前也只是听说这个是使用cookie机制实现的,但是具体怎么实现的还不是很清楚,通过这两天的学习,终于也大致清楚这其中的奥秘,好了,废话不多说了,这两天练习了一个小例子,分享出来,大家共同学习。。。。同时也是自己的一种成长!

项目环境:Myeclipse10.1+MySql5.5 +tomcat7.0+jdk1.7

项目所需要的数据表及相关数据:

-- ----------------------------
-- Table structure for items
-- ----------------------------
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(50) default NULL,
`city` varchar(50) default NULL,
`price` int(11) default NULL,
`number` int(11) default NULL,
`picture` varchar(500) default NULL,
PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '沃特篮球鞋', '佛山', '180', '500', '001.jpg');
INSERT INTO `items` VALUES ('2', '安踏运动鞋', '福州', '120', '800', '002.jpg');
INSERT INTO `items` VALUES ('3', '耐克运动鞋', '广州', '500', '1000', '003.jpg');
INSERT INTO `items` VALUES ('4', '阿迪达斯T血衫', '上海', '388', '600', '004.jpg');
INSERT INTO `items` VALUES ('5', '李宁文化衫', '广州', '180', '900', '005.jpg');
INSERT INTO `items` VALUES ('6', '小米3', '北京', '1999', '3000', '006.jpg');
INSERT INTO `items` VALUES ('7', '小米2S', '北京', '1299', '1000', '007.jpg');
INSERT INTO `items` VALUES ('8', 'thinkpad笔记本', '北京', '6999', '500', '008.jpg');
INSERT INTO `items` VALUES ('9', 'dell笔记本', '北京', '3999', '500', '009.jpg');
INSERT INTO `items` VALUES ('10', 'ipad5', '北京', '5999', '500', '010.jpg');


项目结构:



采用了简单的MVC分层结构:

一、POJO实体类:

package com.entity;

import java.io.Serializable;
/**
* 商品实体类
* @author feizi
*
*/
public class Items implements Serializable {

private static final long serialVersionUID = -7227473786914479285L;

private int id;// 商品编号
private String name;// 商品名称
private String city;// 产地
private double price;// 价格
private int number;// 库存
private String picture;// 图片

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 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 getNumber() {
return number;
}

public void setNumber(int number) {
this.number = number;
}

public String getPicture() {
return picture;
}

public void setPicture(String picture) {
this.picture = picture;
}

public static long getSerialversionuid() {
return serialVersionUID;
}
}


二、数据访问层:

package com.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* dao数据访问层
* @author feizi
*
*/
public class DaoHelper {
private static final String driver = "com.mysql.jdbc.Driver";//数据库驱动
//连接数据库的URL地址(设置字符集防止中文乱码)UTF8或者UTF-8
private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF8";
private static final String username = "root";//数据库用户名
private static final String password = "root";//数据库密码

private static Connection conn = null;//数据库连接对象(java.sql.Connection包下面的)

/**
* 静态代码块负责加载数据库驱动
*/
static{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

/**
* 构造方法私有化
*/
private DaoHelper(){

}

/**
* 单例模式获得数据库连接
* @return
*/
public static Connection getConnection(){
if(conn == null){
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
return conn;
}

/**
* 关闭数据库连接
* @param pst
* @param rs
* @param conn
*/
public static void closeConnection(ResultSet rs, PreparedStatement pst, Connection conn){
try {
if(rs != null){
rs.close();
}
if(pst != null){
pst.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

/**
* main测试
* @param args
*/
public static void main(String[] args){
Connection conn = DaoHelper.getConnection();
if(conn != null){
System.out.println("数据库连接成功!");
}else{
System.out.println("数据库连接失败!");
}
}
}


三、业务逻辑层:

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.entity.Items;

/**
* 实体Dao类
* @author feizi
*	业务逻辑类
*/
public class EntityDao {
private Connection conn = null;
private PreparedStatement pst = null;
private ResultSet rs = null;

/**
* 查询所有的商品列表
* @return
*/
public List<Items> getItemsList(){
List<Items> itemsList = new ArrayList<Items>();
Items items = null;

String sql = "SELECT * FROM items;";
try {
pst = DaoHelper.getConnection().prepareStatement(sql);

rs = pst.executeQuery();
while(rs.next()){
items = new Items();
items.setId(rs.getInt("id"));
items.setName(rs.getString("name"));
items.setCity(rs.getString("city"));
items.setNumber(rs.getInt("number"));
items.setPrice(rs.getDouble("price"));
items.setPicture(rs.getString("picture"));

itemsList.add(items);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DaoHelper.closeConnection(rs, pst, conn);
}
return itemsList;
}

/**
* 根据商品编号查询商品
* @param id
* @return
*/
public Items getItemsById(int id){
Items items = null;
String sql = "SELECT * FROM items WHERE id = ?;";

try {
pst = DaoHelper.getConnection().prepareStatement(sql);
pst.setInt(1, id);

rs = pst.executeQuery();
if(rs.next()){
items = new Items();
items.setId(rs.getInt("id"));
items.setName(rs.getString("name"));
items.setCity(rs.getString("city"));
items.setNumber(rs.getInt("number"));
items.setPrice(rs.getDouble("price"));
items.setPicture(rs.getString("picture"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DaoHelper.closeConnection(rs, pst, conn);
}
return items;
}

/**
* 获取最近浏览的五条记录信息
* @param list
* @return
*/
public List<Items> getViewList(String list){
System.out.println("=================================getViewList");
List<Items> itemList = new ArrayList<Items>();
int iCount = 5;

if(null != list && list.length() > 0){
String[] arr = list.split(",");

//倒序输出五条信息
if(arr.length >= 5){
for (int i = arr.length-1; i >= arr.length-iCount; i--) {
System.out.println("============1>>>>>>>>>i:"+i);
itemList.add(getItemsById(Integer.parseInt(arr[i])));
}
}else{
for (int i = arr.length-1; i >= 0; i--) {
System.out.println("============2>>>>>>>>>>i:"+i);
itemList.add(getItemsById(Integer.parseInt(arr[i])));
}
}
return itemList;
}else{
return null;
}
}

/**
* main测试
* @param args
*/
public static void main(String[] args){
EntityDao dao = new EntityDao();

/*List<Items> itemsList = dao.getItemsList();
if(null != itemsList && itemsList.size() > 0){
for(Items items : itemsList){
System.out.println(items.getId()+","+items.getName()+","+items.getCity()+",¥"
+items.getPrice()+","+items.getNumber()+","+items.getPicture());
}
}*/

/*Items items = dao.getItemsById(1);
if(items != null){
System.out.println("\n\n"+items.getId()+","+items.getName()+","+items.getCity()+",¥"
+items.getPrice()+","+items.getNumber()+","+items.getPicture());
}*/

List<Items> itemsList = dao.getViewList("1;2;3");
if(null != itemsList && itemsList.size() > 0)
{
for(Items items : itemsList)
{
System.out.println(items.getId()+","+items.getName()+","+items.getCity()+",¥"
+items.getPrice()+","+items.getNumber()+","+items.getPicture());
}
}
}
}


四、前台页面展示:

1、商品列表展示页面(item_list.jsp)

<%@page import="com.entity.Items"%>
<%@page import="com.dao.EntityDao"%>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
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>商品列表</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">
-->
<style type="text/css">
h1{
azimuth: center;
}
.main_table{
padding: 20px;
margin-top: 10px;
}
img{
width: 280px;
height: 200px;
}
td{
padding: 5px;
}
.pmg{
width: 200px;
height: 200px;
}
</style>
</head>

<body>
<h1 align="center">商品列表</h1>
<hr>
<table align="center" class="main_table" cellspacing="30px;">
<tr>
<%

EntityDao dao = new EntityDao();
List<Items> itemList = dao.getItemsList();

if(null != itemList && itemList.size() > 0)
{
for(int i = 0;i < itemList.size();i++)
{
Items item = itemList.get(i);
%>
<td>
<table align="center">
<tbody>
<tr>
<td>
<a href="item_info.jsp?id=<%=item.getId() %>">
<img src="images/<%=item.getPicture() %>"/>
</a>
</td>
</tr>
<tr><td>名称:<%=item.getName() %></td></tr>
<tr><td>产地:<%=item.getCity() %></td></tr>
<tr><td><font color="red">价格:¥<%=item.getPrice() %></font></td></tr>
<tr><td><font color="blue">库存:<%=item.getNumber() %></font></td></tr>
</tbody>
</table>
</td>
<%
//每行最多显示3个产品信息
if((i+1) % 3 == 0)
{
%>
</tr>
<%
}
}
}
%>
</table>
</body>
</html>


2、商品详细信息显示页面(item_info.jsp)

<%@page import="com.entity.Items"%>
<%@page import="com.dao.EntityDao"%>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
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>商品信息</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">
-->

<style type="text/css">
h1{
azimuth: center;
}
.main_table{
padding: 0;
margin-top: 0;
}
img.detail{
width: 550px;
height: 430px;
}
img.his{
width: 150px;
height: 120px;
}
td{
padding: 5px;
}
</style>
</head>

<body>
<h1 align="center">商品信息</h1>
<hr>
<table width="100%" height="100%" align="center">
<tr>
<td>
<%
request.setCharacterEncoding("utf-8");

Integer id = Integer.parseInt(request.getParameter("id"));

EntityDao dao = new EntityDao();
Items item = dao.getItemsById(id);

if(item != null)
{
%>
<table align="center" class="main_table" cellspacing="30px;" style="margin-top: 0">
<tr>
<td style="margin-top: 0">
<img class="detail" src="images/<%=item.getPicture() %>"/>
</td>
<td>
<table>
<tr><td>名称:<%=item.getName() %></td></tr>
<tr><td>产地:<%=item.getCity() %></td></tr>
<tr><td><font color="red">价格:¥<%=item.getPrice() %></font></td></tr>
<tr><td><font color="blue">库存:<%=item.getNumber() %></font></td></tr>
</table>
</td>
</tr>
</table>
</td>
<%
}
%>

<%
String list = "";

//从客户端获取cookie集合,遍历cookie集合
Cookie[] cookies = request.getCookies();
if(null != cookies && cookies.length > 0){
for(Cookie cookie : cookies){
if("list".equals(cookie.getName())){
list = cookie.getValue();
}
}
}
//以逗号进行分隔
list += request.getParameter("id") + ",";

//如果cookie中的记录过多,则清零
String[] arr = list.split(",");
if(arr != null && arr.length > 0){
if(arr.length >= 500){
list = "";
}
}

System.out.println("===========list:"+list);
Cookie newCookie = new Cookie("list",list);
//设置cookie的有效期
newCookie.setMaxAge(24*60*60);

response.addCookie(newCookie);
%>

<%--  浏览过的商品  --%>
<td width="25%" bgcolor="#EEE" align="center">
<br>
<b>您浏览过的商品信息:</b>

<%--  循环的开始  --%>
<%
List<Items> itemsList = dao.getViewList(list);

System.out.println("itemsList的大小:"+itemsList.size());
if(null != itemsList && itemsList.size() > 0)
{
for(Items itm : itemsList)
{
%>
<div>
<dl>
<dt>
<a href="item_info.jsp?id=<%=itm.getId() %>">
<img class="his" src="images/<%=itm.getPicture() %>"/>
</a>
</dt>
<dd><%=itm.getName() %></dd>
<dd>产地:<%=itm.getCity() %>  <font color="red">价格:¥<%=itm.getPrice() %></font></dd>
</dl>
</div>
<%
}
}
%>
<%--  循环的结束 --%>
</td>
</tr>
</table>
</body>
</html>


看看最终运行效果,界面可能不怎么好看。css没怎么弄,只是简单的写了下。如下图所示:



最终的cookie浏览历史记录的效果如下:



好了,到这里,整个的流程基本上已经完成了,主要的实现思路就是通过每次点击商品查看信息的时候,传递一个商品编号,然后保存在cookie中,然后从cookie中取出来,去数据库执行相关的查询操作,之后再到页面上进行显示就ok了。。。。

虽然现在还只是一个小小的菜鸟,还有许多许多东西都不懂,也没有接触到,但是不管怎样,保持一颗学习的心总归是好的。学习,永远是世上最快乐的事情。。。。

恩,,,,反正每天都学习一点点,坚持下去,慢慢地就会看见自己的成长了,学编程容易,学的好不易,且学且珍惜!!!

整个项目的源代码已经上传,如果需要的朋友可以看看,

http://download.csdn.net/detail/hu1991die/8275539

点击这里可以查看上一篇文章,里面简单的介绍了一下cookie的来历以及与session之间的区别和相应的用法:

初识JSP之Cookie机制
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: