您的位置:首页 > 编程语言 > Java开发

Java Web学习(22): 阶段小项目实现商品浏览记录

2016-07-27 17:23 477 查看
       案例项目:商品浏览记录的实现

       项目架构:采用Model1模式(JSP+JavaBean)实现

       具体的步骤:

       1)实现DBHelper类

       2)创建实体类

       3)创建页面层

       4)创建业务逻辑类(DAO)

       项目目录结构:

       


       DBHelper类

       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: 2016-07-12 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');
       MySQL客户端显示:

       


       DBHelper.java工具类源代码:

package com.util;

import java.sql.Connection;
import java.sql.DriverManager;

/**
* 连接MySQL数据库工具类
* @author Administrator
* @date 2016年7月12日
*/
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="root";
//Connection连接对象conn
private static Connection conn=null;

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

//单例模式返回数据库连接对象
public static Connection getConnection() throws Exception{
if(conn==null){
conn = DriverManager.getConnection(url, username, password);
return conn;
}else{
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 e){
e.printStackTrace();
}

}
}

       连接MySQL数据库的测试结果:

       


       Items.java实体类源代码:

package com.entity;

/**
* 商品实体类
* @author Administrator
* @date 2016年7月12日
*/
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;
}

}
       index.jsp商品列表页面源代码:

<%@page import="java.util.ArrayList"%>
<%@ page import="com.entity.Items"%>
<%@ page import="com.dao.ItemsDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>商品列表页面</title>
<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>
           <!-- 商品循环开始 -->      
           <% 
               //防止中文乱码
               request.setCharacterEncoding("utf-8");
            
               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() %>  价格:¥ <%=item.getPrice() %></dd> 
             </dl>
          </div>
          <!-- 商品循环结束 -->
          <%
                   }
              } 
          %>
        </td>
      </tr>
    </table>
    </center>
</body>
</html>


       details.jsp商品详情页面源代码:

<%@page import="java.util.ArrayList"%>
<%@ page import="com.entity.Items"%>
<%@ page import="com.dao.ItemsDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>商品详情页面</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();
                 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() %>  价格:<%=i.getPrice() %> ¥ </dd> 
             </dl>
             </div>
             <% 
                        }
                   }
             %>
             <!-- 循环结束 -->
          </td>
        </tr>
      </table>
    </center>
</body>
</html>


       ItemsDAO.java业务逻辑类源代码:

package com.dao;

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

import com.util.DBHelper;
import com.entity.Items;

/**
* 商品的业务逻辑类
* @author Administrator
* @date 2016年7月12日
*/
public class ItemsDAO {

// 获得所有的商品信息
public ArrayList<Items> getAllItems() {
Connection conn = null;//数据库连接对象
PreparedStatement stmt = null;//SQL语句对象
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 e) {
e.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception e) {
e.printStackTrace();
}
}
// 释放SQL语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}

}

// 根据商品编号ID获得商品详细资料
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);
//把id的值赋给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 e) {
e.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception e) {
e.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception e) {
e.printStackTrace();
}
}

}
}

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

}
       测试:

       


   


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