Jsp入门案例(实现简易的商品信息展示)
Posted Cardiolith
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jsp入门案例(实现简易的商品信息展示)相关的知识,希望对你有一定的参考价值。
引言:最近在慕课网上学习了基础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> 以上是关于Jsp入门案例(实现简易的商品信息展示)的主要内容,如果未能解决你的问题,请参考以下文章IDEA+Java+SSM+Jsp+Mysql实现Web商品信息管理系统