JSP 商品浏览[Web application]

JSP 商品信息[Web]

采用Model1(jsp+Javabean)实现

  • 实现DBHelper类(连接数据库)
  • 创建实体类
  • 创建业务逻辑类(DAO)
  • 创建页面层

一、环境准备

1.1 MySQL 安装

Mac 安装方式
  1. 官网下载安装包dmg即可
  2. 安装
  3. 偏好设置启动mysql
  4. 配置bash_profile
  5. 添加“export PATH=$PATH:/usr/local/mysql/bin”

下载MySQL驱动 JDBC

1.2 创建项目

IDEA选择: Java Enterprise -> Web application
配置项目:

  1. WEB_INF 内创建 classes 和 lib 文件夹
  2. File -> Project Structure -> paths -> Use module compile output path 选择classes文件夹
  3. File -> Project Structure -> Dependecies -> “+”号 -> JAR… -> 选择创建的lib文件夹

1.3 数据库创建

开启终端:登录数据库

mysql -u root -p

创建一个新的数据库 -> shopping :

create database shopping;

查看是否创建成功:

show databases;

1.4 连接数据库测试

IDEA: View -> Tool Windows -> Database

  • : 选择 Data Source -> MySQL

Database:shopping
再填写用户名+密码,Test Connection

1.5 创建数据库内容

1. 打开 Navicat,进入shopping数据库
2. Query 选择 New Query

复制粘贴:

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

运行,生成表

1.5.3 刷新数据库,查看结果

1.6 存放数据库的图片到Web项目

  1. 项目中web目录下新建一个文件夹images
  2. 找10张图片放入,命名格式”001.jpg”,”002.jgp”…

二、DBHelper类 连接数据库

定义静态变量:数据库驱动

public static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动
//连接数据库的URL地址
public static final String url = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&charactorEncoding=UTF-8";
public static final String username = "root";
public static final String password = "amoy1205";
public 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){
        ex.printStackTrace();
    }
}

三、item 类(存放商品实体)

定义商品属性 :

private int id ; //商品编号
private String name; //商品名称
private String city; //产地
private int price;  //价格
private int number;  //库存
private String picture; //商品图片

四、ItemDAO 类 (业务逻辑类)

4.1 获取全部商品信息的方法

通过SQL语句:select * from Items; 从表items查询结果。

public ArrayList<Items> getAllItems()
{
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null; //(ResultSet)是数据中查询结果返回的一种对象
    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 {
        //释放数据集对象
        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();
            }
        }
    }
}

执行SQL语句要记得捕获异常,且要用finally释放资源。

PreparedStatement : 执行SQL查询语句的API之一
「JDBC 中preparedStatement和Statement区别」参考资料: https://blog.csdn.net/xuebing1995/article/details/72235380

4.2 根据商品编号获取商品信息

public Items getItemsById()
和获取全部信息的代码差不多,这里仅修改try{}里的代码:

  1. 修改sql查询语句
  2. stmt.setInt(1,id)将指定的参数设置为给定的java int值, sql将查询id匹配的条目
  3. 查询结果不用循环
  4. 返回item而不是list
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;
    }
}

4.3 通过cookie实现 商品浏览记录DAO

① 传入list字符串,通过分隔符”#”识别出不同的商品id,存放到字符串数组arr中

注意: Tomcat高版本中,Cookie对象的构造函数的两个字符串参数:Cookie名字和Cookie值都不能包含空白字符以及下列字符:[]() < > = , " / ? @ :
因此,分隔符采用”#”

② 根据分割后的id,查询商品信息,添加到itemlist中,返回

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

五、页面层

5.1 index.jsp

5.1.1 <head> 中添加css样式
  <head>
    <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>
5.1.2 获取全部商品信息
调用ItemsDAO的getAllItems() 获得所有商品的Item实例

遍历打印商品信息:

    <h1>商品展示</h1>
    <hr>
    <table>
        <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>
为图片设置超链接,目的:进入到商品详情页面

5.2 details.jsp

实现功能:显示商品详情(点取超链接时传入的id值再调用ItemsDAO的getItemsById()获取商品信息)+最近浏览商品记录(cookie实现)

css样式和index.jsp相同,复制即可

<body>中需要处理的:
① 从request中获取cookie: request.getCookies()
② 获取本项目Cookie对应的字符串

  if(c.getName().equals("ListViewCookie"))
  {
     list = c.getValue();
  }

③ 追加本次浏览的记录:

list+=request.getParameter("id")+"#";

④ 创建新的cookie对象,并将其放到response:

  Cookie cookie = new Cookie("ListViewCookie",list);
  response.addCookie(cookie);

⑤ 再通过ItemsDAO的getViewList()获取cookie的字符串,根据返回的列表打印最近浏览的记录

<body>标签中添加完整代码:

  <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() %>&nbsp;&nbsp;价格:<%=i.getPrice() %> ¥ </dd> 
         </dl>
         </div>
         <% 
               }
            }
         %>
         <!-- 循环结束 -->
      </td>
    </tr>
  </table>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值