Java基础14

Java基础14

Java基础14    1

文件结构    1

购物网开发过程    2

此购物网数据库设计    4

此购物网MVC模型图    8

view_WebRoot/index.jsp    8

view_WebRoot/head.jsp    10

view_WebRoot/tail.jsp    11

view_WebRoot/left.jsp    12

view_WebRoot/right.jsp    14

view_WebRoot/showDetail.jsp    17

view_WebRoot/showMycart.jsp    19

view_WebRoot/shopping2.jsp    23

view_WebRoot/shopping3.jsp    24

view_WebRoot/shopping4.jsp    28

Controller_src/Shop.servlet/ShowGoodsClServlet.java    30

Controller_src/Shop.servlet/ShoppingClServlet.java    32

Controller_src/Shop.servlet/LoginCl.java    35

Controller_src/Shop.servlet/ShoppingCl2.java    37

Controller_src/Shop.servlet/OrderClServlet.java    39

model_src/Shop.model/ConnDB.java    41

model_src/Shop.model/ GoodsBean.java    42

model_src/Shop.model/ GoodsBeanBO.java    43

model_src/Shop.model/Test.java    47

model_src/Shop.model/MyCartBO.java    48

model_src/Shop.model/UserBean.java    52

model_src/Shop.model/Test.java    54

model_src/Shop.model/OrderBean.java    57

model_src/Shop.model/OrderBeanBO.java    58

model_src/Shop.model/ OrderDetailBean.java    62

model_src/Shop.model/ OrderInfoBean.java    63

 

文件结构

购物网开发过程

