- 疫情期间 朋友的作业 唉!!!
- 帮忙搞搞吧
— 创建个Maven项目 (JBoss -->web application都行)
来到了我的久违象牙白界面
- 先来看看小老妹的需求
- ojbk 搞起
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 USERNAME = "root";
private static final String PASSWORD = "xxxxxx";
private static final String dbName = "shop_show";
private static Connection con = null;
private static final String URL ="jdbc:mysql://localhost/"+dbName+"?user="+USERNAME+"&password="+PASSWORD;
//连接URL为 jdbc:mysql//服务器地址/数据库名?user=登陆用户名&password=密码
//加载数据库驱动
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启动和关闭外键约束的方法(FOREIGN_KEY_CHECKS)
[Err] 1451 -Cannot delete or update a parent row: a foreign key constraint fails (...)
这是因为MySQL中设置了foreign key关联,造成无法更新或删除数据。可以通过设置FOREIGN_KEY_CHECKS变量来避免这种情况。
我们可以使用
SET FOREIGN_KEY_CHECKS=0;
来禁用外键约束.
之后再用
SET FOREIGN_KEY_CHECKS=1;
来启动外键约束.
eg:
SET FOREIGN_KEY_CHECKS = 0;
DELETE FROM TABLE_NAME_;
SET FOREIGN_KEY_CHECKS = 1;
查看当前FOREIGN_KEY_CHECKS的值可用如下命令
SELECT @@FOREIGN_KEY_CHECKS;
在navicat中创建 数据库并执行以下语句创建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');
- 而且 最好不用中文版 --en 毛病太多
- 且 从新配置下 环境
不要忘记在工程文件中导入MySQL对应驱动程序的jar包
实体类(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;
}
}
业务逻辑类(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;
import static java.lang.System.out;
public class ItemsDAO {
//获取数据库内所有的商品资料
public static ArrayList<Items> getAllItems(){
Connection conn = null;
PreparedStatement stmt = null;
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();
out.print(rs);
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();
}
}
}
}
//获取最近浏览的5条商品资料
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;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;
}
}
}
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="dao.ItemsDAO" %>
<%@ page import="entity.Items" %>
<%
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: 10px;
}
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="120"></a>
</dt>
<dd class="dd_name"><%=item.getName() %></dd>
<dd class="dd_city">产地:<%=item.getCity() %> 价格:<%=item.getPrice() %></dd>
</dl>
</div>
<!-- 商品循环结束 -->
<%
}
}
%>
<%-- <%@ page contentType="text/html; charset=utf-8" %>--%>
<%-- <%@ page language="java" %>--%>
<%-- <%@ page import="com.mysql.jdbc.Driver" %>--%>
<%-- <%@ page import="java.sql.*" %>--%>
<%-- <%@ page import="java.util.*" %>--%>
<%-- <%--%>
<%-- String driverName="com.mysql.jdbc.Driver"; //驱动程序 --%>
<%-- String userName="map"; //Mysql用户名 --%>
<%-- String userPasswd="mapadmin"; //密码 --%>
<%-- String dbName="maptest";//数据库名 --%>
<%-- String tableName="deviceinfo";//数据表名 --%>
<%-- String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;--%>
<%-- //连接URL为 jdbc:mysql//服务器地址/数据库名?user=登陆用户名&password=密码--%>
<%-- Class.forName("com.mysql.jdbc.Driver").newInstance(); //加载驱动程序 --%>
<%-- Connection conn=DriverManager.getConnection(url); //获取数据库连接 --%>
<%-- Statement stmt = conn.createStatement(); //创建Statement对象 --%>
<%-- String sql="SELECT * FROM "+tableName; //SQL语句--%>
<%-- ResultSet rs = stmt.executeQuery(sql); //执行SQL语句--%>
<%-- List<String> list = new ArrayList<String>(); //list--%>
<%-- while(rs.next()) {--%>
<%-- list.add (rs.getString("Name"));//将Name加入到list中 --%>
<%-- }--%>
<%-- out.println("打印 list:");--%>
<%-- out.print(list);--%>
<%-- //关闭资源--%>
<%-- rs.close();--%>
<%-- stmt.close();--%>
<%-- conn.close();--%>
<%-- %>--%>
</td>
</tr>
</table>
</center>
</body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="dao.ItemsDAO" %>
<%@ page import="entity.Items" %>
<%
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">
<style type="text/css">
div{
float: left;
margin: 10px;
}
div dd{
margin: 0px;
font-size: 10px;
}
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 itemsDao = new ItemsDAO();
Items item = itemsDao.getItemById(Integer.valueOf(request.getParameter("id")));
if(item!=null){
%>
<td width="70%" valign="top">
<table>
<tr>
<td rowspan="4"><img src="images/<%=item.getPicture() %>" width="200" height="200"/></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 = "";
Cookie[] cookies = request.getCookies();
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> itemsList = itemsDao.getViewList(list);
if(itemsList!=null&&itemsList.size()>0){
for(Items i: itemsList)
{
%>
<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>