实验电子商城 mvc设计思想简介
这次实验的要求是使用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 exceptionex.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 exceptionex.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 exceptionex.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");//从购物页面获取的商品idString 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();//链表存的是购物车商品的idint 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;//再此基础上加1totalprice = 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" /> <inputtype="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登陆密码
此次的购物车实验是符合三层架构思想:web与用户交互,业务层和数据层,之前也有讲过设计的思想在这就不多做赘述.此次实验的代码并没有完整的上传,如果有需要请留言看见我会及时回复,此次实验是从最初的的只有servlet的版本一直一直升级,每次都加入了不同的更新,建议可以先从简单的入手,servlet–>jsp–>JavaBean–>jdbc 不过数据库的学习可能大家的进度不一样,有什么问题可以在下留言,登录数据库时注意用户名和密码和我的不一样.
实验电子商城 mvc设计思想简介相关推荐
- 简单网页版的注册登录案例(JSP+CSS+MySQL+Servlet+MVC设计思想,含源码!)
文章目录 一.登陆注册小案例 1.数据库创建与连接测试 2.用户登录注册逻辑实现及测试 3.界面实现 4.程序MVC设计思想 一.登陆注册小案例 1.数据库创建与连接测试 创建数据库weblogin, ...
- 基于JSP(java)电子商城的设计和实现 (含源文件)
摘 要 Internet以其标准化.全球化.全民化.迅猛发展等特点成为了电子商务的基础,电子商务活动己经演变成了利用Internet进行经济活动的网络经济.电子商务网站如雨后春笋般地发展壮大起来,各式 ...
- 基于JSP(java)电子商城的设计和实现
摘 要 Internet以其标准化.全球化.全民化.迅猛发展等特点成为了电子商务的基础,电子商务活动己经演变成了利用Internet进行经济活动的网络经济.电子商务网站如雨后春笋般地发展壮大起来,各式 ...
- PHP电子商城需求分析,网站(电子商城)设计与实现[原创]
内容介绍 原文档由会员 小丑88 发布 网站(电子商城)设计与实现 1.44字 自己原创的毕业论文,已经通过校内系统检测,重复率低,仅在本站独家出售,大家放心下载使用 摘要 随着Internet技术的 ...
- 网上电子商城的设计与实现
技术:Java.JSP等 摘要: 21 世纪以来,人类经济高速发展,人们的生活发生了日新月异的变化,特别是计算机的应用及普及到经济和社会生活的各个领域.在消费领域,网上购物已经成为大众所接受的一种新型 ...
- Java、JSP网上电子商城的设计
技术:Java.JSP等 摘要: 21 世纪以来,人类经济高速发展,人们的生活发生了日新月异的变化,特别是计算机的应用及普及到经济和社会生活的各个领域.在消费领域,网上购物已经成为大众所接受的一种新型 ...
- 电子商城数据库设计思路
一.设计目标 本次设计为设计一个电子商城,即我们经常在淘宝,京东等网站看到的网店.这只是一个初步的设计,跟实际上的网店还有很多的差距.主要的差距在于数据的并发处理,图片服务器,视频服务器,以及用户访问 ...
- java B2B2C Springcloud多租户电子商城系统-集成项目简介
Spring Cloud集成项目有很多,下面我们列举一下和Spring Cloud相关的优秀项目,希望可以帮助到大家. Spring Cloud Config 配置管理工具包,让你可以把配置放到远程服 ...
- 谷粒商城RabbitMQ设计思想详解:消息队列双重保险设计
前言 上来先放一张设计图,看这篇文章的前提是一定得写过或者了解这段业务,不然会看不懂,我下面将会给出我的理解,尽量让大家明白 设计思想 @Transactional@Overridepublic Su ...
最新文章
- windows nodejs mysql_windows server 安装 mysql + nondejs连接mysql
- 将Java程序打jar包并运行
- Go的runtime.GOMAXPROCS
- window下eclipse搭建C/C++开发环境(超简单无需插件版) .
- mysql和sqlserver读写分离_C#简单构架之EF进行读写分离+多数据库Mysql/SqlServer
- Selenium3笔记-WebDriver源码初探
- 为什么做AI的都选Python?
- tm4c123g c语言,Tm4c123GX(tiva)入门详细教程
- Nacos集群环境搭建
- CTCconnectionist temporal classfication: labelling unsegmented sequence data with recurrent(一)
- 学会对VUE的SEO优化,你的网站总是排在前面
- 关于 IOS 的299$ 美元企业模式(In House)及Installing Apps Wirelessly 详解
- 【社区团购平台排名】社区团购平台有哪些?
- Java工程师通宵都要看完这几本阿里P8都强烈推荐的Java电子书
- 人脸识别,验证,登录开发 (三)
- AccountManager使用教程
- 河南朱砂服务器位置,探访河南境内规模最大的龙山遗址 龙山大墓主人头部疑似涂有朱砂...
- 理性行为理论和计划行为理论
- 借条上的字迹消失了,怎么办?
- VC2008 Redist依赖安装 win10下报1935失败解决