开发步骤:

    1.界面(模仿)

    2.数据库(表的设计)[界面(功能)-->猜出表???]

    3.建立web工程,ShoppingSite

    4.写主页面(index.jsp),死去活来法,先死后活。

        在dw中,建立html --> 在myeclipse中建立 jsp

        

        开发的界面,这里使用table+css方式布局。

        在table+css布局中,常用的一个技巧是在行的某列中嵌入一个表格,做精确的布局。

        初步介绍css:css是层又叠样式表,控制网页的字体,颜色,大小,背景,边框...

 

    5.把静态的页面向动态的页面修改。

        在主页面,用户点击了书名的超链接就显示该商品信息页面(showDetail.jsp)——死去活来法

        完成返回购物大厅[js]

        开发model和servlet,把静态界面做活

        

    6.在index.jsp页面加入分页显示货物的功能

        把显示货物的信息的table循环显示(在jsp页面中 java片段和html标签混用)

        haspmap:

            特点:

                1.hashmap就像一张表

                2.key值是不能重复

                3.key值和value值,可以是java的Object类型

                

            key值--->书的 id

            values值 ---> 书的数量

    7.对购物车可以增加,删除,清空,修改数量,计算总价

        为了让servlet得到货物的id和数量,这里使用隐藏表单完成

    8.完成以下几项功能:

        1.用户登录

        2.显示用户联系情况用订单情况

        3.订单表的设计及订单的生成

        4.发送电子邮件(javamail)到用记信箱

        5.购物流程设计(MVC(模型,界面,控制器))

        

        如果一种处理器(控制器)只处理一种业务逻辑,就没有必要给它加标志以示区别不同的业务逻辑

        

        完成生成订单的功能:

            1.设计订单表

                当表和表之间有多对多的关系时,就应该使用中间表来解决数据冗余问题

                对订单表的分解处理:

                初始表:

                    order(orderId bigint primary key auto_increment, #订单号

                        userId bigint references users(userId), #用户id

                        goodsId bigint references goods(goodsId), #商品id

                        nums int not null,    #数量

                        orderDate datetime not null,    #时间

                        payMode String not null,    #付款方式

                        isPayed boolean,    #付款否

                        totalPrice float not null)    #总价

                

                分解优化后的订单表:

                    order1(orderId bigint primary key auto_increment, #订单号

                        userId bigint constraint fk_userId references users(userId), #用户id

                        orderDate datetime ,#default curdate(),    #时间

                        payMode varchar(20) ,#check(payMode in('货到付款','支付宝付款')),    #付款方式

                        isPayed bit ,#check(isPayed in(0,1)),    #付款否

                        totalPrice float not null)    #总价

                            

                    order2(orderId bigint references order1(orderId), #订单号

                        goodsId bigint not null references goods(goodsId), #商品id

                        nums int not null,    #数量)

                通过将订单表分解,这样就把订单表和货物表的多对多的关系,简化成一对多的关系:从而

                达到解决数据冗余的问题。

            

                mysql中对键的约束问题,有待解决。。。。。。                

                

    9.javamail技术,主要用户发送电子邮件给某个信箱。

        (自己想办法独立完成)

                

    10.还有待实现的功能:

        1.后台商品的管理

        2.后台用户的管理

        3.用户注册的功能

        4.网站公告的管理

        5.网站最受用户欢迎的书籍(动态)

        

此购物网数据库设计

 

--=============================================

-----------------sql server--------------------

--run:

--sqlcmd -U sa -P luowei -d master

 

drop database shoppingdb;

go

create database shoppingdb;

go

use shoppingdb;

go

 

--普通用户表

create table users(

userId bigint primary key identity, --用户id

userName varchar(30) not null unique, --用户名

trueName varchar(30) not null, --真实名字

passWd varchar(30) not null, --密码

email varchar(40) not null, --电子邮件

phone varchar(20) not null, --电话号码

address varchar(30) not null, --用户地址

postcode char(6) not null, --邮编

grade int default 1 --用户级别

)

 

--管理员表admin

--暂时留着

 

--货物表

create table goods(

goodsId bigint primary key identity, --货物id

goodsName varchar(40), --名称

goodsIntro varchar(500), --介绍

goodsPrice float , --价格

goodsNum int, --数量

publisher varchar(40), --发行商

photo varchar(40), --照片

goodsType varchar(10) --类型

)

--向用户表添加数据

insert into users values('luowei','维唯为为','luowei','luowei010101@sina.com','010-88888888','湖南省娄星区','417000',1);

 

select * from users;

 

--向货物添加数据

insert into goods values('黑白森林','这是一部好片',59,1,'香港嘉禾出品','1.jpg','香港电影');

insert into goods values('金鸡IT','这是一部好片',49,1,'香港嘉禾出品','2.jpg','香港电影');

insert into goods values('靓女菜馆','这是一部好片',99,1,'香港嘉禾出品','3.jpg','香港电影');

insert into goods values('布衣神相','这是一部好片',19,1,'香港嘉禾出品','4.jpg','香港电影');

insert into goods values('洛神','这是一部好片',56,1,'香港嘉禾出品','5.jpg','香港电影');

 

--订单表

create table orders(

ordersId bigint primary key identity(1,1),

userId bigint references users(userId),

orderDate datetime default getDate(),

payMode varchar(20) check(payMode in('货到付款','支付宝付款')),

isPayed bit check(isPayed in(0,1)),

totalPrice float not null

)

go

create table orderDetail(

ordersId bigint references orders(ordersId),

goodsId bigint references goods(goodsId),

nums int not null

)

go

--=============================================

--------------------mysql----------------------

run: mysql -u root -p

Enter password:root

create database shoppingdb;

use shoppingdb;

 

#普通用户表

create table users(

userId bigint primary key auto_increment, #用户id

userName varchar(30) not null unique, #用户名

trueName varchar(30) not null, #真实名字

passWd varchar(30) not null, #密码

email varchar(40) not null, #电子邮件

phone varchar(20) not null, #电话号码

address varchar(30) not null, #用户地址

postcode char(6) not null, #邮编

grade int default 1 #用户级别

);

 

 

#货物表

create table goods(

goodsId bigint primary key auto_increment, #货物id

goodsName varchar(40), #名称

goodsIntro varchar(500), #介绍

goodsPrice float , #价格

goodsNum int, #数量

publisher varchar(40), #发行商

photo varchar(40), #照片

goodsType varchar(10) #类型

);

ALTER TABLE users CONVERT TO CHARACTER SET utf8;

--ALTER TABLE users DEFAULT CHARACTER SET utf8;

 

#向用户表添加数据

insert into users values(null,'luowei','维唯为为','luowei','luowei@sina.com','010-88888888','湖南省娄星区','417000',1);

 

select * from users;

 

#向货物添加数据

insert into goods values(null,'黑白森林','这是一部好片',59,1,'香港嘉禾出品','1.jpg','香港电影');

insert into goods values(null,'金鸡IT','这是一部好片',49,1,'香港嘉禾出品','2.jpg','香港电影');

insert into goods values(null,'靓女菜馆','这是一部好片',99,1,'香港嘉禾出品','3.jpg','香港电影');

insert into goods values(null,'布衣神相','这是一部好片',19,1,'香港嘉禾出品','4.jpg','香港电影');

insert into goods values(null,'洛神','这是一部好片',56,1,'香港嘉禾出品','5.jpg','香港电影');

 

select * from goods;

 

#订单表

create table orders(

ordersId bigint primary key auto_increment,

userId bigint references users(userId),

orderDate datetime ,#default curdate(),

payMode varchar(20) , #mysql中约束问题有待解决

isPayed bit ,#check(isPayed in(0,1)),

totalPrice float not null

);

 

create table orderDetail(

ordersId bigint references orders(ordersId),

goodsId bigint references goods(goodsId),

nums int not null

);

 

insert into orders(userId,orderDate,payMode,isPayed,totalPrice) values(1,(select curdate()),'货到付款',0,120.0);

 

select * from orders;

 

 

此购物网MVC模型图

 

view_WebRoot/index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

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">

    

    <!-- 要引用css,之前这里的注释符号要去掉 -->

    <link rel="stylesheet" type="text/css" href="css/my.css">

      

</head>

 

<body topmargin="0" background="img/bg.jpg">

    <table width="80%" border="1" align="center" cellpadding="1" cellspacing="1">

     <tr>

     <td height="120" colspan="2" align="center">

        <jsp:include page="head.jsp" flush="true"></jsp:include>

        </td>

     </tr>

     <tr>

     <td width="25%" height="400" align="center" valign="top">

        <jsp:include page="left.jsp" flush="true"></jsp:include>

        </td>

     <td align="center" valign="top">

        <jsp:include page="right.jsp" flush="true"></jsp:include>

        </td>

     </tr>

     <tr>

     <td height="86" colspan="2" align="center">

        <jsp:include page="tail.jsp" flush="true"></jsp:include>

        </td>

     </tr>

    </table>

</body>

</html>

 

 

view_WebRoot/head.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!-- 只把table引入即可 -->

<table width="100%" border="0" cellpadding="1" cellspacing="1" class="abc">

<tr>

<td height="10" colspan="3" bgcolor="#FF9999"></td>

</tr>

<tr>

<td width="24%" align="center"><img src="img/head/logo.jpg" width="213" height="76"></td>

<td width="58%" align="center"><img src="img/head/center.jpg" width="399" height="78"></td>

<td width="18%"><p><img src="img/head/right1.jpg" width="26" height="22">【我的账号】</p>

<p><img src="img/head/right2.jpg" width="23" height="22"/><a href=ShoppingClServlet?type=show>【我的购物车】</a></p></td>

</tr>

<tr>

<td height="10" colspan="3" bgcolor="#FF9999"></td>

</tr>

<tr>

<td colspan="3"><table width="100%" border="0" cellpadding="1" cellspacing="1">

<tr align="center">

<td width="11%">&nbsp;</td>

<td width="11%" class="navi">首页</td>

<td width="11%">&nbsp;</td>

<td width="11%" class="navi">香港电影</td>

<td width="11%">&nbsp;</td>

<td width="11%" class="navi">大陆电影</td>

<td width="11%">&nbsp;</td>

<td width="11%" class="navi">关于我们</td>

<td width="11%">&nbsp;</td>

</tr>

</table></td>

</tr>

</table>

 

view_WebRoot/tail.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

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 'tail.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">

    -->

 

</head>

 

<body>

<table width="100%" border="0" align="center" cellpadding="1" cellspacing="1" class="abc">

<tr>

<td align="center" bgcolor="#FF9999">合作伙伴:<a href="http:www.sohu.com">搜狐</a> <a href="http:www.163.com">网易</a> <a href="http:www.baidu.com">百度</a> <a href="http:www.sina.com">新浪</a> </td>

</tr>

<tr>

<td align="center">地址:湖南省娄星区 客服热线:0738-8888888</td>

</tr>

<tr>

<td align="center">邮编:417000 客服信箱:luowei505050@126.com</td>

</tr>

<tr>

<td align="center">Copyright 为为购物网 </td>

</tr>

</table>

</body>

</html>

 

view_WebRoot/left.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<table width="100%" border="0" cellpadding="1" cellspacing="1" class="abc">

<tr>

<td height="60" align="center" valign="top"><img src="img/left/top.jpg" width="160" height="60"></td>

</tr>

<tr>

<td height="170" align="center" valign="top">&nbsp;<img src="img/left/flash.jpg" width="160" height="170">

    <!-- 滚动的页面

    <script language="javascript" src="banner.js"></script>

    -->

    

    </td>

</tr>

<tr>

<td height="10" align="center" bgcolor="#FF9999"></td>

</tr>

<tr>

<td align="center"><table width="100%" border="0" cellpadding="1" cellspacing="1" class="abc">

<tr align="center" valign="middle">

<td height="60" colspan="3"><img src="img/left/botton.jpg" width="160" height="60"></td>

</tr>

<tr align="center" valign="middle">

<td width="33%">排行</td>

<td width="33%" nowrap>商品名称 </td>

<td width="33%">点击次数</td>

</tr>

<tr align="center" valign="middle">

<td width="33%">1</td>

<td width="33%" nowrap><a href="#">笑傲江湖</a></td>

<td width="33%">10</td>

</tr>

<tr align="center" valign="middle">

<td width="33%">2</td>

<td width="33%" nowrap><a href="#">天龙八部</a></td>

<td width="33%">9</td>

</tr>

<tr align="center" valign="middle">

<td width="33%">3</td>

<td width="33%" nowrap><a href="#">天龙八部</a></td>

<td width="33%">8</td>

</tr>

<tr align="center" valign="middle">

<td width="33%">4</td>

<td width="33%" nowrap><a href="#">笑傲江湖</a></td>

<td width="33%">7</td>

</tr>

<tr align="center" valign="middle">

<td width="33%">5</td>

<td width="33%" nowrap><a href="#">笑傲江湖</a></td>

<td width="33%">5</td>

</tr>

<tr align="center" valign="middle">

<td width="33%">6</td>

<td width="33%" nowrap><a href="#">笑傲江湖</a></td>

<td width="33%">4</td>

</tr>

<tr align="center" valign="middle">

<td width="33%">7</td>

<td width="33%" nowrap><a href="#">天龙八部</a></td>

<td width="33%">2</td>

</tr>

</table></td>

</tr>

</table>

view_WebRoot/right.jsp

 

<%@ page language="java" import="java.util.*,Shop.model.*" pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

 

//接收pageNow

String s_pageNow=(String)request.getAttribute("pagenow");

int pageNow=1;

if(s_pageNow!=null)

{

    //String-->int

    pageNow=Integer.parseInt(s_pageNow);

}

//使用GoodsBeanBO,完成分页(:正规的流程应该要经过servlet调用Bo)

GoodsBeanBO gbb=new GoodsBeanBO();

//默认显示第一页

ArrayList al=gbb.getGoodByPage(6,pageNow);

 

//得到共有多少页

int pageCount=gbb.getPageCount(6);

 

 

 

%>

 

<table width="100%" height="445" border="0" cellpadding="1" cellspacing="1" class="abc">

<tr>

<td height="30" colspan="3"><img src="img/right/top.jpg" width="419" height="64"></td>

</tr>

 

<%

        int time=0;

        for(int i=0;i<2;i++)

        {

            //打印两大行(每行有三个【有可能不够显示】)

    %>

    <tr>

    <%

            //取出三个

            for(int j=0;j<3;j++)

            {

                if(time<al.size())

                {

                //取出货物bean

                GoodsBean gb=(GoodsBean)al.get(time);

                time++;

                

    %>

    <td width="33%" height="160">

<table width="100%" height="100%" border="0" cellpadding="1" cellspacing="1" class="abc">

<tr align="left" valign="top">

<td width="40%" height="60%" rowspan="3"><img src="img/right/<%=gb.getPhoto() %>" width="112" height="112"></td>

<td width="60%" height="35" align="left" valign="top"><div align="left"></div> <div align="left"></div> <div align="left"></div></td>

</tr>

<tr>

<td width="60%" height="31" align="left" valign="top"><a href="ShowGoodsClServlet?type=showDetail&id=<%=gb.getGoodsId() %>"><%=gb.getGoodsName() %></a></td>

</tr>

<tr>

<td width="60%" height="12%" align="left" valign="top">价格:$<%=gb.getGoodsPrice() %></td>

</tr>

<tr align="left" valign="top">

<td height="50" colspan="2"><p>简单介绍:<%=gb.getGoodsIntro() %></p>

<p>&nbsp;</p></td>

</tr>

</table></td>

    <%

                }else break;

            }

    %>

    </tr>

    <%

             //判断第一大行是否结束

             if(i==0)

             {

     %>

    <tr bgcolor="#FF9999">

<td height="10" colspan="3" align="center"></td>

    </tr>

     <%             

             }

        }

     %>

 

<tr>

<td height="25" colspan="3" align="center">

    <%

        for(int i=1;i<=pageCount;i++)

        {

    %>

    <a href="ShowGoodsClServlet?type=fenye&pageNow=<%=i %>"><%=i %></a>

    <%

        }

     %>

     </td>

</tr>

</table>

view_WebRoot/showDetail.jsp

 

<%@ page language="java" import="java.util.*,Shop.model.*" pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

 

//初始数据一般写在这里

//取出要显示的信息(goodsBean)

GoodsBean gb=(GoodsBean)request.getAttribute("goodsInfo");

 

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'showDetail.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="css/my.css">

    <script type="text/javascript">

    <!--

        //响应点击返回购物大厅的事件

        function returnHall()

        {

            //默认open函数是打开一个新页面

            //如果在后面加入一个_self

            window.open("index.jsp","_self");

        }

        

        //响应点击购买货物的事件

        function addGoods(goodsId)

        {

            //判断是否得到货物id

            //window.alert(goodsId);

            //向ShoppingClServlet请求添加货物

            window.open("ShoppingClServlet?type=addGoods&goodsId="+goodsId,"_self");

        }

        

     -->

    </script>

      

</head>

 

<body background="img/bg.jpg" topmargin="0">

<table width="100%" border="1" cellspacing="1" cellpadding="1">

<tr>

<td align="center" valign="middle">

        <table width="100%" border="0" cellpadding="1" cellspacing="1" class="abc">

         <tr align="center">

            <td height="25" colspan="2">

            <jsp:include page="head.jsp" flush="true"></jsp:include>

            </td>

         </tr>

         <tr>

            <td width="22%" rowspan="7"><img src="img/right/<%=gb.getPhoto() %>" width="136" height="169"></td>

            <td width="78%" height="25" align="center"><strong><%=gb.getGoodsName() %></strong></td>

         </tr>

         <tr>

            <td height="24">价格:¥<%=gb.getGoodsPrice() %></td>

         </tr>

         <tr>

            <td height="27">&nbsp;</td>

         </tr>

         <tr>

            <td height="27">ISBN:<%=gb.getGoodsId() %></td>

         </tr>

         <tr>

            <td height="25">类型:<%=gb.getGoodsType() %></td>

         </tr>

         <tr>

            <td height="26">出版商:<%=gb.getPublisher() %></td>

         </tr>

         <tr>

            <td height="72" align="left" valign="top">简介:<%=gb.getGoodsIntro() %></td>

         </tr>

         <tr>

            <td height="33" colspan="2"><input type="submit" name="Submit" onclick="addGoods(<%=gb.getGoodsId() %>)" value=" 购买 ">

            <input type="submit" name="Submit2" onclick="returnHall()" value="返回购物大厅"></td>

         </tr>

         <tr>

            <td height="32" colspan="2">&nbsp;</td>

         </tr>

         <tr align="center">

            <td height="20" colspan="2">

            <jsp:include page="tail.jsp" flush="true"></jsp:include>

            </td>

         </tr>

     </table>

    </td>

</tr>

</table>

</body>

</html>

 

view_WebRoot/showMycart.jsp

 

<%@ page language="java" import="java.util.*,Shop.model.*" pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

 

//取出al [购物车中的商品]

ArrayList al=(ArrayList)request.getAttribute("mycartInfo");

 

//从session中取出购物车(注意购物车是存在session中)

MyCartBO mbo=(MyCartBO)session.getAttribute("mycart");

 

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'showMycar.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="css/my.css">

    

    <script type="text/javascript">

    <!--

        //响应删除全部书籍

        function delAll()

        {

            window.open("ShoppingClServlet?type=delAll","_self");

        }

    -->

    </script>

      

</head>

 

<body topmargin="0" background="img/bg.jpg" >

<table width="80%" align="center" border="0" cellpadding="1" cellspacing="1" class="abc">

<tr>

<td align="center">

    <jsp:include page="head.jsp" flush="true"></jsp:include>

    </td>

</tr>

 

<tr>

<td align="center">

<form action="ShoppingClServlet?type=updateGoods" method="post">

<table width="100%" border="1" cellpadding="1" cellspacing="1" class="abc">

<tr align="center">

<td colspan="6"><img src="img/car/img_1.jpg" width="634" height="48"></td>

</tr>

<tr align="center">

<td width="20%">编号</td>

<td width="25%">名称</td>

<td width="25%">单价</td>

<td colspan="3">数量</td>

</tr>

 

<%

    for(int i=0;i<al.size();i++)

    {

        //从al中取出货物bean

        GoodsBean gb=(GoodsBean)al.get(i);

%>

<tr align="center">

<td width="20%"><%=gb.getGoodsId() %></td>

<td width="25%"><%=gb.getGoodsName() %></td>

<td width="25%"><%=gb.getGoodsPrice() %></td>

<td width="10%">

<input type="hidden" name="goodsId" value="<%=gb.getGoodsId() %>"/><!-- 货物id -->

<%//System.out.println("showMycart.jsp中得到goodsId="+gb.getGoodsId()); %>

<input name="newNums" type="text" size="8" value="<%=mbo.getGoodsNumById(gb.getGoodsId()+"") %>"/> <!-- 货物数量 -->

</td>

<td width="10%"><a href="ShoppingClServlet?type=delGoods&goodsId=<%=gb.getGoodsId() %>">删除</a></td>

<td width="10%"><a href="ShowGoodsClServlet?type=showDetail&id=<%=gb.getGoodsId() %>">查看</a></td>

</tr>

<%

    }

%>

 

<tr align="center">

<td width="20%">&nbsp;</td>

<td width="25%"><input type="button" name="Submit" onclick="delAll()" value="删除全部书籍"></td>

<td width="25%"><input type="submit" name="Submit2" value="修 改 数 量"></td>

<td colspan="3">&nbsp;</td>

</tr>

<tr>

<td colspan="6" bordercolor="#EFEAE6">&nbsp;</td>

</tr>

 

<tr align="center">

<td colspan="6"><table width="100%" border="0" cellpadding="1" cellspacing="1" class="abc">

<tr>

<td width="60%" align="left" nowrap>您共选择了价值¥<%=mbo.returnAllPrices() %>元的商品,点击 <a href="index.jsp">此处</a> 继续购物。</td>

<td align="right"><a href="ShoppingCl2"><img src="img/next.jpg" width="84" height="18" border="0"></a></td>

</tr>

</table></td>

</tr>

 

</table></form></td>

</tr>

 

<tr>

<td align="center">&nbsp;<jsp:include page="tail.jsp" flush="true"></jsp:include>

    </td>

</tr>

</table>

</body>

</html>

 

view_WebRoot/shopping2.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

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 'shopping2.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="css/my.css">

      

 

</head>

 

<body topmargin="0" background="img/bg.jpg">

<table width="80%" border="0" align="center" cellpadding="1" cellspacing="1">

<tr>

<td align="center">

    <jsp:include page="head.jsp" flush="true"></jsp:include>

    </td>

</tr>

<tr>

<td align="center"><table width="100%" border="1" cellspacing="1" cellpadding="1">

<tr>

<td align="center"><img src="img/shopping2/yanzhen.jpg" width="591" height="48"></td>

</tr>

<tr>

<td align="center">

<form action="LoginCl" method="post">

<table width="40%" border="2" cellpadding="1" cellspacing="1" bordercolor="#00CC00" class="abc">

<tr align="center">

<td colspan="2"><img src="img/shopping2/dl.jpg" width="149" height="55"></td>

</tr>

<tr align="center">

<td width="45%" align="right">用户名:</td>

<td align="left"><input name="username" type="text" size="12" maxlength="16"></td>

</tr>

<tr align="center">

<td width="45%" align="right">&nbsp;&nbsp;码:</td>

<td align="left"><input name="passwd" type="text" size="12" maxlength="16"></td>

</tr>

<tr align="center">

<td width="45%"><input type="submit" name="Submit" value="用户登录"></td>

<td ><input type="submit" name="Submit2" value="用户注册"></td>

</tr>

</table></form></td>

</tr>

<tr>

<td align="right"><img src="img/next.jpg" width="84" height="18"></td>

</tr>

</table> </td>

</tr>

<tr>

<td align="center">

    <jsp:include page="tail.jsp" flush="true"></jsp:include>

    </td>

</tr>

</table>

</body>

</html>

 

view_WebRoot/shopping3.jsp

 

<%@ page language="java" import="java.util.*,Shop.model.*" pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

 

//得到用户信息

UserBean ub=(UserBean)session.getAttribute("userInfo");

//得到购物车的信息

ArrayList al=(ArrayList)request.getAttribute("mycartInfo");

//GoodsBean gb=(GoodsBean)al.get(1);

//System.out.println("goodsId="+gb.getGoodsId());

//得到购物车

MyCartBO mcb=(MyCartBO)session.getAttribute("mycart");

 

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'shopping3.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="css/my.css">

      

 

</head>

 

<body topmargin="0" background="img/bg.jpg">

<table width="80%" border="0" align="center" cellpadding="1" cellspacing="1">

<tr>

<td align="center">

    <jsp:include page="head.jsp" flush="true"></jsp:include>

    </td>

</tr>

<tr>

<td align="center"><table width="100%" border="1" cellspacing="1" cellpadding="1">

<tr>

<td align="center"><img src="img/shopping3/shopping3.jpg" width="607" height="45"></td>

</tr>

<tr>

<td align="center"><table width="80%" border="1" cellpadding="1" cellspacing="1" bordercolor="#00CC00" class="abc">

<tr align="center">

<td colspan="2">购买人的信息</td>

</tr>

<tr>

<td width="50%" align="right">&nbsp;&nbsp;名:</td>

<td align="left"><input type="text" name="textfield" value="<%=ub.getUsername() %>"></td>

</tr>

<tr>

<td width="50%" align="right">*真实姓名:</td>

<td align="left"><input type="text" name="textfield2" value="<%=ub.getTruename() %>"></td>

</tr>

<tr>

<td width="50%" align="right">*家庭住址:</td>

<td align="left"><input type="text" name="textfield22" value="<%=ub.getAddress() %>"></td>

</tr>

<tr>

<td width="50%" align="right">*联系电话:</td>

<td align="left"><input type="text" name="textfield222" value="<%=ub.getPhone() %>"></td>

</tr>

<tr>

<td width="50%" align="right">*电子邮件:</td>

<td align="left"><input type="text" name="textfield2222" value="<%=ub.getEmail() %>"></td>

</tr>

<tr>

<td width="50%" align="right">*邮&nbsp;&nbsp;&nbsp;&nbsp;编:</td>

<td align="left"><input type="text" name="textfield22222" value="<%=ub.getPostcode() %>"></td>

</tr>

<tr>

<td width="50%" align="right"><input type="submit" name="Submit" value="&nbsp;&nbsp;完成订单&nbsp;&nbsp;"></td>

<td><input type="submit" name="Submit2" value="修改个人信息"></td>

</tr>

</table> </td>

</tr>

<tr>

<td align="center"><table width="80%" border="1" cellpadding="1" cellspacing="1" bordercolor="#00CC00" class="abc">

<tr>

<td colspan="4" align="center">我的购物车</td>

</tr>

<tr align="center">

<td>编号</td>

<td>商品名称</td>

<td>单价</td>

<td>数量</td>

</tr>

 

<%

 

    for(int i=0;i<al.size();i++)

    {

        GoodsBean gb=(GoodsBean)al.get(i);

%>

<tr align="center">

<td><%=gb.getGoodsId() %></td>

<td><%=gb.getGoodsName() %></td>

<td><%=gb.getGoodsPrice() %></td>

<td><%=mcb.getGoodsNumById(gb.getGoodsId()+"") %></td>

</tr>

<%

    }

%>

 

<tr align="left">

<td colspan="4">您选择了价值¥<%=mcb.returnAllPrices() %>元的商品。</td>

</tr>

<tr align="center">

<td colspan="4"><input type="submit" name="Submit3" value="修改我的购物车"></td>

</tr>

</table> </td>

</tr>

<tr>

<td align="right">

<a href="ShoppingClServlet?type=show">

<img src="img/pre.jpg" width="85" height="19">&nbsp;

</a>

<a href="OrderClServlet">

<img src="img/next.jpg" width="84" height="18">

</a>

</td>

</tr>

</table></td>

</tr>

<tr>

<td align="center">

    <jsp:include page="tail.jsp" flush="true"></jsp:include>

    </td>

</tr>

</table>

</body>

</html>

 

view_WebRoot/shopping4.jsp

 

<%@ page language="java" import="java.util.*,Shop.model.*" pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

 

//订单的详细信息取出

OrderInfoBean oib=(OrderInfoBean)request.getAttribute("detailbean");

 

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'shopping4.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="css/my.css">

      

 

</head>

 

<body topmargin="0" background="img/bg.jpg">

<table width="80%" border="0" align="center" cellpadding="1" cellspacing="1">

<tr>

<td align="center">

    <jsp:include page="head.jsp" flush="true"></jsp:include>

    </td>

</tr>

<tr>

<td align="center"><table width="100%" border="1" cellpadding="1" cellspacing="1" bordercolor="#00CC00" class="abc">

<tr align="center">

<td colspan="9" nowrap><img src="img/shopping4/shopping4.jpg" width="599" height="44"></td>

</tr>

<tr>

<td colspan="9" align="center" nowrap>订单详细信息</td>

</tr>

<tr align="center">

<td nowrap>订单号</td>

<td nowrap>收货人</td>

<td nowrap>收货地址</td>

<td nowrap>邮编</td>

<td nowrap>电话</td>

<td nowrap>总价</td>

<td nowrap>用户名</td>

<td nowrap>电子邮件</td>

<td nowrap>备注</td>

</tr>

<tr align="center">

<td nowrap><%=oib.getOrdersId() %></td>

<td nowrap><%=oib.getTruename() %></td>

<td nowrap><%=oib.getAddress() %></td>

<td nowrap><%=oib.getPostcode()%></td>

<td nowrap><%=oib.getPhone() %></td>

<td nowrap><%=oib.getTotalPrice() %></td>

<td nowrap><%=oib.getUsername() %></td>

<td nowrap><%=oib.getEmail() %></td>

<td nowrap><a href="#">查看详情</a></td>

</tr>

<tr align="left">

<td colspan="9" nowrap>您的订单已完成,服务器将在稍后向您的电子邮箱发送确认信息,并确认订单信息。</td>

</tr>

</table></td>

</tr>

<tr>

<td align="center">

    <jsp:include page="tail.jsp" flush="true"></jsp:include>

    </td>

</tr>

</table>

</body>

</html>

 

Controller_src/Shop.servlet/ShowGoodsClServlet.java

 

package Shop.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import Shop.model.GoodsBean;

import Shop.model.GoodsBeanBO;

 

public class ShowGoodsClServlet extends HttpServlet {

 

    /**

     * The doGet method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to get.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        //System.out.println("进入了ShowGoodsClServlet");

        response.setContentType("text/html");

        response.setCharacterEncoding("utf-8"); //要记得写上这个,不然不能显示中文

        PrintWriter out=response.getWriter();

        

        //得到要显示的货物的id

        String goodsId=request.getParameter("id");

        //调用GoodsBeanBO [可以得到货物的具体信息]

        GoodsBeanBO gbb=new GoodsBeanBO();

        GoodsBean gb=gbb.getGoodsBean(goodsId);

        

        //得到type,判断用户是想分页,还是想显示贷物的详细信息

        String type=request.getParameter("type");

        

        if(type.equals("showDetail"))

        {

            //把gb放入到request

            request.setAttribute("goodsInfo", gb);

            

            //跳转

            request.getRequestDispatcher("showDetail.jsp").forward(request, response);

        }else if(type.equals("fenye"))

        {

            //得到pageNow

            String pageNow=request.getParameter("pageNow");

            //把pageNow放入到request

            request.setAttribute("pagenow", pageNow);

            //跳回购物大厅

            request.getRequestDispatcher("index.jsp").forward(request, response);

        }

    }

 

    /**

     * The doPost method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to post.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

}

 

Controller_src/Shop.servlet/ShoppingClServlet.java

 

package Shop.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import Shop.model.*;

 

public class ShoppingClServlet extends HttpServlet {

 

    /**

     * The doGet method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to get.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        //System.out.println("进入了ShoppingClServlet");    

        response.setContentType("text/html");

        response.setCharacterEncoding("utf-8");

        PrintWriter out=response.getWriter();

        

        //得到type值,判断用户是要进行怎样的操作

        String type=request.getParameter("type");

        

        //调用MyCartBD,完成购物

        //MyCartBO mbo=new MyCartBO(); //这样会造成有多个购物车

        //所以必须想办法,保证只有一个购物车

        

        //解决多个购物车问题

        //1.先试图从session中取出一个购物车

        MyCartBO mbo=(MyCartBO)request.getSession().getAttribute("mycart");

        

        if(mbo==null) //说明购物车还没有创建,用户是第一次点购买

        {

            //创建一个购物车,并放入session

            mbo=new MyCartBO();

            request.getSession().setAttribute("mycart", mbo);

        }

        

        if(type.equals("addGoods")) //添加货物

        {

            //获得货物的id

            String goodsId=request.getParameter("goodsId");

            //System.out.println("goodsId="+goodsId);

            

            //默认购买是1本书,以后可以修改

            mbo.addGoods(goodsId, "1");

        }

        else if(type.equals("delGoods")) //删除货物

        {

            //得到要删除的货物的id

            String goodsId=request.getParameter("goodsId");

            

            //从购物车中删除(session)

            mbo.delGoods(goodsId);

        }

        else if(type.equals("show"))//显示购物车

        {    

            //do nothing

        }

        else if(type.equals("delAll")) //清空货物

        {

            mbo.clear();

        }

        else if(type.equals("updateGoods"))//修改货物数量

        {

            //在servlet中得到货物的id,和新的数量,在界面上利用隐藏表单提交数据

            String goodsId[]=request.getParameterValues("goodsId");

            String newNums[]=request.getParameterValues("newNums");

            //测试是否得到新修改的值

            for(int i=0;i<goodsId.length;i++)

            {

                //System.out.println("id="+goodsId[i]+" 数量="+newNums[i]);

                mbo.upGoods(goodsId[i], newNums[i]);

                

            }

        }

        

        //把购物车的货物取出,准备在下一个页面显示

        ArrayList al=mbo.showMyCart();

        

        //放入到request

        request.setAttribute("mycartInfo", al);

        

        //跳转到showMyCart.jsp

        request.getRequestDispatcher("showMycart.jsp").forward(request, response);

    }

 

    /**

     * The doPost method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to post.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

}

 

Controller_src/Shop.servlet/LoginCl.java

 

package Shop.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import Shop.model.*;

 

public class LoginCl extends HttpServlet {

 

    /**

     * The doGet method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to get.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        response.setContentType("text/html");

        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        

        //得到用户名和密码,验证用户是否合法

        String u=request.getParameter("username");

        String p=request.getParameter("passwd");

        

        //验证用户

        UserBeanBO ubb=new UserBeanBO();

        if(ubb.checkUser(u, p))

        {

            //用户合法

            //1.把成功登录的用户信息放入session[后面要用到]

            UserBean ub=ubb.getUserBean(u);

            request.getSession().setAttribute("userInfo", ub);

            

            //2.把购物车的信息取出,准备在下一个页面显示

            MyCartBO mcb=(MyCartBO)request.getSession().getAttribute("mycart");

            

            ArrayList al=mcb.showMyCart();

            

            //把al放入request

            request.setAttribute("mycartInfo", al);

            

            request.getRequestDispatcher("shopping3.jsp").forward(request, response);

        }else

        {

            //用户不合法

            request.getRequestDispatcher("shopping2.jsp").forward(request, response);

        }

        

    }

 

    /**

     * The doPost method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to post.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

}

 

Controller_src/Shop.servlet/ShoppingCl2.java

 

/**

* 这个控制器用于检测用户是否登录过,如果没有登录就进入登录界面

* 如果登录过,就直接进入显示用户信息和购物车情况的页面

*/

 

package Shop.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import Shop.model.*;

public class ShoppingCl2 extends HttpServlet {

 

    /**

     * The doGet method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to get.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        response.setContentType("text/html");

        response.setCharacterEncoding("utf-8");

        PrintWriter out=response.getWriter();

        

        //1.看看session中是否有用户登录的信息

        UserBean ub=(UserBean)request.getSession().getAttribute("userInfo");

        if(ub==null)

        {

            //说明用户没有登录过

            //就跳转到shopping2.jsp

            request.getRequestDispatcher("shopping2.jsp").forward(request, response);

        }else

        {

            //说明登录过

            //2.把购物车的信息取出,准备在下一个页面显示

            MyCartBO mcb=(MyCartBO)request.getSession().getAttribute("mycart");

            

            ArrayList al=mcb.showMyCart();

            

            //把al放入request

            request.setAttribute("mycartInfo", al);

            

            //就跳转到shopping3.jsp

            request.getRequestDispatcher("shopping3.jsp").forward(request, response);

        }

    }

 

    /**

     * The doPost method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to post.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

}

 

Controller_src/Shop.servlet/OrderClServlet.java

 

/**

* 处理订单

*/

 

package Shop.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import Shop.model.*;

public class OrderClServlet extends HttpServlet {

 

    /**

     * The doGet method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to get.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        response.setContentType("text/html");

        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        

        //处理完成订单(把订单写入数据库)

        OrderBeanBO obb=new OrderBeanBO();

        //得到购物车

        MyCartBO mcb=(MyCartBO)request.getSession().getAttribute("mycart");

        

        //用户id

        long userId=((UserBean)request.getSession().getAttribute("userInfo")).getUserid();

        OrderInfoBean oib=obb.addOrder(mcb, userId+"");

        if(oib!=null)

        {

            //添加Ok

            //准备显示订单的详细信息的数据,给下个页面shopping4.jsp

            request.setAttribute("detailbean", oib);

            request.getRequestDispatcher("shopping4.jsp").forward(request, response);

        }

        else

        {

            //添加订单失败

            request.getRequestDispatcher("shopping3.jsp").forward(request, response);

        }

    }

 

    /**

     * The doPost method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to post.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        this.doGet(request, response);

    }

}

 

model_src/Shop.model/ConnDB.java

 

/**

* 这是一个model类

* 完成得到一个数据库连接

*/

 

package Shop.model;

import java.sql.*;

 

public class ConnDB {

    private Connection ct=null;

    

    public Connection getConn()

    {

        try {

            //Class.forName("org.gjt.mm.mysql.Driver").newInstance();

            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();

            //ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/shoppingdb","root","root");

            ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databaseName=shoppingdb","sa","luowei");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return ct;

    }

}

 

model_src/Shop.model/ GoodsBean.java

 

/**

* 这是一个model类 <---->goods表

*/

 

package Shop.model;

 

public class GoodsBean {

    

    public long getGoodsId() {

        return goodsId;

    }

    public void setGoodsId(long goodsId) {

        this.goodsId = goodsId;

    }

    public String getGoodsName() {

        return goodsName;

    }

    public void setGoodsName(String goodsName) {

        this.goodsName = goodsName;

    }

    public String getGoodsIntro() {

        return goodsIntro;

    }

    public void setGoodsIntro(String goodsIntro) {

        this.goodsIntro = goodsIntro;

    }

    public float getGoodsPrice() {

        return goodsPrice;

    }

    public void setGoodsPrice(float goodsPrice) {

        this.goodsPrice = goodsPrice;

    }

    public int getGoodsNum() {

        return goodsNum;

    }

    public void setGoodsNum(int goodsNum) {

        this.goodsNum = goodsNum;

    }

    public String getPublisher() {

        return publisher;

    }

    public void setPublisher(String publisher) {

        this.publisher = publisher;

    }

    public String getPhoto() {

        return photo;

    }

    public void setPhoto(String photo) {

        this.photo = photo;

    }

    public String getGoodsType() {

        return goodsType;

    }

    public void setGoodsType(String goodsType) {

        this.goodsType = goodsType;

    }

    private long goodsId;

    private String goodsName;

    private String goodsIntro;

    private float goodsPrice;

    private int goodsNum;

    private String publisher;

    private String photo;

    private String goodsType;

}

 

model_src/Shop.model/ GoodsBeanBO.java

/**

* 这是一个model类,处理与goods表相关的业务逻辑

*/

 

package Shop.model;

import java.sql.*;

import java.util.*;

 

public class GoodsBeanBO {

    //定义一些变量

    private ResultSet rs=null;

    private Connection ct=null;

    private PreparedStatement ps=null;

    

    //根据一个贷物id,得到贷物具体信息的函数

    public GoodsBean getGoodsBean(String id )

    {

        GoodsBean gb=new GoodsBean();

        try {

            ct=new ConnDB().getConn();

            

            ps=ct.prepareStatement("select * from goods where goodsId=?");

            ps.setString(1, id);

            rs=ps.executeQuery();

            

            if(rs.next())

            {

                //放入到db

                gb.setGoodsId(rs.getInt(1));

                gb.setGoodsName(rs.getString(2));

                gb.setGoodsIntro(rs.getString(3));

                gb.setGoodsPrice(rs.getFloat(4));

                gb.setGoodsNum(rs.getInt(5));

                gb.setPublisher(rs.getString(6));

                gb.setPhoto(rs.getString(7));

                gb.setGoodsType(rs.getString(8));

                

            }

            

        } catch (Exception e) {

            e.printStackTrace();

        }finally

        {

            this.close();

        }

        

        return gb;

    }

 

    /**返回共有多少页

     *

     */

    public int getPageCount(int pageSize)

    {

        int pageCount=0;

        int rowCount=0;

        try {

            ct=new ConnDB().getConn();

            ps=ct.prepareStatement("select count(*) from goods");

            //得到总有多少条记录

            rs=ps.executeQuery();

            if(rs.next())

            {

                rowCount=rs.getInt(1);

            }

            if(rowCount%pageSize==0)

            {

                pageCount=rowCount/pageSize;

            }else

            {

                pageCount=rowCount/pageSize+1;

            }

        } catch (Exception e) {

            e.printStackTrace();

        }finally{

            this.close();

        }

        return pageCount;

    }

    

    /**分页显示货物信息

     * @author luowei

     * @param int pageSize:每页显示几条记录

     * @param int pageNow:显示第几页

     * @return ArrayList [显示货物集合]

     * ctrl+shirft+m(可以引入包)

     */

    public ArrayList getGoodByPage(int pageSize,int pageNow)

    {

        ArrayList al=new ArrayList();

        try {

            ct=new ConnDB().getConn();

            ps=ct.prepareStatement("select top "+pageSize+" * from goods where goodsId not in " +

                    "(select top "+(pageSize*(pageNow-1))+" goodsId from goods)"); //sql server

            //ps=ct.prepareStatement("select * from goods order by goodsId limit "+(pageSize*(pageNow-1))+","+pageSize); //mysql

            

            rs=ps.executeQuery();

            while(rs.next())

            {

                GoodsBean gb=new GoodsBean();

                //放入到db

                gb.setGoodsId(rs.getInt(1));

                gb.setGoodsName(rs.getString(2));

                gb.setGoodsIntro(rs.getString(3));

                gb.setGoodsPrice(rs.getFloat(4));

                gb.setGoodsNum(rs.getInt(5));

                gb.setPublisher(rs.getString(6));

                gb.setPhoto(rs.getString(7));

                gb.setGoodsType(rs.getString(8));

                

                //加入到al

                al.add(gb);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }finally{

            this.close();

        }

        

        return al;

    }

      

    

    /**关闭资源

     *

     */

    public void close()

    {

        try {

            if(rs!=null)

            {

                rs.close();

                rs=null;

            }

            if(ps!=null)

            {

                ps.close();

                ps=null;

            }

            if(ct!=null)

            {

                ct.close();

                ct=null;

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

 

model_src/Shop.model/Test.java

 

/**

* hashmap使用的简单案例

*/

 

package Shop.model;

import java.util.*;

 

public class Test {

    

    public static void main(String []args)

    {

        HashMap hm=new HashMap();

        hm.put("1","3");

        hm.put("2","10");

        hm.put("3","100");

        

        //hm.remove("2");

        //hm.clear();

        

        //使用换代器

        Iterator it=hm.keySet().iterator();

        

        while(it.hasNext())

        {

            //取出key

            String key=(String)it.next();

            

            //根据key取出value

            String nums=(String)hm.get(key);

            

            System.out.println("key="+key+" nums="+nums);

        }

    }

}

 

model_src/Shop.model/MyCartBO.java

 

/**

* 这是一个BO(model)

* 用于处理与购物相关的业务逻辑(可以把它看成是一个购物车)

*/

 

package Shop.model;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.*;

 

public class MyCartBO {

    

    //定义一些变量

    private ResultSet rs=null;

    private Connection ct=null;

    private PreparedStatement ps=null;

    

    //定义一个haspmap集合,用于存放书的id和书的数量

    HashMap<String,String> hm=new HashMap<String,String>();

    

    //购物车的总价

    private float allPrice=0.0f;

    

    /**

     * 返回货物总价

     */

    public float returnAllPrices()

    {

        return this.allPrice;

    }

    

    /**根据货物id,返回货物的数量

     *

     */

    public String getGoodsNumById(String goodsId)

    {

        //System.out.println("进入了getGoodsNubById,货物id="+goodsId);

        return (String)hm.get(goodsId); //返回货物的数量

    }

    

    /**1.添加货物

     *

     */

    public void addGoods(String goodsId,String goodsNum)

    {

        hm.put(goodsId, goodsNum);

    }

    

    /**2.删除货物

     *

     */

    public void delGoods(String goodsId)

    {

        hm.remove(goodsId);

    }

    

    /**3.清空货物

     *

     */

    public void clear()

    {

        hm.clear();

    }

    

    /**4.修改货物数量

     *

     */

    public void upGoods(String goodsId,String goodsNum)

    {

        hm.put(goodsId, goodsNum);

    }

      

    

    /**5.显示购物车

     *

     */

    public ArrayList showMyCart()

    {

        ArrayList<GoodsBean> al=new ArrayList<GoodsBean>();

        try {

            //组织sql

            String sub="";

            //使用迭代器完成从hm中取出货物id

            Iterator it=hm.keySet().iterator();

 

            while(it.hasNext())

            {

                //取出goodsId

                String goodsId=(String)it.next();

                //判断goodsId是不是最后id

                if(it.hasNext())

                {

                    sub+=goodsId+",";

                }else

                {

                    sub+=goodsId;

                }

                //System.out.println(sub);

            }

            if(!sub.equals(""))

            {

                //System.out.println("进来了");

                String sql="select * from goods where goodsId in("+sub+")";

                ct=new ConnDB().getConn();

                ps=ct.prepareStatement(sql);

                rs=ps.executeQuery();

                

                this.allPrice=0.0f;//把总价清空

                while(rs.next())

                {

                    GoodsBean gb=new GoodsBean();

                    //放入到gb

                    int goodsId=rs.getInt(1);

                    gb.setGoodsId(goodsId);    //得到商品Id

                    gb.setGoodsName(rs.getString(2));

                    gb.setGoodsIntro(rs.getString(3));

                    float unitPrice=rs.getFloat(4);    //得到货物单价

                    gb.setGoodsPrice(unitPrice);

                    gb.setGoodsNum(rs.getInt(5));

                    gb.setPublisher(rs.getString(6));

                    gb.setPhoto(rs.getString(7));

                    gb.setGoodsType(rs.getString(8));

                    

                    //加入到al

                    al.add(gb);

                    //得出总价

                    this.allPrice=this.allPrice+unitPrice*Integer.parseInt(this.getGoodsNumById(goodsId+""));

                }

            }

 

        } catch (Exception e) {

            e.printStackTrace();

        }finally{

            this.close();

        }

        

        return al;

    }

      

 

    /**关闭资源

     *

     */

    public void close()

    {

        try {

            if(rs!=null)

            {

                rs.close();

                rs=null;

            }

            if(ps!=null)

            {

                ps.close();

                ps=null;

            }

            if(ct!=null)

            {

                ct.close();

                ct=null;

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

 

model_src/Shop.model/UserBean.java

 

/**

* 对用户表的映射

*/

 

package Shop.model;

 

public class UserBean {

    

    public long getUserid() {

        return userid;

    }

    public void setUserid(long userid) {

        this.userid = userid;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getTruename() {

        return truename;

    }

    public void setTruename(String truename) {

        this.truename = truename;

    }

    public String getPasswd() {

        return passwd;

    }

    public void setPasswd(String passwd) {

        this.passwd = passwd;

    }

    public String getEmail() {

        return email;

    }

    public void setEmail(String email) {

        this.email = email;

    }

    public String getPhone() {

        return phone;

    }

    public void setPhone(String phone) {

        this.phone = phone;

    }

    public String getAddress() {

        return address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

    public String getPostcode() {

        return postcode;

    }

    public void setPostcode(String postcode) {

        this.postcode = postcode;

    }

    public int getGrade() {

        return grade;

    }

    public void setGrade(int grade) {

        this.grade = grade;

    }

    private long userid;

    private String username;

    private String truename;

    private String passwd;

    private String email;

    private String phone;

    private String address;

    private String postcode;

    private int grade;

}

 

model_src/Shop.model/Test.java

 

/**

*此model 处理与user表相关的业务逻辑

*/

 

package Shop.model;

 

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

 

public class UserBeanBO {

    //定义一些变量

    private ResultSet rs=null;

    private Connection ct=null;

    private PreparedStatement ps=null;

    

    /*

     * 根据用户名返回UserBean

     */

    public UserBean getUserBean(String u)

    {

        UserBean ub=new UserBean();

        try {

            ct=new ConnDB().getConn();

            //ps=ct.prepareStatement("select * from users where userName=? limit 1");

            ps=ct.prepareStatement("select top 1 * from users where userName=?");

            ps.setString(1, u);

            rs=ps.executeQuery();

            if(rs.next())

            {

                ub.setUserid(rs.getLong(1));

                ub.setUsername(rs.getString(2));

                ub.setTruename(rs.getString(3));

                ub.setPasswd(rs.getString(4));

                ub.setEmail(rs.getString(5));

                ub.setPhone(rs.getString(6));

                ub.setAddress(rs.getString(7));

                ub.setPostcode(rs.getString(8));

                ub.setGrade(rs.getInt(9));

            }

        } catch (Exception e) {

            e.printStackTrace();

        }finally{

            this.close();

        }

        return ub;

    }

      

      

    

    /**

     * 验证用户是否合法

     */

    public boolean checkUser(String u,String p)

    {

        boolean b=false;

        try {

            ct=new ConnDB().getConn();

            //ps=ct.prepareStatement("select passWd from users where userName=? limit 1");

            ps=ct.prepareStatement("select top 1 passWd from users where userName=?");

            //limit 1 表示查到一条记录就返回,提高查询速度

            ps.setString(1,u); //给问号赋值

            rs=ps.executeQuery();

            if(rs.next())

            {

                //取出数据库的密码

                String dbPasswd=rs.getString(1);

                if(dbPasswd.equals(p))

                {

                    b=true;

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        }finally{

            //关闭资源

            this.close();

        }

        return b;

    }

    

    /**关闭资源

     *

     */

    public void close()

    {

        try {

            if(rs!=null)

            {

                rs.close();

                rs=null;

            }

            if(ps!=null)

            {

                ps.close();

                ps=null;

            }

            if(ct!=null)

            {

                ct.close();

                ct=null;

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

 

model_src/Shop.model/OrderBean.java

 

/**

* 对orders表的映射

*/

 

package Shop.model;

 

public class OrderBean {

    public long getOrdersId() {

        return ordersId;

    }

    public void setOrdersId(long ordersId) {

        this.ordersId = ordersId;

    }

    public long getUserId() {

        return userId;

    }

    public void setUserId(long userId) {

        this.userId = userId;

    }

    public java.util.Date getOrderDate() {

        return orderDate;

    }

    public void setOrderDate(java.util.Date orderDate) {

        this.orderDate = orderDate;

    }

    public String getPayMode() {

        return payMode;

    }

    public void setPayMode(String payMode) {

        this.payMode = payMode;

    }

    public byte getIsPayed() {

        return isPayed;

    }

    public void setIsPayed(byte isPayed) {

        this.isPayed = isPayed;

    }

    public float getTotalPrice() {

        return totalPrice;

    }

    public void setTotalPrice(float totalPrice) {

        this.totalPrice = totalPrice;

    }

    private long ordersId;

    private long userId;

    private java.util.Date orderDate;

    private String payMode;

    private byte isPayed;

    private float totalPrice;

}

 

model_src/Shop.model/OrderBeanBO.java

 

/**

* 对Orders表及orderDetail表的业务逻辑

*/

 

package Shop.model;

 

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

 

public class OrderBeanBO {

    

    //定义一些变量

    private ResultSet rs=null;

    private Connection ct=null;

    private PreparedStatement ps=null;

      

    

    /**

     * 生成订单

     * @param mbo 用户的购物车

     * @param userId 用户 id号

     * @return 返回一个订单详细信息Bean [OrderInfoBean]

     */

    public OrderInfoBean addOrder(MyCartBO mbo,String userId)

    {

        //System.out.println("进入了addOrder函数");

        OrderInfoBean oib=new OrderInfoBean();

        boolean b=true;

        try {

            ct=new ConnDB().getConn();

            //ps=ct.prepareStatement("insert into orders(userId,orderDate,payMode,isPayed,totalPrice)" +

                //    " values(?,(select curdate()),'huodaofukuan',?,?)");

            ps=ct.prepareStatement("insert into orders(userId,isPayed,totalPrice)" +

            " values(?,?,?)");

            ps.setString(1, userId);

            ps.setByte(2, (byte)0);

            ps.setFloat(3, mbo.returnAllPrices());

            

            //执行

            int a=ps.executeUpdate();

            if(a==1)

            {

                //System.out.println("添加orders表成功!");

                //必须取出刚刚添加到orders表的那个订单

                //取出最后那条orders的id就是了

                ps=ct.prepareStatement("select max(ordersId) from orders");

                rs=ps.executeQuery();

                long orderId=0;

                if(rs.next())

                {

                    orderId=rs.getInt(1);

                    //System.out.println("orderId="+orderId);

                }

                

                //orders表添加成功

                //添加orderDetail表

                //从购物车中取出所有选购的商品

                ArrayList al=mbo.showMyCart();

                //循环的添加到orders表 //循环添加效率低

                //我们可以批量操作数据库的方法,提高操作数据库的效率

                Statement sm=ct.createStatement();

                //System.out.println("al.size()="+al.size());

                for(int i=0;i<al.size();i++)

                {

                    GoodsBean gb=(GoodsBean)al.get(i);

                    //System.out.println("gb.getGoodsId()="+gb.getGoodsId());

                    sm.addBatch("insert into orderDetail values('"+orderId+"','"+gb.getGoodsId()+

                            "','"+mbo.getGoodsNumById(gb.getGoodsId()+"")+"')");

                }

                //批量执行添加任务

                sm.executeBatch();

                

                String sql="select ordersId,trueName,address,postcode,phone,totalPrice,userName,email from users,orders" +

                        " where ordersId=? and users.userId=(select orders.userId from orders where ordersId=?)";

                ps=ct.prepareStatement(sql);

                ps.setLong(1, orderId);

                ps.setLong(2, orderId);

                

                rs=ps.executeQuery(); //执行

                if(rs.next())

                {

                    oib.setOrdersId(rs.getLong(1));

                    oib.setTruename(rs.getString(2));

                    oib.setAddress(rs.getString(3));

                    oib.setPostcode(rs.getString(4));

                    oib.setPhone(rs.getString(5));

                    oib.setTotalPrice(rs.getFloat(6));

                    oib.setUsername(rs.getString(7));

                    oib.setEmail(rs.getString(8));

                }

                

            }else

            {

                //添加订单失败

                System.out.println("添加订单失败");

                

            }

        } catch (Exception e) {

            b=false;

            e.printStackTrace();

        }finally{

            this.close();

        }

        if(b)

        {

            return oib;

        }

        else{

            return null;

        }

    }

      

    

    /**关闭资源

     *

     */

    public void close()

    {

        try {

            if(rs!=null)

            {

                rs.close();

                rs=null;

            }

            if(ps!=null)

            {

                ps.close();

                ps=null;

            }

            if(ct!=null)

            {

                ct.close();

                ct=null;

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

 

model_src/Shop.model/ OrderDetailBean.java

 

/**

* 映射orderDetail表

*/

 

package Shop.model;

 

public class OrderDetailBean {

    public long getOrdersId() {

        return ordersId;

    }

    public void setOrdersId(long ordersId) {

        this.ordersId = ordersId;

    }

    public long getGoodsId() {

        return goodsId;

    }

    public void setGoodsId(long goodsId) {

        this.goodsId = goodsId;

    }

    public int getNums() {

        return nums;

    }

    public void setNums(int nums) {

        this.nums = nums;

    }

    private long ordersId;

    private long goodsId;

    private int nums;

}

 

model_src/Shop.model/ OrderInfoBean.java

 

/**

* 这是一个最全的javaBean

* 显示订单详细信息时,要用它

*/

 

package Shop.model;

 

public class OrderInfoBean {

    public long getUserid() {

        return userid;

    }

    public void setUserid(long userid) {

        this.userid = userid;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getTruename() {

        return truename;

    }

    public void setTruename(String truename) {

        this.truename = truename;

    }

    public String getPasswd() {

        return passwd;

    }

    public void setPasswd(String passwd) {

        this.passwd = passwd;

    }

    public String getEmail() {

        return email;

    }

    public void setEmail(String email) {

        this.email = email;

    }

    public String getPhone() {

        return phone;

    }

    public void setPhone(String phone) {

        this.phone = phone;

    }

    public String getAddress() {

        return address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

    public String getPostcode() {

        return postcode;

    }

    public void setPostcode(String postcode) {

        this.postcode = postcode;

    }

    public int getGrade() {

        return grade;

    }

    public void setGrade(int grade) {

        this.grade = grade;

    }

    public long getOrdersId() {

        return ordersId;

    }

    public void setOrdersId(long ordersId) {

        this.ordersId = ordersId;

    }

    public long getUserId() {

        return userId;

    }

    public void setUserId(long userId) {

        this.userId = userId;

    }

    public java.util.Date getOrderDate() {

        return orderDate;

    }

    public void setOrderDate(java.util.Date orderDate) {

        this.orderDate = orderDate;

    }

    public String getPayMode() {

        return payMode;

    }

    public void setPayMode(String payMode) {

        this.payMode = payMode;

    }

    public byte getIsPayed() {

        return isPayed;

    }

    public void setIsPayed(byte isPayed) {

        this.isPayed = isPayed;

    }

    public float getTotalPrice() {

        return totalPrice;

    }

    public void setTotalPrice(float totalPrice) {

        this.totalPrice = totalPrice;

    }

    private long userid;

    private String username;

    private String truename;

    private String passwd;

    private String email;

    private String phone;

    private String address;

    private String postcode;

    private int grade;

    private long ordersId;

    private long userId;

    private java.util.Date orderDate;

    private String payMode;

    private byte isPayed;

    private float totalPrice;

}

posted @ 2011-08-14 19:46  维唯为为  阅读(779)  评论(0编辑  收藏  举报