这次实验的要求是使用mvc设计模式完成一个购物车的项目 使用技术是java中jsp+servlet+javabean+jdbc,实现MVC分层设计模式,数据库采用的是mysql
接下来我们一步一步的来完成这个项目,首先是对整个项目的设计模式与逻辑进行分析
在MVC模式中,一个应用被划分成了模型(Model)、视图(View)和控制器(Controller)三个部分,接下来认识一下这三个部分。
1:首先看一下模型、视图、控制器各部分的作用
模型(Model):负责封装应用的状态,并实现应用的功能。通常又分为数据模型和业务逻辑模型,数据模型用来存放业务数据,比如订单信息、用户信息等;而业务逻辑模型包含应用的业务操作,比如订单的添加或者修改等。
视图(View):用来将模型的内容展现给用户,用户可以通过视图来请求模型进行更新。视图从模型获得要展示的数据,然后用自己的方式展现给用户,相当于提供界面来与用户进行人机交互;用户在界面上操作或者填写完成后,会点击提交按钮或是以其它触发事件的方式,来向控制器发出请求。
控制器(Controller):用来控制应用程序的流程和处理视图所发出的请求。当控制器接收到用户的请求后,会将用户的数据和模型的更新相映射,也就是调用模型来实现用户请求的功能;然后控制器会选择用于响应的视图,把模型更新后的数据展示给用户。
2:模型和视图的关系
在MVC中,模型和视图是分离的,通常视图里面不会有任何逻辑实现;而模型也是不依赖于视图的,同一个模型可能会有很多种不同的展示方式,也就是同一个模型可以对应多种不同的视图。
1.搭建开发环境
1)导入jdbc驱动的jar包
2)创建程序所在的包
2.数据库的建表
DROP TABLE IF EXISTS `admininfo`;
CREATE TABLE `admininfo` (
`Aid` int(11) NOT NULL,
`Aname` varchar(50) NOT NULL,
`Apwd` varchar(20) NOT NULL,
`Alevel` varchar(10) DEFAULT NULL,
PRIMARY KEY (`Aid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of admininfo
-- ----------------------------
INSERT INTO `admininfo` VALUES ('1', 'admin', 'adminadmin', '超级');
INSERT INTO `admininfo` VALUES ('2', 'admin2', 'adminadmin', '超级');
-- ----------------------------
-- Table structure for `goodsinfo`
-- ----------------------------
DROP TABLE IF EXISTS `goodsinfo`;
CREATE TABLE `goodsinfo` (
`Gid` int(11) NOT NULL,
`Gname` varchar(100) NOT NULL,
`Gprice` double NOT NULL,
`Gclass` varchar(50) DEFAULT NULL,
`Gamount` int(11) NOT NULL,
`Gdate` datetime DEFAULT NULL,
`Gimgurl` varchar(100) DEFAULT NULL,
`Glook` int(11) DEFAULT NULL,
`Gintro` text,
`Gbrief` text,
PRIMARY KEY (`Gid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of goodsinfo
-- ----------------------------
INSERT INTO `goodsinfo` VALUES ('7', '华为 荣耀畅玩4X 双卡双待 全网通4G智能手机 移动/联通/电信 4G/3G/2G(金色)', '800', '手机分类', '18', '2015-06-09 18:55:29', 'http://img12.360buyimg.com/n4/g13/M02/07/02/rBEhU1NSCG8IAAAAAAGn2uh3er4AAMGLwCNdkUAAafy554.jpg', '12', '华为 荣耀畅玩4X 双卡双待 全网通4G智能手机 移动/联通/电信 4G/3G/2G(金色)', '华为 荣耀畅玩4X 双卡双待 全网通4G智能手机 移动/联通/电信 4G/3G/2G(金色)');
INSERT INTO `goodsinfo` VALUES ('8', '三星 Galaxy S6 edge(G9250)32G版 (铂光金)全网通4G手机 双曲面', '1500', '手机分类', '2000', '2015-06-09 00:00:00', 'http://image4.suning.cn/b2c/catentries/000000000126894718_1_200x200.jpg', '20', '三星 Galaxy S6 edge(G9250)32G版 (铂光金)全网通4G手机 双曲面\r\n让未来现在就来!现货发售!下单即送专用皮套+钢化膜+49元实用六件套礼包!', '三星 Galaxy S6 edge(G9250)32G版 (铂光金)全网通4G手机 双曲面\r\n\r\n 品牌:三星\r\n 型号:G9250\r\n 上市时间:2015.04\r\n 颜色:金色\r\n CPU核数:八核\r\n 手机操作系统:Android\r\n 手机制式:多模(WCDMA/GSM+TD-SCDMA/GSM)\r\n 屏幕尺寸:5.1英寸\r\n 摄像头像素:1600万像素');
INSERT INTO `goodsinfo` VALUES ('9', '计算机导论', '20', '计算机类书籍', '666', '2015-06-09 00:00:00', 'http://img5.douban.com/lpic/s1502278.jpg', '10', '计算机导论说明计算机导论说明计算机导论说明计算机导论说明计算机导论说明计算机导论说明计算机导论说明计算机导论说明计算机导论说明计算机导论说明', '简介简介简介简介简介简介简介简介简介简介');
INSERT INTO `goodsinfo` VALUES ('10', 'Apple iPhone 5s (16GB) (金色) 4G手机开放版', '5000', '手机分类', '540', '2015-06-09 19:02:18', 'http://image5.suning.cn/b2c/catentries/000000000123129118_1_200x200.jpg', '120', 'Apple iPhone 5s (16GB) (金色) 4G手机开放版\r\n官方授权 正品行货 好评过万!限量疯抢!库存紧俏!支持移动/联通网络,畅享4G/3G高速网络!', '· 下单后2小时内送达,点击查看您所在地址是否支持\r\n门店现货 · 选择有现货的门店下单,可立即提货\r\n免费贴膜 · 门店专业贴膜师将免费为您的设备贴膜');
INSERT INTO `goodsinfo` VALUES ('11', '大学语文', '30', '大学生必修课', '666', '2015-06-09 19:03:28', 'http://www.eyjx.com/admin/uploadpic/2009419131918358.jpg', '10', '大学语文大学语文大学语文大学语文大学语文大学语文大学语文大学语文大学语文大学语文大学语文', '课本简介课本简介课本简介课本简介课本简介');
-- ----------------------------
-- Table structure for `ordergoods`
-- ----------------------------
DROP TABLE IF EXISTS `ordergoods`;
CREATE TABLE `ordergoods` (
`OGid` int(11) NOT NULL,
`Uid` int(11) NOT NULL,
`Gid` int(11) NOT NULL,
`Oid` int(11) NOT NULL,
`OGamount` int(11) NOT NULL,
`OGtotalprice` double NOT NULL,
PRIMARY KEY (`OGid`),
KEY `FK_Reference_2` (`Uid`),
KEY `FK_Reference_3` (`Gid`),
KEY `FK_Reference_4` (`Oid`),
CONSTRAINT `FK_Reference_2` FOREIGN KEY (`Uid`) REFERENCES `userinfo` (`Uid`),
CONSTRAINT `FK_Reference_3` FOREIGN KEY (`Gid`) REFERENCES `goodsinfo` (`Gid`),
CONSTRAINT `FK_Reference_4` FOREIGN KEY (`Oid`) REFERENCES `orderinfo` (`Oid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of ordergoods
-- ----------------------------
INSERT INTO `ordergoods` VALUES ('2', '2', '7', '21', '2', '1600');
INSERT INTO `ordergoods` VALUES ('3', '2', '8', '23', '1', '1500');
INSERT INTO `ordergoods` VALUES ('4', '2', '7', '25', '2', '1600');
-- ----------------------------
-- Table structure for `orderinfo`
-- ----------------------------
DROP TABLE IF EXISTS `orderinfo`;
CREATE TABLE `orderinfo` (
`Oid` int(11) NOT NULL,
`Aid` int(11) DEFAULT NULL,
`Odate` datetime NOT NULL,
`Ostate` varchar(20) DEFAULT NULL,
`Orecname` varchar(50) NOT NULL,
`Orecadr` varchar(200) NOT NULL,
`Orectel` varchar(20) DEFAULT NULL,
`Uid` int(11) DEFAULT NULL,
`Ototalprice` double DEFAULT NULL,
PRIMARY KEY (`Oid`),
KEY `FK_Reference_1` (`Aid`),
CONSTRAINT `FK_Reference_1` FOREIGN KEY (`Aid`) REFERENCES `admininfo` (`Aid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of orderinfo
-- ----------------------------
INSERT INTO `orderinfo` VALUES ('21', null, '2015-06-10 08:16:57', '未发货', '地方时', '地方时', '地方时', '2', '1600');
INSERT INTO `orderinfo` VALUES ('23', null, '2015-06-10 08:19:03', '未发货', '收货人姓名', '收货人地址', '收货人电话', '2', '1500');
INSERT INTO `orderinfo` VALUES ('25', '1', '2015-06-10 09:13:53', '已发货', '收货人姓名01', '收货人地址01', '18314412345', '2', '1600');
-- ----------------------------
-- Table structure for `userinfo`
-- ----------------------------
DROP TABLE IF EXISTS `userinfo`;
CREATE TABLE `userinfo` (
`Uid` int(11) NOT NULL,
`Uname` varchar(50) NOT NULL,
`Upwd` varchar(20) NOT NULL,
`Uemail` varchar(100) DEFAULT NULL,
PRIMARY KEY (`Uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of userinfo
-- ----------------------------
INSERT INTO `userinfo` VALUES ('1', 'yed', '123456789', '1234567892QQ.COM');
INSERT INTO `userinfo` VALUES ('2', 'text01', '123456', '1234567892QQ.COM');
INSERT INTO `userinfo` VALUES ('3', 'text02', '123456', '1234567892QQ.COM');
INSERT INTO `userinfo` VALUES ('4', 'text03', '123456', '1234567892QQ.COM');
INSERT INTO `userinfo` VALUES ('5', 'text04', '123456', '1234567892QQ.COM');
INSERT INTO `userinfo` VALUES ('6', 'text05', '123456', '1234567892QQ.COM');
数据库操作工具类
package test5;
import java.sql.*;
public class DataBaseConnection {
private static String driverStr="com.mysql.jdbc.Driver";//驱动列表
private static String connStr="jdbc:mysql://localhost/mySql";//mySql是我自己的数据库名
private static String dbusername="root";//数据库用户名
private static String dbpassword="12345678";//密码和数据库一致
private static Connection conn=null;//数据库的连接对象
private Statement stmt=null;//创建Statement对象
public DataBaseConnection() { }
//一个静态方法,返回一个数据库的连接,这样达到了对数据库连接统一控制的目的
public static Connection getConnection() throws SQLException {
try{
Class.forName(driverStr);//加载驱动程序
conn = DriverManager.getConnection(connStr,dbusername, dbpassword);//连接数据库
}
catch(Exception ex){System.out.println("无法同数据库建立连接!");}
return conn;
}
public int executeUpdate(String s)
{
int result=0;
try{
stmt = conn.createStatement();//创建Statement语句
result=stmt.executeUpdate(s);//执行更新语句
}
catch(Exception ex){System.out.println("执行更新错误!");}
return result;
}
public ResultSet executeQuery(String s)
{
ResultSet rs=null;
try{rs=stmt.executeQuery(s);}//执行查询语句
catch(Exception ex){System.out.println("执行查询错误!");}
return rs;
}
public void close()//关闭与数据库的连接
{
try{
stmt.close();
conn.close();
}
catch(Exception e){}
}
public static void main(String[] args) {
try {
Connection conn=DataBaseConnection.getConnection();
if(conn!=null)
{
System.out.println("连接数据库正常");
}
else {
System.out.println("连接数据库异常");
}
} catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
}
}
}
上面是连接数据库的步骤
商品类
product.java
public class DataBaseConnection {
private static String driverStr="com.mysql.jdbc.Driver";//驱动列表
private static String connStr="jdbc:mysql://localhost/mySql";//mySql是我自己的数据库名
private static String dbusername="root";//数据库用户名
private static String dbpassword="12345678";//密码和数据库一致
private static Connection conn=null;//数据库的连接对象
private Statement stmt=null;//创建Statement对象
public DataBaseConnection() { }
//一个静态方法,返回一个数据库的连接,这样达到了对数据库连接统一控制的目的
public static Connection getConnection() throws SQLException {
try{
Class.forName(driverStr);//加载驱动程序
conn = DriverManager.getConnection(connStr,dbusername, dbpassword);//连接数据库
}
catch(Exception ex){System.out.println("无法同数据库建立连接!");}
return conn;
}
public int executeUpdate(String s)
{
int result=0;
try{
stmt = conn.createStatement();//创建Statement语句
result=stmt.executeUpdate(s);//执行更新语句
}
catch(Exception ex){System.out.println("执行更新错误!");}
return result;
}
public ResultSet executeQuery(String s)
{
ResultSet rs=null;
try{rs=stmt.executeQuery(s);}//执行查询语句
catch(Exception ex){System.out.println("执行查询错误!");}
return rs;
}
public void close()//关闭与数据库的连接
{
try{
stmt.close();
conn.close();
}
catch(Exception e){}
}
public static void main(String[] args) {
try {
Connection conn=DataBaseConnection.getConnection();
if(conn!=null)
{
System.out.println("连接数据库正常");
}
else {
System.out.println("连接数据库异常");
}
} catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
}
}
}
获取商品表中的全部信息
package test5;
import java.sql.*;
public class DataBaseConnection {
private static String driverStr="com.mysql.jdbc.Driver";//驱动列表
private static String connStr="jdbc:mysql://localhost/mySql";//mySql是我自己的数据库名
private static String dbusername="root";//数据库用户名
private static String dbpassword="12345678";//密码和数据库一致
private static Connection conn=null;//数据库的连接对象
private Statement stmt=null;//创建Statement对象
public DataBaseConnection() { }
//一个静态方法,返回一个数据库的连接,这样达到了对数据库连接统一控制的目的
public static Connection getConnection() throws SQLException {
try{
Class.forName(driverStr);//加载驱动程序
conn = DriverManager.getConnection(connStr,dbusername, dbpassword);//连接数据库
}
catch(Exception ex){System.out.println("无法同数据库建立连接!");}
return conn;
}
public int executeUpdate(String s)
{
int result=0;
try{
stmt = conn.createStatement();//创建Statement语句
result=stmt.executeUpdate(s);//执行更新语句
}
catch(Exception ex){System.out.println("执行更新错误!");}
return result;
}
public ResultSet executeQuery(String s)
{
ResultSet rs=null;
try{rs=stmt.executeQuery(s);}//执行查询语句
catch(Exception ex){System.out.println("执行查询错误!");}
return rs;
}
public void close()//关闭与数据库的连接
{
try{
stmt.close();
conn.close();
}
catch(Exception e){}
}
public static void main(String[] args) {
try {
Connection conn=DataBaseConnection.getConnection();
if(conn!=null)
{
System.out.println("连接数据库正常");
}
else {
System.out.println("连接数据库异常");
}
} catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
}
}
}
shop.jsp(商品页面表)
<%@page import="test5.product"%>
<%@page import="test5.Product_clo"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>在线购物</title>
<style type="text/css">
body {
background-color: #FFCCCC;
}
img {
width: 300px;
height: 400px;
}
</style>
</head>
<body>
<jsp:useBean id="db" scope="application"
class="test5.DataBaseConnection"></jsp:useBean>
<form action="shopcart.jsp?op=add" method="post">
<table>
<tr>
<!-- 遍历商品全部信息 -->
<%
String op, name, type, msg;
int price, quantity;
int id;
Product_clo clo = new Product_clo();
ArrayList<product> list = clo.getAllProduct();
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
product pro = list.get(i);
id = pro.getId();
name = pro.getName();
price = pro.getPrice();
type = pro.getType();
msg = pro.getMsg();
quantity = pro.getQuantity();
%><td><img alt="商品图片" src="/img/<%=pro.getPicture()%>"></td>
<td>
<dd>
商品名称:<%=name%></dd> <br>
<dd>
商品价格:?<%=price%></dd> <br>
<dd>
商品类型:<%=type%></dd> <br>
<dd>
商品介绍:<%=msg%></dd> <br>
<dd>
商品数量:<%=quantity%></dd> <br>
<dd>
<a href='shopcart.jsp?op=add&id=<%=id%>&name=<%=name%>&price=<%=price%>'>加入购物车</a>
</dd> <!-- <input type="submit" name="submit" value="加入购物车"> <br> -->
</td>
</tr>
<%
}
}
%>
</table>
<br>
</form>
</body>
</html>
商品的增删改查
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" import="java.sql.*"%>
<%@page import="test5.product"%>
<%@page import="test5.Product_clo"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我的购物车</title>
</head>
<body>
<jsp:useBean id="db" scope="application"
class="test5.DataBaseConnection"></jsp:useBean>
<%
String proid = request.getParameter("id");//从购物页面获取的商品id
String proname = request.getParameter("name");
String proprice = request.getParameter("price");
String op = request.getParameter("op");
ResultSet rs = null;
Connection conn = null;
PreparedStatement stmt = null;
conn = db.getConnection();
Product_clo clo = new Product_clo();
String sql = null;
ArrayList<Integer> list = new ArrayList();
try {
//将所选商品加入购物车表中
if (op.equals("add")) {
list = clo.getCartId();//链表存的是购物车商品的id
int pid = 0;
int num = 0;
int totalprice = 0;
pid = Integer.parseInt(proid);//从购物页面传过来的id,强转int后面好比较
int cartid = 0;
int price = 0;
if (list.contains(pid)) {//如果链表里有,那说明该商品已经存在于购物车,在数量上加1即可
//得先从购物车把该商品id的相关的数量和价格查询出来
sql = "select product_price,cart_product_quantity from shop.shopcart where product_id="+pid;
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery(sql);
while(rs.next()){
price = rs.getInt(1);
num = rs.getInt(2);
}
num = num + 1;//再此基础上加1
totalprice = price * num;//更新该商品的总价
sql = "update shop.shopcart set cart_product_quantity = ?, totalprice = ? where product_id=?;";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, num);
stmt.setInt(2, totalprice);
stmt.setInt(3, pid);
stmt.executeUpdate();
out.print("pid = cartid");
response.sendRedirect("buy.jsp");//重定向到购物车
stmt.close();
conn.close();
} else {//没有购物车匹配不到该商品则直接插入
sql = "insert into shop.shopcart(product_id,product_name,product_price,cart_product_quantity,totalprice) values(?,?,?,?,?);";
stmt = conn.prepareStatement(sql);
stmt.setString(1, proid);
stmt.setString(2, proname);
stmt.setString(3, proprice);
stmt.setInt(4, 1);
stmt.setString(5, proprice);
stmt.executeUpdate();
stmt.close();
conn.close();
response.sendRedirect("buy.jsp");
}
}
//在购物车中删除商品
if (op.equals("del")) {
int id = Integer.parseInt(request.getParameter("id"));
sql = "delete from shop.shopcart where product_id=?;";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
stmt.executeUpdate();
stmt.close();
conn.close();
response.sendRedirect("buy.jsp");
}
//更改商品的数量
if (op.equals("update")) {
int totalprice = 0;
int total = 0;
int id = Integer.parseInt(request.getParameter("id"));
int num = Integer.parseInt(request.getParameter("num"));
int price = Integer.parseInt(request.getParameter("price"));
totalprice = price * num;
sql = "update shop.shopcart set cart_product_quantity = ?, totalprice = ? where product_id=?;";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, num);
stmt.setInt(2, totalprice);
stmt.setInt(3, id);
stmt.executeUpdate();
stmt.close();
conn.close();
response.sendRedirect("buy.jsp");
}
//清空购物车
if (op.equals("clear")) {
sql = "delete from shop.shopcart;";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate();
stmt.close();
//关闭数据库连接
conn.close();
//重定向到购物车页面
response.sendRedirect("buy.jsp");
}
} catch (
Exception ex) {
ex.printStackTrace();
}
%>
</body>
</html>
BUY.jsp(购物车页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" import="java.sql.*"%>
<%@page import="test5.product"%>
<%@page import="test5.Product_clo"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我的购物车</title>
<style type="text/css">
body {
background-color: #FFCCCC;
}
th, td {
text-align: center;
}
</style>
<script type="text/javascript">
function updateNum(id, num, price) {
var quantity=document.getElementById("quantity").value;
var qua = parseInt(quantity);
var n = parseInt(num);
var reg=/^[0-9]*[1-9][0-9]*$/;//只能输入正整数的正则表达式
if(!reg.test(num)){
alert("只能输入正整数!");
num=1;
}
if(n>qua){
alert("库存不足!");
num=1;
}
var url = "shopcart.jsp?op=update&id=" + id + "&num=" + num + "&price="
+ price;
window.location = url;
}
//其实这复选框功能在这个实验并卵用,我没有太多的精力去实验了。这个复选框可以不要的
//按全选框则选择所有复选框
function selectAll() {
var oInput = document.getElementsByName("cartCheckBox");
for (var i = 0; i < oInput.length; i++) {
oInput[i].checked = document.getElementById("allCheckBox").checked;
}
}
//如果有其中一个没有被选中,则取消全选框,或全部复选框选中,则全选框也选中
function selectSingle() {
var k = 0;
var oInput = document.getElementsByName("cartCheckBox");
for (var i = 0; i < oInput.length; i++) {
if (oInput[i].checked == false) {
k = 1;
break;
}
}
if (k == 0) {
document.getElementById("allCheckBox").checked = true;
} else {
document.getElementById("allCheckBox").checked = false;
}
}
</script>
</head>
<body>
<h2>我的购物车</h2>
<hr>
<jsp:useBean id="db" scope="application"
class="test5.DataBaseConnection"></jsp:useBean>
<form method="post" action="pay.jsp">
<table style="width:600px; background-color:#FFCCCC">
<%!int total=0;int s; %>
<tr>
<td class="title_1"><input id="allCheckBox" type="checkbox"
value="" οnclick="selectAll()" />全选</td>
<td>商品名称</td>
<td>商品单价</td>
<td>购买数量</td>
<td>购买金额</td>
<td>编辑</td>
<td></td>
</tr>
<%
try {
int quantity = 0;
ResultSet rs = null;
Connection conn = null;
PreparedStatement stmt = null;
Statement stmts = null;
String id = null;String sql=null;
String inputid = null;
conn = db.getConnection();
Product_clo clo = new Product_clo();
ArrayList<product> list = clo.getAllProduct();
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
product pro = list.get(i);
quantity = pro.getQuantity();
}
}
sql = "select * from shop.shopcart;";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
int t = 0;
String name = null;
String price = null;
int num = 0;
String totalprice = null;
int to;
while (rs.next()) {
//显示在购物车里到商品信息
id = rs.getString("product_id");
name = rs.getString("product_name");
price = rs.getString("product_price");
num = rs.getInt("cart_product_quantity");
totalprice = rs.getString("totalprice");
%>
<tr>
<td class="cart_td_1"><input name="cartCheckBox"
type="checkbox" value="product1" οnclick="selectSingle()" /></td>
<td><%=name%></td>
<td align="center"><%=price%></td>
<%
out.println("<td><input type=text size=8 name=num id=num value=" + num + " onChange=\"updateNum('" + id + "',this.value,'"
+ price + "')\" ></td>");
%>
<td><%=totalprice%></td>
<td><a href='shopcart.jsp?op=del&id=<%=id%>'>删除</a></td>
<td><input type="hidden" name="quantity" id="quantity"
value="<%=quantity%>" /></td>
</tr>
<%
}
sql = "select sum(totalprice) from shop.shopcart;";//算全部商品总价
stmts = conn.createStatement();
rs = stmts.executeQuery(sql);
while (rs.next()) {
total=rs.getInt(1);
}
session.setAttribute("total",total);
s=(Integer)session.getAttribute("total");
%>
</tr>
<%
stmt.close();
//关闭数据库连接
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
%>
<% %>
</table>
<img alt="购买" src="/img/buy.jpg" width="50" hight="50">
商品总价:<%=s%> 元
<input type="submit" value="立即购买" />
</form>
<br>
<a href="shop.jsp">继续购物</a>
<a href="shopcart.jsp?op=clear">清空购物车</a>
</body>
支付页面
pay.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>支付界面</title>
<style>
body {
background-color: #FFCCCC;
width: 400px;
padding: 250px;
text-align: center;
margin: auto;
}
div {
font-size: 20px;
}
</style>
</head>
<body>
<%
Integer a = (Integer) session.getAttribute("a");//账户余额
Integer total = (Integer) session.getAttribute("total");//支付金额
if (session.getAttribute("a") == null) {
a = 0;
}
if (a >= total) {
a = a - total;
session.setAttribute("a", a);
%>
<div>支付成功!正在生成订单...</div>
<%
response.setHeader("Refresh", "3;url=order.jsp"); //3秒跳转到支付订单
} else {
%>
<div>
余额不足!请充值或者返回购物车<br>
<br> <a href="money.jsp" target="_parent">账户充值</a> <br> <br>
<a href="buy.jsp">返回购物车</a> <br> <br>
</div>
<%
}
%>
</body>
查看订单页面
order.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="test5.product" import="java.util.*" import="java.sql.*"%>
<%@page import="test5.Product_clo" import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我的订单</title>
<style>
table {
margin: 0 auto;
width: 300px;
border: 1px solid red;
border-collapse: collapse;
}
th, td {
text-align: center;
border: 1px solid green;
}
</style>
</head>
<body>
<jsp:useBean id="db" scope="application"
class="test5.DataBaseConnection"></jsp:useBean>
<%!int total;%>
<%
//获取订单生成的时间
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dd = format.format(date);
session.setAttribute("payDate", dd);
String d = (String) session.getAttribute("payDate");
%>
<table style="width: 600px; background-color: #FFCCCC">
<tr>
<td colspan="4"><%=d%>您的订单如下:</td>
</tr>
<tr>
<td>商品名称</td>
<td>商品单价</td>
<td>购买数量</td>
<td>商品价格</td>
</tr>
<%
//取商品信息值
String name = null;
ResultSet rs = null;
Connection conn = null;
PreparedStatement stmt = null;
conn = db.getConnection();
//String sql="insert into shop.order select * from shop.shopcart;";
String sql = "insert into shop.order(product_id,product_name,product_price,product_num,product_total) select product_id,product_name,product_price,cart_product_quantity,totalprice from shop.shopcart;";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate();
//String name = null;
sql = "select * from shop.order;";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
int price = 0;
int num = 0;
int totalprice = 0;
int id = 0;int pronum=0;
%>
<%
while (rs.next()) {
//显示在购物车里到商品信息
id=rs.getInt("product_id");
name = rs.getString("product_name");
price = rs.getInt("product_price");
num = rs.getInt("product_num");
totalprice = rs.getInt("product_total");
//商品表的库存也要更新
sql = "select product_quantity from shop.product where product_id="+id;
stmt = conn.prepareStatement(sql);
rs=stmt.executeQuery(sql);
while(rs.next()){
pronum=rs.getInt(1);
}
sql = "update shop.product set product_quantity = ? where product_id=?;";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, pronum-num);
stmt.setInt(2, id);
stmt.executeUpdate();
%>
<tr>
<td style="width: 200px;"><%=name%></td>
<td style="width: 200px;"><%=price%></td>
<td style="width: 200px;"><%=num%></td>
<td style="width: 200px;"><%=totalprice%></td>
</tr>
<%
}
%>
<tr>
<td colspan="4">总价?:<%=session.getAttribute("total")%>元
</td>
</tr>
</table>
<%
//加入订单表我的购物车表自然要清空了
sql = "delete from shop.shopcart";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate();
stmt.close();
//关闭数据库连接
conn.close();
%>
<div align="center">
<a href="shop.jsp">继续购物</a>
</div>
</body>
</html>
欢迎页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
body {
background-color: #FFCCCC;
}
</style>
</head>
<body>
尊敬的用户 <%-- <%= session.getAttribute("username")%> --%>欢迎您!
<h1 align="center">在线购物</h1>
<form action="Search.jsp">
<div align="center">
<input type="text" style="width: 500px; height: 25px" /> <input
type="submit" οnclick="Search.jsp" value="搜索" />
</div>
</form>
</body>
</html>
***1、打开数据库文件夹,在mysql中创建一个名为shoppingjsp.sql文件名的数据库shoppingjsp 编码为utf-8 防止数据插入乱码
,使用工具导入数据库文件。(不明白,我可以帮助导入)
2、修改数据库连接信息:
String DBDRIVER = “com.mysql.jdbc.Driver”; //加载数据库驱动
String DBURL = “jdbc:mysql://localhost:3306/shoppingjsp?characterEncoding=utf-8”; //db_jsp数据库名 数据库编码 防止乱码
String DBUSER = “root”; //mysql登陆用户名
String DBPASSWORD = “root”; //mysql登陆密码