项目总体介绍
案例:商品浏览记录的实现
采用Model1(Jsp+Javabean)实现
实现DBHelper类
创建实体类
创建业务逻辑类(DAO)
创建页面层
DBHelper类设计
首先将驱动架包复制到lib文件夹内
架包下载
链接: https://pan.baidu.com/s/1pM325b9 密码: 62jg
String driver = "com.mysql.jdbc.Driver";//数据库驱动
//连接数据库的URL地址
String url = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterRncoding=UTF-8";
String username="root"; //数据库的用户名
String password="";//数据库的密码
DBHelper.java类
package util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBHelper {
private static final String driver = "com.mysql.jdbc.Driver";// 数据库驱动
// 连接数据库的URL地址
private static final String url = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterRncoding=UTF-8";
private static final String username = "root"; // 数据库的用户名
private static final String password = "";// 数据库的密码
private static Connection conn=null;
//静态代码块负责加载驱动
static {
try {
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) {
// TODO: handle exception
ex.printStackTrace();
}
}
}
运行一下。
对数据库不了解的,可以参考下面的文章:
安装好Navicat Premium,打开后新建连接->mysql,主机名端口要跟DBHeper类对应,确定完成连接。右键新建数据库,名字shopping,字符集utf-8,排序规则utf8_general_ci,确定完成数据库。右键数据库->运行SQL文件选择案例素材里的items.sql导入或者直接把它拖进去,完成后关闭连接再次打开就发现有个items的表了。
商品实体类设计
新建entity包,Items类
package entity;
//商品类
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;
}
}
获取所有商品资料方法的实现
新建dao包,ItemsDAO类,注意命名规则
package dao;
import java.sql.Connection;
import java.util.ArrayList;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import entity.Items;
import util.DBHelper;
//商品的业务逻辑类
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 = (PreparedStatement) conn.prepareStatement(sql);
rs = (ResultSet) 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 e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
finally {
//释放数据集对象
if(rs !=null) {
try {
rs.close();
rs = null;
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
//释放语句对象
if(stmt !=null) {
try {
stmt.close();
stmt = null;
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
}
商品详细信息显示
ItemsDAO.java类新增一个方法getItemsById
// 根据商品编号获得商品资料
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 = (PreparedStatement) conn.prepareStatement(sql);
stmt.setInt(1, id);
rs = (ResultSet) 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 e) {
// TODO: handle exception
e.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
新建details.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<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();//创建业务逻辑类对象
//获取上一个页面传过来的id转换成整型,调用getItemsById方法
Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
if (item != null) {
%>
<td width="70%" valign="top">
<table>
<tr>
<td rowspan="4"><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>
</table>
</td>
<%
}
%>
</tr>
</table>
</center>
</body>
</html>
使用Cookie实现保存商品浏览记录
ItemsDAO.java类新增getViewList方法
//获取最近浏览的前5条商品信息
public ArrayList<Items> getViewList(String list){
ArrayList<Items> itemlist = new ArrayList<Items>();
int iCount= 5;
if(list !=null && list.length()>0) {
String[] arr = list.split(",");//根据,分割字符串
//如果商品记录大于等于5条
if(arr.length>=iCount) {
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;
}
}
details.jsp文件整体代码
<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<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();//创建业务逻辑类对象
//获取上一个页面传过来的id转换成整型,调用getItemsById方法
Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
if (item != null) {
%>
<td width="70%" valign="top">
<table>
<tr>
<td rowspan="4"><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>
</table>
</td>
<%
}
%>
<%
String list = "";//创建空的字符串
//从客户端获得Cookies集合
Cookie[] cookies = request.getCookies();
//遍历这个Cookies集合
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
//是否保存过一个名为ListViewCookie的Cookie
if (c.getName().equals("ListViewCookie")) {
//list = c.getValue();//获取ListViewCookie对应的值(id字符串)
list = URLDecoder.decode(c.getValue(), "UTF-8");
}
}
}
list += request.getParameter("id") + ",";
//如果浏览记录超过1000条,清零.
String[] arr = list.split(",");
if (arr != null && arr.length > 0) {
if (arr.length >= 1000) {
list = "";
}
}
//1.保存list到cookie中时需要转码
Cookie cookie = new Cookie("ListViewCookie",URLEncoder.encode(list, "UTF-8"));
cookie.setMaxAge(846000);
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) {
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>