Java遇见HTML——JSP篇之商品浏览记录的实现

时间:2023-03-09 07:23:34
Java遇见HTML——JSP篇之商品浏览记录的实现

一、项目总体介绍

使用Cookie实现商品浏览记录。

Java遇见HTML——JSP篇之商品浏览记录的实现

要实现这个程序采取的是Model1(Jsp+JavaBean)架构实现,具体步骤:

  • 首先要有个数据库,商品表,操作数据库的一个类DBHelper类
  • 创建实体类(与数据库表一一对应)
  • 创建业务逻辑类(DAO)
  • 创建页面层

二、DBHelper类设计

 1 package util;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5
6 public class DBHelper {
7
8 private static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动
9 //连接数据库的URL地址
10 private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8";
11 private static final String username="root";//数据库的用户名
12 private static final String password="root";//数据库的密码
13
14 private static Connection conn=null;
15
16 //静态代码块负责加载驱动
17 static
18 {
19 try
20 {
21 Class.forName(driver);
22 }
23 catch(Exception ex)
24 {
25 ex.printStackTrace();
26 }
27 }
28
29 //单例模式返回数据库连接对象
30 public static Connection getConnection() throws Exception
31 {
32 if(conn==null)//连接为空
33 {
34 conn = DriverManager.getConnection(url, username, password);
35 return conn;
36 }
37 return conn;//连接不为空,说明这个conn曾经被实例化过。被实例化也是通过DriverManager实例化了。
38 //由于这是单例模式,意味着这个连接对象在整个服务中只有一份拷贝
39 }
40
41 //测试DBHelper类
42 public static void main(String[] args) {
43 try
44 {
45 Connection conn = DBHelper.getConnection();
46 if(conn!=null)
47 {
48 System.out.println("数据库连接正常!");
49 }
50 else
51 {
52 System.out.println("数据库连接异常!");
53 }
54 }
55 catch(Exception ex)
56 {
57 ex.printStackTrace();
58 }
59
60 }
61 }

三、商品实体类设计

数据库shopping中items表:

Java遇见HTML——JSP篇之商品浏览记录的实现

对应的实体类:

 1 package entity;
2
3 //商品类
4 public class Items {
5
6 private int id; // 商品编号
7 private String name; // 商品名称
8 private String city; // 产地
9 private int price; // 价格
10 private int number; // 库存
11 private String picture; // 商品图片
12
13 public int getId() {
14 return id;
15 }
16
17 public void setId(int id) {
18 this.id = id;
19 }
20
21 public String getName() {
22 return name;
23 }
24
25 public void setName(String name) {
26 this.name = name;
27 }
28
29 public String getCity() {
30 return city;
31 }
32
33 public void setCity(String city) {
34 this.city = city;
35 }
36
37 public int getPrice() {
38 return price;
39 }
40
41 public void setPrice(int price) {
42 this.price = price;
43 }
44
45 public int getNumber() {
46 return number;
47 }
48
49 public void setNumber(int number) {
50 this.number = number;
51 }
52
53 public String getPicture() {
54 return picture;
55 }
56
57 public void setPicture(String picture) {
58 this.picture = picture;
59 }
60
61 }

四、获取所有商品资料方法的实现

 package dao;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList; import util.DBHelper; import entity.Items; //商品的业务逻辑类
public class ItemsDAO { // 获得所有的商品信息
public ArrayList<Items> getAllItems() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
try {
conn = DBHelper.getConnection();
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);// 每次遍历时把一个商品加入集合
}
return list; // 返回集合。
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
//finally释放资源(从小到大释放资源rs,stmt。注意连接对象conn不要释放,因为它是单例模式,一旦释放了,后面的方法就没法使用了)
// 释放数据集对象
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();
}
}
} } }

五、所有商品信息显示

 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<%
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 'index.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">
-->
<style type="text/css">
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="data:images/<%=item.getPicture()%>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=item.getName() %></dd>
<dd class="dd_city">产地:<%=item.getCity() %>&nbsp;&nbsp;价格:¥ <%=item.getPrice() %></dd>
</dl>
</div>
<!-- 商品循环结束 -->
<%
}
}
%>
</td>
</tr>
</table>
</center>
</body>
</html>

六、商品详细信息显示

在ItemsDAO.java中添加如下代码:

 // 根据商品编号获得商品资料
public Items getItemsById(int id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBHelper.getConnection();
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();
}
} }
}

在details.jsp添加如下代码:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<%
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 'details.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">
-->
<style type="text/css">
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;
}
</style>
</head> <body>
<h1>商品详情</h1>
<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="4"><img src="data: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>
</table>
</td>
<%
}
%>
</tr>
</table>
</center>
</body>
</html>

七、使用Cookie实现保存商品浏览记录

如何把浏览记录保存在cookie中?

因为商品编号是唯一的,我们可以获取商品的编号,自然而然可以获取商品的信息。那么用户在每一次点击商品的详情的时候,他会把商品的编号传给details.jsp页面,那么我们可以想办法在details.jsp页面当中把传过来的商品编号给它保存在一个字符串当中。

主要思路:

把每次浏览的商品编号保存在字符串中,编号和编号之间用分隔符分隔,每次取出前五条记录。

(把字符串保存在cookie当中,每次只要在cookie中读取这个字符串就可以了。把这个字符串通过分隔符转换成字符串数组,数组中的每个元素实际上就是商品编号)

大致思路:
1、用一个字符串来记录浏览商品的id记录。***字符串处理:将id添加到字符串中,并用','隔开。操作方式:str += id + ",";这样所有的记录都保存在字符串中,如:1,3,5,1,....
2、通过request.getCookies()遍历cookie集合,通过cookie.getName().equals(strname)查询用于保存字符串的cookie,通过cookie.getValue()得到字符串后传入逻辑业务中的方法。
3、在逻辑业务操作中,定义一个方法接受字符串,取得字符串后,使用str.sqlit(",")将字符串分割为字符串数组[1,3,5,1...],这样就获得了商品id的浏览记录。
4、之后就是通过遍历和添加数组,最后返回浏览记录的数组即可

 //获取最近浏览的前五条商品信息
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;
} }

detail.jsp

 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<%
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 'details.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">
-->
<style type="text/css">
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;
}
</style>
</head> <body>
<h1>商品详情</h1>
<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="4"><img src="data: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>
</table>
</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>您浏览过的商品</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="data:images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=i.getName() %></dd>
<dd class="dd_city">产地:<%=i.getCity() %>&nbsp;&nbsp;价格:<%=i.getPrice() %> ¥ </dd>
</dl>
</div>
<%
}
}
%>
<!-- 循环结束 -->
</td>
</tr>
</table>
</center>
</body>
</html>

最终的案例界面:

Java遇见HTML——JSP篇之商品浏览记录的实现