Javaweb学习--显示商品浏览记录

功能:如淘宝侧边栏:您最近浏览过的商品,显示商品的标题图片等信息.

1.项目结构(ViewListDBHelperDemo项目名)


把页面要用到的文件放在WebContent文件夹下,包括images(商品图片), sql(数据库建表), details.jsp(详情页), index.jsp(首页).

其中sql文件夹下的items.sql是里面写的是建表语句,可以复制到终端进行运行建表.


2.工具类com.util.DBHelper / DBHelper.java

/*********************开始***********************/

package com.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&characterEncoding=UTF-8";
private static final String username="root";//数据库的用户名
private static final String password="123456";//数据库的密码
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("数据库连接正常");
System.out.println(conn);
}else {
System.out.println("数据库连接异常");
}
}catch(Exception e) {
e.printStackTrace();
}
}
}

/*********************结束***********************/

注意:连接数据库要时刻注意跑出异常,用try catch进行处理.


sql 文件夹\ items.sql:创建表(数据库名称为shopping 要自己建)

建数据库: 

$ mysql -u root - p

>password 1********

mysql> show databases

mysql>create database shopping

mysql>use shopping

mysql>把下面的代码复制进去就可以完成建表

/*********************开始***********************/


/*
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
*/


SET FOREIGN_KEY_CHECKS=0;
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;


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');

/*********************结束***********************/


3.业务逻辑类com.dao.DAO / ItemsDAO.java

注意引入的包为mysql.jdbc下的.

/*********************开始***********************/

package com.dao;
import java.util.ArrayList;
import com.entity.items;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.util.DBHelper;


//商品的业务逻辑类
public class ItemsDAO {
    //获得所有商品的信息
public ArrayList<items> getAllItems(){
//连接对象
Connection conn = null;
//语句对象( PreparedStatement 用于sql执行参数化查询)
   PreparedStatement stmt = null;
   //数据集(结果集)
   ResultSet rs = null;
   //商品集合
   ArrayList<items> list = new ArrayList<items>();
   //对数据库的操作会抛出异常,要用try catch finally
   try {
    //获得连接对象
   conn = (Connection) 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); //每次遍历完把商品加到list集合中
   }
   return list;
   }
   catch(Exception e){
   e.printStackTrace();
   return null;
   }finally { //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();
   }
  
   }
   }
}
//根据商品编号获取商品资料getItemsById
public items getItemsById(int id) {
//连接对象
Connection conn = null;
//语句对象( PreparedStatement 用于sql执行参数化查询)
   PreparedStatement stmt = null;
   //数据集
   ResultSet rs = null;
   //商品集合
   ArrayList<items> list = new ArrayList<items>();
   //对数据库的操作会抛出异常,要用try catch finally
   try {
    //获得连接对象
   conn = (Connection) 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){
   e.printStackTrace();
   return null;
   }finally { //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){
ArrayList<items> itemlist = new ArrayList<items>();
int iCount = 5;//每次返回前五条记录
if(list!=null && list.length()>0) {
String[]  arr = list.split("#");
if(arr.length>=5) {
for(int i=arr.length-1;i>=arr.length-iCount-1;i--) {
itemlist.add(getItemsById(i));
}
}
return itemlist;
}else {
return null;
}
}
}

/*********************结束***********************/


4.实体类com.entity/items.java /  items.java

商品类items(以后类最好用大写字母开头比较有辨识度),包括商品的各种private属性及getter\setter方法.

/*********************开始***********************/

package com.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;
}


}

/*********************结束***********************/


5.显示页面

/*********************开始***********************/

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="com.entity.items"%>
<%@ page import="com.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="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>

/*********************结束***********************/

6.详情页面

在循环遍历时生成页面结构,开头要引入实体类和逻辑类

/*********************开始**********************/

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ page import="com.entity.items"%>
<%@ page import="com.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")));
            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)
              {
                  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="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>

/*********************结束***********************/

7.数据库

查看表结构:mysql>desc items(表的名字)

 PreparedStatement (语句对象) 

参考:PreparedStatement   http://blog.csdn.net/kingskyleader/article/details/4800397

在数据库的操作过程中,PreparedStatement 对象是一个很不起眼但是记为重要的接口对象,它继承 于Statement,并与之在两方面有所不同:

1)PreparedStatement 实例包含已编译的 SQL 语句。这就是使语句“准备好”。包含于 PreparedStatement 对象中的 SQL 语句可具有一个或多个 IN 参数。IN参数的值在 SQL 语句创建时未被指定。相反的,该语句为每个 IN 参数保留一个问号(“?”)作为占位符。每个问号的值必须在该语句执行之前,通过适当的setXXX 方法来提供。

2)由于 PreparedStatement 对象已预编译过,所以其执行速度要快于 Statement 对象。因此,多次执行的 SQL 语句经常创建为 PreparedStatement 对象,以提高效率。

 

作为 Statement 的子类,PreparedStatement 继承了 Statement 的所有功能。同时,三种方法 execute、 executeQuery 和 executeUpdate 已被更改以使之不再需要参数。这些方法的 Statement 形式(接受 SQL 语句参数的形式)不应该用于 PreparedStatement 对象。

 

 

二.PreparedStatement在java中常用数据库操作 
1 引用特定的包  
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 

2 一般实例化一个PreparedStatement和结果集 
PreparedStatement prepstmt = null; 
ResultSet rs = null; 

3 得到SQL语句 
conn 为Connection类型 
prepstmt = conn.prepareStatement(String StrSQl); 

4 执行SQL,得到结果集 
rs 为ResultSet类型。 
rs = prepstmt.executeQuery();


ResultSet (数据库)结果集 参考:

ResultSet接口介绍(推荐这篇)   ResultSet

对数据库的查询操作,一般需要返回查询结果,在程序中,JDBC为我们提供了ResultSet接口来专门处理查询结果集

Statement通过以下方法执行一个查询操作:

ResultSet executeQuery(String sql) throws SQLException 

单词Query就是查询的意思。函数的返回类型是ResultSet,实际上查询的数据并不在ResultSet里面,依然是在数据库里,ResultSet中的next()方法类似于一个指针,指向查询的结果,然后不断遍历。所以这就要求连接不能断开。

ResultSet接口常用方法:

  • boolean next()     遍历时,判断是否有下一个结果
  • int getInt(String columnLabel)
  • int getInt(int columnIndex)
  • Date getDate(String columnLabel)
  • Date getDate(int columnIndex)
  • String getString(String columnLabel)
  • String getString(int columnIndex)

 

二、ResultSet接口实现查询操作:

步骤如下:(和上一篇博文中的增删改的步骤类似哦)

  • 1、加载数据库驱动程序:Class.forName(驱动程序类)
  • 2、通过用户名密码和连接地址获取数据库连接对象:DriverManager.getConnection(连接地址,用户名,密码)
  • 3、构造查询SQL语句
  • 4、创建Statement实例:Statement stmt = conn.createStatement()
  • 5、执行查询SQL语句,并返回结果:ResultSet rs = stmt.executeQuery(sql)
  • 6、处理结果
  • 7、关闭连接:rs.close()、stmt.close()、conn.close()



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值