web应用开发案例
购物车
gitee连接:https://gitee.com/vertex_summit/officaldocument/tree/master/code tree/Web开发
注意:xml文件不要复制,因为window系统会误读xml的换行
一、业务结构
二、创建Java包
1.在src新建com.review
(在odea下,如果在新建的文件夹或者包名,中包含"."的,系统会按照分级目录创建文件夹,这样的好处是可以方便创建含多个子目录的文件夹)
2.创建Java类
创建DBHelper类,
用于写基本的数据库连接
package com.review;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBHelper {
private static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动
//连接数据库的URL地址
private static final String url="jdbc:mysql://localhost:3306/web_order";//修改要连接的数据库名称
private static final String username="root";//数据库的用户名
private static final String password="你的数据库密码";//数据库的密码
private 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();
}
}
}
创建Items类,
用于封装属性
package com.review;
//商品类
public class Items {
private int id; // 商品编号
private String name; // 商品名称
private String city; // 产地
private int price; // 价格
private int number; // 库存
private String picture; // 商品图片
private int gtypeid;//商品类型
private String gintro;//商品描述
private int gsail;//已经卖出份数
private int row;
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;
}
public void setGintro(String gintro) {
this.gintro = gintro;
}
public String getGintro() {
return gintro;
}
public void setGsail(int gsail) {
this.gsail = gsail;
}
public int getGsail() {
return gsail;
}
public void setGtypeid(int gtypeid) {
this.gtypeid = gtypeid;
}
public int getGtypeid() {
return gtypeid;
}
public void setRow(int row) {
this.row = row;
}
public int getRow() {
return row;
}
}
创建ItemsDAO类,
用于向数据库查询数据和插入数据
package com.review;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
//商品的业务逻辑类
public class ItemsDAO {
// 获得所有的商品信息
public 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 goods;"; // SQL语句
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("goodsid"));
item.setName(rs.getString("gname"));
item.setNumber(rs.getInt("gcount"));
item.setPrice(rs.getInt("gprice"));
item.setPicture(rs.getString("gimage"));
item.setGintro(rs.getString("gintro"));
item.setGtypeid(rs.getInt("gtypeid"));
item.setGsail(rs.getInt("gsail"));
System.out.println("成功获得所有的商品信息");
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 getItemsById(int id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBHelper.getConnection();
String sql = "select * from goods where goodsid=?;"; // SQL语句
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
rs = stmt.executeQuery();
if (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("goodsid"));
item.setName(rs.getString("gname"));
item.setNumber(rs.getInt("gcount"));
item.setPrice(rs.getInt("gprice"));
item.setPicture(rs.getString("gimage"));
item.setGintro(rs.getString("gintro"));
item.setGtypeid(rs.getInt("gtypeid"));
item.setGsail(rs.getInt("gsail"));
System.out.println(getClass()+"查询到数据");
System.out.println("成功根据商品编号获得商品资料");
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();
}
}
}
}
//向购物车添加商品,插入数据
public Items insert(String goodsid,String gname,String gprice,String gimage) {
System.out.println("调用insert方法");
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
int row=0;
try {
conn = DBHelper.getConnection();
String sql="insert into insert_to_shoppingcar (goodsid,gname,gprice,giamge) values (goodsid,gname,gprice,giamge)";
stmt = conn.prepareStatement(sql);
// stmt.setString(1, goodsid);
// stmt.setString(2, gname);
// stmt.setString(3, gprice);
// stmt.setString(4, gimage);
stmt.executeUpdate(sql);
System.out.println("注册模块开始启动");
// Statement stmt=conn.createStatement();//创建一个Statement对象
// stmt.executeUpdate(sql);//执行sql语句
row++;
System.out.println("可以插入数据");
System.out.println(Integer.parseInt(String.valueOf(rs.getInt("goodsid"))));
Items item = new Items();
item.setId(Integer.parseInt(String.valueOf(rs.getInt("goodsid"))));//从网页取到的数据是String类
item.setName(rs.getString("gname"));
item.setPrice(Integer.parseInt(String.valueOf(rs.getInt("gprice"))));
item.setPicture(rs.getString("gimage"));
System.out.println(getClass()+"添加了数据");
System.out.println("成功向购物车添加了数据");
return item;
} 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 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;
}
}
}
三、创建jsp
注意:在创建好web项目或者模型后,idea会自动创建好index.jsp文件,这是tomcat启动默认打开的文件(首先打开)
1.制作主页index.jsp。(显示商品主页)
<%@page import="java.sql.*"%>
<%@ page import="jdk.swing.interop.SwingInterOpUtils" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.imgList {
float:left;
}
.imgList div {
float:left;
padding:5px;
margin:5px;
border:#CCC 1px solid;
}
.imgList div img {
display:block;
width:160px;
height:120px;
}
p{
margin:3px;
padding:3px;
}
</style>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
购物车
<%
ResultSet rs= null;//因为要在try之外访问它
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/web_order",
"root",
"你的数据库密码");
Statement stmt = conn.createStatement();
rs = stmt.executeQuery("select * from goods");
System.out.println("主页注册驱动完成,查询到数据");
}catch(Exception e){
e.printStackTrace();
}
%>
<div class="imgList">
<%
try{
System.out.println("主页开始显示商品");
if(rs!=null){
while(rs.next()){
System.out.println("主页查询数据不为空");
%>
<!-- HTML代码 -->
<div style="border: solid red 1px">
<img src="<%=rs.getString("gimage")%>"/>
<p><%=rs.getString(2)%></p>
<p><%=rs.getString(1)%></p>
<%
System.out.println("主页显示商品正常");
%>
<p>数量:<%=rs.getString(7)%> 单价:<%=rs.getString(3)%></p>
<a href="details.jsp?goodsid=<%=rs.getString(1)%>">加入购物车</a>
</div>
<%
}
}
}catch (Exception e){
}
%>
</div>
</body>
</html>
2.添加details.jsp。商品详情页,在点击商品时会请求打开details.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ page import="com.review.Items"%>
<%@ page import="com.review.ItemsDAO"%>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.nio.charset.StandardCharsets" %>
<%
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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<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;
}
div #shoppingcar_parent{
padding-top: 10px;
display: flex;
justify-content: space-between;
width: 80px;
height: 50px;
}
div #insertshoppingcar{
padding: 10px;
width: 20px;
height: 10px;
}
div #showshoppingcar{
padding-top: 10px;
width: 20px;
height: 10px;
}
</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 =null;
item =itemDao.getItemsById(Integer.parseInt(request.getParameter("goodsid")));
System.out.println("在goodscar.jsp中成功根据商品编号获得商品资料");
if(item!=null)
{
%>
<td width="70%" valign="top">
<table>
<tr>
<%-- 如果要获取其他路径的图片,/目录/item.getPicture()--%>
<td rowspan="4"><img src="<%=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>
<tr>
<td>数量:<%=item.getNumber() %></td>
</tr>
<tr>
<td>描述:<%=item.getGintro() %></td>
</tr>
<tr>
<td>类型:<%=item.getGtypeid() %></td>
</tr>
<tr>
<td>销量:<%=item.getGsail() %></td>
</tr>
</table>
<table>
<div id="shoppingcar_parent">
<%-- 已成功取得商品id--%>
<div id="insertshoppingcar">
<a href="shoppingCar.jsp?goodsid= <%=request.getParameter("goodsid")%>">加入购物车</a>
</div>
<div id="showshoppingcar">
<a href="showShoppingCar.jsp?=<%=request.getParameter("goodsid")%>">查看购物车</a>
</div>
</div>
</table>
</td>
<%
}
%>
</tr>
</table>
</center>
</body>
</html>
3.创建shoppingCar.jsp。用于处理“加入购物车”
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ page import="com.review.ItemsDAO" %>
<%@ page import="com.review.Items" %>
<%--
Created by IntelliJ IDEA.
User: 出猎
Date: 2020/11/23
Time: 15:31
To change this template use File | Settings | File Templates.
--%>
<html>
<head>
<title>shoppingCar</title>
</head>
<body>
<%
String goodsid=request.getParameter("goodsid");
String gname=request.getParameter("gname");
String gprice=request.getParameter("gprice");
String gimage=request.getParameter("gimage");
System.out.println(goodsid.getClass().getName());//输出变量的类型
%>
<%
ItemsDAO itemDao = new ItemsDAO();
Items item =null;
item =itemDao.insert(goodsid,gname,gprice,gimage);
System.out.println("在shoppingCar.jsp中准备要将商品添加到数据库中");
%>
<jsp:forward page="index.jsp">
<jsp:param name="uname" value="<%=goodsid%>"/></jsp:forward>
<%-- param 中name是变量名 value是变量值,在forward里面,所以会将uname传递到index页面--%>
<%
if(item!=null)
{
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("添加购物车成功,开始跳转主页面!");
}
%>
</body>
</html>
4.创建showShoppingCar.jsp。用于处理“查看购物车”
<%--
Created by IntelliJ IDEA.
User: 出猎
Date: 2020/11/23
Time: 16:21
To change this template use File | Settings | File Templates.
--%>
<%@page import="java.sql.*"%>
<%@ page import="jdk.swing.interop.SwingInterOpUtils" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>Title</title>
<style type="text/css">
.imgList {
float:left;
}
.imgList div {
float:left;
padding:5px;
margin:5px;
border:#CCC 1px solid;
}
.imgList div img {
display:block;
width:160px;
height:120px;
}
p{
margin:3px;
padding:3px;
}
</style>
</head>
<body>
<%
ResultSet rs= null;//因为要在try之外访问它
int count=0;
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/web_order",
"root",
"你的数据库密码");//基于MySQL数据库开发的,Oracle的在注册驱动和建立连接会有些不同
Statement stmt = conn.createStatement();
//select count(*) from 表名;
rs = stmt.executeQuery("select * from insert_to_shoppingcar");
}catch(Exception e){
e.printStackTrace();
}
%>
<div class="imgList">
<%
try{
if(rs != null){
while(rs.next()){
count++;
%>
<!-- HTML代码 -->
<div style="border: solid red 1px">
<img src="<%=rs.getString("gimage")%>"/>
<p><%=rs.getString(2)%></p>
<p>商品编号<%=rs.getString(1)%></p>
<%
%>
<p>单价:<%=rs.getString(3)%></p>
</div>
<%
}
}
}catch (Exception e){
}
%>
<p>购物车添加了:<%=count%>件商品 </p>
</div>
</body>
</html>
四、构建数据库
导入两个sql文件
1.goods.sql
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (0, '平板', 21, 3, '电子产品', 'img/s02.jpg', 2543, 232, 12, '0000-00-00 00:00:00', '234');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (1, '牛奶糖', 1, 1, '好吃不贵', 'img/s03.jpg', 1000, 500, 1, '2020-10-06 14:50:08', '10');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (2, '巧克力', 8, 1, '好吃但贵', 'img/s01.jpg', 100, 30, 1, '2020-10-01 14:52:17', '30');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (3, '果冻', 2, 1, '好吃不贵', 'img/s04.jpg', 500, 400, 2, '2020-10-03 14:54:24', '15');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (4, '冰棍', 3, 1, '不好吃又贵', 'img/s05.jpg', 299, 100, 3, '2020-10-07 14:55:36', '30');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (5, '充电宝', 50, 2, '电子产品', 'img/s06.jpg', 50, 20, 10, '2020-10-02 14:56:36', '50');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (6, '充电器', 20, 2, '电子产品', 'img/s01.jpg', 100, 80, 4, '2020-10-06 14:57:19', '30');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (7, '鼠标', 100, 2, '电子产品', 'img/s02.jpg', 20, 10, 8, '2020-10-03 14:57:55', '45');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (8, 'iPhone', 5000, 2, '电子产品', 'img/s03.jpg', 10, 5, 15, '2020-10-08 14:58:39', '200');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (9, '电视', 2000, 1, '家用电器', 'img/s04.jpg', 20, 15, 200, '2020-10-07 15:00:01', '300');
INSERT INTO web_order.goods (GoodsID, Gname, Gprice, GtypeID, Gintro, Gimage, Gcount, Gsail, Gweight, GDateTime, Gsize) VALUES (10, 'apple', 5400, 1, '苹果', 'img/s01.jpg', 4534, 23, 19, '2020-05-23 18:34:48', '12');
2.insert_to_shoppingcar.sql
INSERT INTO web_order.insert_to_shoppingcar (goodsid, gname, gprice, gimage) VALUES ('10', 'apple', '5400', 'img/s01.jpg');