注:采用Model1和(JSP+JavaBean)实现
注意:这是很容易出现的问题,若不在tomcat的lib目录添加jar包,会报ider java.lang.ClassNotFoundException: com.mysql.jdbc.Driver的错。
package utils;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* Created by Administrator on 2017/4/9.
*/
public class DBHelper {
private static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动
private static final String url="jdbc:mysql://localhost:3306/supermarket?useUnicode=true&characterEncoding=UTF-8";//连接数据库的URL地址并设置编码方式为“utf-8”
private static final String username="root";//数据库的用户名
private static final String password="root";//数据库的密码
private static Connection conn=null;//静态代码块负责加载驱动
static
{
{
Class.forName(driver);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//单例模式返回数据库连接对象
public static Connection getConnection() throws Exception
{
if(conn==null)
{
conn = DriverManager.getConnection(url,username,password);
return conn;//如果数据库连接对象为空,则重新建立
}
return conn;//若不为空,直接返回数据库连接对象
}
//主函数测试代码
public static void main(String[] args) {
try
{
Connection conn = DBHelper.getConnection();
if(conn!=null)
{
System.out.println("数据库连接正常!");
}
else
{
System.out.println("数据库连接异常!");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
items.sql
/*
Navicat MySQL Data Transfer
Source Server : MySQL50
Source Server Version : 50067
Source Host : localhost:3306
Source Database : shopping
Target Server Type : MYSQL
Target Server Version : 50067
File Encoding : 65001
Date: 2014-08-27 12:12:31
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- 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');
items.java
package entity;
/**
* Created by Administrator on 2017/4/9.
*/
public class items {
private int id; // 商品编号
private String name; // 商品名称
private String city; // 产地
private int 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 int getPrice() {
return price;
}
public void setPrice(int 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;
}
}
itemsDAO.java
package dao;
import entity.items;
import utils.DBHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
* Created by Administrator on 2017/4/9.
*/
public class itemsDAO {
}
public ArrayList getAllItems(){//创建查询所有的方法
Connection conn = null;//连接对象
PreparedStatement stmt = null;//语句对象
ResultSet rs = null;//结果集对象
ArrayList list = new ArrayList();//存储集合
try {
conn= DBHelper.getConnection();//获取连接对象
String sql = "select * from items;";//建立sql语句
stmt=conn.prepareStatement(sql);//创语句对象并放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.setPrice(rs.getInt("price"));
item.setNumber(rs.getInt("number"));
item.setPicture(rs.getString("picture"));
list.add(item);//将遍历出的结果放入到集合中
}
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 getItemById(int id){
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn= DBHelper.getConnection();
String sql = "select * from items where id=?;";
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.setPrice(rs.getInt("price"));
item.setNumber(rs.getInt("number"));
item.setPicture(rs.getString("picture"));
return item;
}
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();
}
}
}
}
//根据收集到的item的点击顺序的字符串,创建返回浏览记录的方法
public ArrayList getViewList(String list) {
//创建返回除去的集合
ArrayList ViewList = new ArrayList();
//定义最多5条记录
int iCount = 5;
//遍历接收到的list字符串,里面包含的是item的id号,间隔为","
if (list != null && list.length() > 0) {
//获得item的id号字符串数组
String[] itemlist = list.split(",");
//当item浏览数大于5个时候
if (itemlist.length >= 5) {
//从最后一个开始循环
for (int i = itemlist.length - 1; i >= itemlist.length - iCount; i--) {
items item = getItemById(Integer.parseInt(itemlist[i]));
//循环最后5个并添加到要返回除去的集合当中去
ViewList.add(item);
}
//当item浏览数小于5个时
} else {
for (int i = itemlist.length - 1; i >= 0; i--) {
items item = getItemById(Integer.parseInt(itemlist[i]));
ViewList.add(item);
}
}
//将小于5个浏览记录的商品集合返回出去
return ViewList;
} else {
//如果接收到的字符串list为空,则返回空
return null;
}
}
与之相对应的
<%
//建立业务逻辑对象
itemsDAO itemsDao = new itemsDAO();
//建立实体对象
items item = new items();
//建立接收实体对象的集合并接收数据库中的所有实体
ArrayList list = itemsDao.getAllItems();
//若集合不为空
if (list != null && list.size() > 0) {
//遍历集合中的实体
for (int i = 0; i < list.size(); i++) {
item = list.get(i);
%>
//循环展示实体开始
<a href="details.jsp?id=<%=item.getId()%>" class="thumbnail">
图片:<img src="img/<%=item.getPicture()%>" alt="<%=item.getName()%>" class="img-rounded" width="120"
height="90">a>
<p>
名称:<%=item.getName()%><br>
产地:<%=item.getCity()%><br>
价格:<%=item.getPrice()%><br>
p>
//循环展示实体结束
<%
}
}
%>
<%
//创建业务逻辑对象
itemsDAO itemsDao = new itemsDAO();
//创建要展示的实体对象,利用index页面超链接传过来的id号进行处理
items item = itemsDao.getItemById(Integer.parseInt(request.getParameter("id")));
if (item != null) {
%>
//实体展示开始
<a href="details.jsp?id=<%=item.getId()%>" class="thumbnail">
<img src="img/<%=item.getPicture()%>" alt="<%=item.getName()%>" class="img-rounded" width="120" height="90">
a>
<p>
名称:<%=item.getName()%><br>
产地:<%=item.getCity()%><br>
价格:<%=item.getPrice()%><br>
p>
//实体展示结束
<%
}
%>
3.1 利用cookie记录商品浏览信息
<%
//创建一个字符串接收cookie中的缓存id记录
String list = "";
//获取已存在的cookie中的id记录
Cookie[] cookies = request.getCookies();
for (Cookie c : cookies) {
if (c.getName().equals("ListViewCookie")) {
list = c.getValue();
}
}
//若商品id记录超过1000条,则清零
String[] arr = list.split(",");
if (arr != null && arr.length > 0) {
if (arr.length >= 1000) {
list = "";
}
}
//将新点击的商品的id存放到list中
list = list + request.getParameter("id") + ",";
//将list放入到cookie中并用response添加cookie
Cookie cookie = new Cookie("ListViewCookie", list);
response.addCookie(cookie);
%>
3.2根据cookie中保存的id号,利用业务逻辑对象,展示实体对象。
<%
//创建业务逻辑对象
itemsDAO itemsDao = new itemsDAO();
//创建cookie接收集合
ArrayList Viewarr = new ArrayList();
//根据cookie中保存的id号,利用业务逻辑对象的getViewList()方法调出实体对象
Viewarr = itemsDao.getViewList(list);
//循环展示实体对象开始
for (items i : Viewarr) {
%>
图片:<img src="img/<%=i.getPicture()%>" alt="<%=i.getName()%>" class="img-rounded" width="120" height="90">
<p>
名称:<%=i.getName()%><br>
产地:<%=i.getCity()%><br>
价格:<%=i.getPrice()%><br>
p>
<%
//循环展示实体对象结束
}
%>
——至此JSP部分学习完毕。