引言:最近在慕课网上学习了基础Jsp入门教学视频,在课程的最后有一个案例项目,以Jsp+JavaBean模式实现商品信息展示的Java Web Project。今天我就简单地回顾一下这个项目的流程。
一. 项目总体介绍
- 预期效果
- 流程概述
° 实现DBHelper类(数据库连接)
° 创建实体类(Items)
° 创建业务逻辑类(ItemsDAO)
° 创建页面层
二. 项目实现
1. DBHelper类设计
在工程目录src文件夹下创建util包,包中新建DBHelper类。
DBHelper类的目的是建立与MySQL数据库的连接。
package util; import java.sql.Connection; import java.sql.DriverManager; public class DBHelper { private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8"; private static final String USERNAME = "root"; private static final String PASSWORD = "******"; private static Connection con = null; //加载数据库驱动 static { try{ Class.forName(DRIVER); }catch(Exception ex){ ex.printStackTrace(); } } //单例模式返回数据库连接对象 public static Connection getConnection() throws Exception{ if(con==null){ con = DriverManager.getConnection(URL, USERNAME, PASSWORD); return con; } return con; } }
同时不要忘记在工程文件中导入MySQL对应驱动程序的jar包。
在navicat中创建shopping数据库并执行以下语句创建items表和插入数据
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');
2. 实体类(Items)设计
Items类中数据成员对应表items的属性,右键Source选择为每个数据成员进行封装。
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; } }
3. 业务逻辑类(ItemsDAO)设计
ItemsDAOS类主要是实现以后要在Jsp页面中运送数据的方法,包括获取所有商品资料,根据id获取对应商品资料和获取浏览记录中最近5条记录。
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import entity.Items; import util.DBHelper; public class ItemsDAOS { //获取数据库内所有的商品资料 public ArrayList<Items> getAllItems(){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; ArrayList<Items> list = new ArrayList<>(); //商品集合 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.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=?;"; //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.setPrice(rs.getInt("price")); item.setNumber(rs.getInt("number")); item.setPicture(rs.getString("picture")); return item; }else{ 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(); } } } } //获取最近浏览的5条商品资料 public ArrayList<Items> getViewList(String list){ ArrayList<Items> itemList = new ArrayList<>(); 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;i--){ itemList.add(getItemById(Integer.valueOf(arr[i]))); } } else{ for(int i=arr.length-1;i>=0;i--){ itemList.add(getItemById(Integer.valueOf(arr[i]))); } } return itemList; }else { return null; } } }
4. 页面层的设计
最后一步是在jsp页面中实现浏览商品信息。
主页index.jsp
1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> 2 <%@ page import="dao.ItemsDAOS" %> 3 <%@ page import="entity.Items" %> 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 14 <title>My JSP 'index.jsp' starting page</title> 15 <meta http-equiv="pragma" content="no-cache"> 16 <meta http-equiv="cache-control" content="no-cache"> 17 <meta http-equiv="expires" content="0"> 18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 19 <meta http-equiv="description" content="This is my page"> 20 <!-- 21 <link rel="stylesheet" type="text/css" href="styles.css"> 22 --> 23 <style type="text/css"> 24 div{ 25 float: left; 26 margin: 10px; 27 } 28 div dd{ 29 margin: 0px; 30 font-size: 10px; 31 } 32 div dd.dd_name{ 33 color: blue; 34 } 35 div dd.dd_city{ 36 color: #000; 37 } 38 </style> 39 </head> 40 41 <body> 42 <h1>商品展示</h1> 43 <hr> 44 45 <center> 46 <table width="750" height="60" cellpadding="0" cellspacing="0" border="0"> 47 <tr> 48 <td> 49 50 <!-- 商品循环开始 --> 51 <% 52 ItemsDAOS itemsDao = new ItemsDAOS(); 53 ArrayList<Items> list = itemsDao.getAllItems(); 54 if(list!=null&&list.size()>0){ 55 for(int i=0;i<list.size();i++){ 56 Items item = list.get(i); 57 %> 58 <div> 59 <dl> 60 <dt> 61 <a href="details.jsp?id=<%=item.getId() %>"><img src="images/<%=item.getPicture() %>" width="120" height="120"></a> 62 </dt> 63 <dd class="dd_name"><%=item.getName() %></dd> 64 <dd class="dd_city">产地:<%=item.getCity() %> 价格:<%=item.getPrice() %></dd> 65 </dl> 66 </div> 67 <!-- 商品循环结束 --> 68 <% 69 } 70 } 71 %> 72 73 </td> 74 </tr> 75 </table> 76 </center> 77 </body> 78 </html>
商品详情页details.jsp
1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> 2 <%@ page import="dao.ItemsDAOS" %> 3 <%@ page import="entity.Items" %> 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 14 <title>My JSP 'details.jsp' starting page</title> 15 16 <meta http-equiv="pragma" content="no-cache"> 17 <meta http-equiv="cache-control" content="no-cache"> 18 <meta http-equiv="expires" content="0"> 19 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 20 <meta http-equiv="description" content="This is my page"> 21 22 <style type="text/css"> 23 div{ 24 float: left; 25 margin: 10px; 26 } 27 div dd{ 28 margin: 0px; 29 font-size: 10px; 30 } 31 div dd.dd_name{ 32 color: blue; 33 } 34 div dd.dd_city{ 35 color: #000; 36 } 37 </style> 38 </head> 39 40 <body> 41 <h1>商品详情</h1> 42 <hr> 43 <center> 44 <table width="750" height="60" cellpadding="0" cellspacing="0" border="0"> 45 <tr> 46 <!-- 商品详情 --> 47 <% 48 ItemsDAOS itemsDao = new ItemsDAOS(); 49 Items item = itemsDao.getItemById(Integer.valueOf(request.getParameter("id"))); 50 if(item!=null){ 51 %> 52 <td width="70%" valign="top"> 53 <table> 54 <tr> 55 <td rowspan="4"><img src="images/<%=item.getPicture() %>" width="200" height="200"/></td> 56 </tr> 57 <tr> 58 <td><B><%=item.getName() %></B></td> 59 </tr> 60 <tr> 61 <td>产地:<%=item.getCity() %></td> 62 </tr> 63 <tr> 64 <td>价格:<%=item.getPrice() %></td> 65 </tr> 66 </table> 67 </td> 68 <% 69 } 70 %> 71 <% 72 String list = ""; 73 Cookie[] cookies = request.getCookies(); 74 if(cookies!=null&&cookies.length>0){ 75 for(Cookie c: cookies){ 76 if(c.getName().equals("listViewCookie")){ 77 list = c.getValue(); 78 } 79 } 80 } 81 list+=request.getParameter("id")+","; 82 //如果浏览记录超过1000条,清零 83 String[] arr = list.split(","); 84 if(arr!=null&&arr.length>0){ 85 if(arr.length>=1000) 86 list = ""; 87 } 88 89 Cookie cookie = new Cookie("listViewCookie",list); 90 response.addCookie(cookie); 91 %> 92 <!-- 浏览过的商品 --> 93 <td width="30%" bgcolor="#EEE" align="center"> 94 <br> 95 <b>您浏览过的商品</b><br> 96 <!-- 循环开始 --> 97 <% 98 ArrayList<Items> itemsList = itemsDao.getViewList(list); 99 if(itemsList!=null&&itemsList.size()>0){ 100 for(Items i: itemsList) 101 { 102 %> 103 <div> 104 <dl> 105 <dt> 106 <a href="details.jsp?id="<%=i.getId() %>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"></a> 107 </dt> 108 <dd class="dd_name"><%=i.getName() %></dd> 109 <dd class="dd_city">产地:<%=i.getCity() %> 价格:<%=i.getPrice() %></dd> 110 </dl> 111 </div> 112 <% 113 } 114 } 115 %> 116 <!-- 循环结束 --> 117 </td> 118 </tr> 119 </table> 120 </center> 121 </body> 122 </html>
三. 项目总结
在Jsp中执行脚本获取Items对象,再通过Items中封装的方法来获取信息在页面上显示。(对象判空不可缺,否则运行服务器加载页面会报错)
Jsp页面 ——参数——> Java类方法
Jsp页面 <——数据—— Java类方法
Jsp基础学习已经告一段落,明天我将整理一下Jsp相关基础知识,之后会通过专业书籍进一步提高对Jsp的了解。
---每天积累一点点,吃水不忘挖井人---