JSP教程第9讲笔记

继续开发网上购物商城

用户登录
显示用户订单
订单表的设计
发送电子邮件javaMail
购物流程设计

通过订单细节表,把订单表和商品表的多对多的关系,简化为一对多的关系,从而解决了数据冗余的问题。

完整的网上购物商城源码如下:

JSP部分

head.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting pagetitle>
	<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="mycss/Untitled-3.css">

  head>
  
  <body>
    <table width="80%" border="0.5" align="center">
  <tr>
    <td height="117" colspan="2" align="center">
    <jsp:include flush="true" page="head.jsp">jsp:include>
    td>
  tr>
  <tr>
    <td width="21%" height="198">
    <jsp:include flush="true" page="left.jsp">jsp:include>
    td>
    <td width="74%"><jsp:include flush="true" page="right.jsp">jsp:include>td>
  tr>
  <tr>
    <td height="121" colspan="2" align="center">
    <jsp:include flush="true" page="tail.jsp">jsp:include>td>
  tr>
table>
  body>
html>

JSP教程第9讲笔记_第1张图片
head.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<table width="100%" border="0.5">
  <tr>
    <td height="10" colspan="3" bgcolor="#FF9999">td>
  tr>
  <tr>
    <td width="26%" align="center"><img src="images/logo5.jpg" width="183" height="53" align="middle" />td>
    <td width="40%" align="center" valign="middle"><img src="images/logo22.jpg" width="367" height="85" align="middle" />td>
    <td width="13%" align="center" valign="middle" bordercolor="#FFFFFF"><p><img src="images/logo1.jpg" width="30" height="29" align="top" />【我的账号】p>
    <p><img src="images/logo12.jpg" width="32" height="28" /><a href="ShoppingClServlet?type=show">【我的购物车】a>p>td>
  tr>
  <tr>
    <td height="10" colspan="3" bgcolor="#FF99FF">td>
  tr>
  <tr>
    <td colspan="3"><table width="100%" border="0.5" align="center">
      <tr>
        <td width="15%" align="center" class="navi">首页td>
        <td width="13%" align="center"> td>
        <td width="13%" align="center" class="navi">香港电影td>
        <td width="13%" align="center"> td>
        <td width="13%" align="center" class="navi">大陆电影td>
        <td width="10%" align="center"> td>
        <td width="11%" align="center" class="navi">关于我们td>
        <td width="12%" align="center"> td>
      tr>
    table>td>
  tr>
table>

在这里插入图片描述
tail.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" align="center">
  <tr>
    <td align="center" bgcolor="#FF6699" class="abc">合作伙伴:搜狐 网易 腾讯 新浪td>
  tr>
  <tr>
    <td align="center" class="abc">地址:湖北省十堰市 客户热线:400-820-8820td>
  tr>
  <tr>
    <td align="center" class="abc">邮编:100000 客服邮箱:[email protected]td>
  tr>
  <tr>
    <td align="center" class="abc">Copyright 天马星空科技有限公司td>
  tr>
table>

在这里插入图片描述
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.5" align="center">
  <tr>
    <td align="center" valign="middle"><table width="100%" border="0.5">
      <tr>
        <td align="center"><img src="images/9.jpg" width="276" height="50" />td>
      tr>
      <tr>
        <td align="center">滚动的图片td>
      tr>
    table>td>
  tr>
  <tr>
    <td valign="middle" bgcolor="#FF66FF"> td>
  tr>
  <tr>
    <td valign="middle"><table width="100%" border="0.5">
      <tr>
        <td colspan="3" align="center"><img src="images/logo23.jpg" width="190" height="75" />td>
        tr>
      <tr>
        <td align="center" class="abc">销量榜td>
        <td align="center" class="abc">商品名称td>
        <td align="center" class="abc">点击次数td>
      tr>
      <tr>
        <td align="center" class="abc">1td>
        <td align="center" class="abc"><a href="head.html">倚天屠龙记a>td>
        <td align="center" class="abc">55td>
      tr>
      <tr>
        <td align="center" class="abc">2td>
        <td align="center" class="abc">西游记td>
        <td align="center" class="abc">11td>
      tr>
      <tr>
        <td align="center" class="abc">3td>
        <td align="center" class="abc">笑傲江湖td>
        <td align="center" class="abc">5td>
      tr>
      <tr>
        <td align="center" class="abc">4td>
        <td align="center" class="abc">西厢记td>
        <td align="center" class="abc">4td>
      tr>
      <tr>
        <td align="center" class="abc">5td>
        <td align="center" class="abc">红楼梦td>
        <td align="center" class="abc">3td>
      tr>
      <tr>
        <td align="center" class="abc">6td>
        <td align="center" class="abc">水浒传td>
        <td align="center" class="abc">2td>
      tr>
      <tr>
        <td align="center" class="abc">7td>
        <td align="center" class="abc">射雕英雄传td>
        <td align="center" class="abc">1td>
      tr>
    table>td>
  tr>
table>

JSP教程第9讲笔记_第2张图片
right.jsp

<%@ page language="java" import="java.util.*,com.tingwei.model.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

//使用GoodsBeanBO,完成分页(也可以先走servlet)
GoodsBeanBO gbb=new GoodsBeanBO();
String s_pageNow=(String)request.getAttribute("pageNow");
int pageSize=9;
int pageNow=1;
if(s_pageNow!=null)
{
	pageNow=Integer.parseInt(s_pageNow);
}
//默认显示第一页
ArrayList al=gbb.getGoodsByPage(pageSize,pageNow);
//得到总共有多少页
int pageCount=gbb.getPageCount(pageSize);
%>
<table width="80%" border="0.5" align="center">
  <tr valign="middle">
    <td colspan="3" align="center" class="abc"><img src="images/logo24.jpg" width="203" height="47" />td>
  tr>

  <tr>
    <td 
    width="32%" align="center" valign="middle" class="abc"><p><img src="images/<%=((GoodsBean)al.get(0)).getPhoto() %>" width="100" height="100" />p>
    <a href="ShowGoodsClServlet?type=showItem&id=<%=((GoodsBean)al.get(0)).getGoodsId() %>"><%=((GoodsBean)al.get(0)).getGoodsName() %>a>
    td>
    <td width="30%" align="center" class="abc"><p><img src="images/<%=((GoodsBean)al.get(1)).getPhoto() %>" width="100" height="100" />p>
    <a href="ShowGoodsClServlet?type=showItem&id=<%=((GoodsBean)al.get(1)).getGoodsId() %>"><%=((GoodsBean)al.get(1)).getGoodsName() %>a>
    td>
    <td width="38%" align="center" class="abc"><p><img src="images/<%=((GoodsBean)al.get(2)).getPhoto() %>" width="100" height="100" />p>
    <a href="ShowGoodsClServlet?type=showItem&id=<%=((GoodsBean)al.get(2)).getGoodsId() %>"><%=((GoodsBean)al.get(2)).getGoodsName() %>a>
    td>
  tr>
  <tr>
    <td 
    width="32%" align="center" valign="middle" class="abc"><p><img src="images/<%=((GoodsBean)al.get(3)).getPhoto() %>" width="100" height="100" />p>
    <a href="ShowGoodsClServlet?type=showItem&id=<%=((GoodsBean)al.get(3)).getGoodsId() %>"><%=((GoodsBean)al.get(3)).getGoodsName() %>a>
    td>
    <td width="30%" align="center" class="abc"><p><img src="images/<%=((GoodsBean)al.get(4)).getPhoto() %>" width="100" height="100" />p>
    <a href="ShowGoodsClServlet?type=showItem&id=<%=((GoodsBean)al.get(4)).getGoodsId() %>"><%=((GoodsBean)al.get(4)).getGoodsName() %>a>
    td>
    <td width="38%" align="center" class="abc"><p><img src="images/<%=((GoodsBean)al.get(5)).getPhoto() %>" width="100" height="100" />p>
    <a href="ShowGoodsClServlet?type=showItem&id=<%=((GoodsBean)al.get(5)).getGoodsId() %>"><%=((GoodsBean)al.get(5)).getGoodsName() %>a>
    td>
  tr>
  <tr>
    <td 
    width="32%" align="center" valign="middle" class="abc"><p><img src="images/<%=((GoodsBean)al.get(6)).getPhoto() %>" width="100" height="100" />p>
    <a href="ShowGoodsClServlet?type=showItem&id=<%=((GoodsBean)al.get(6)).getGoodsId() %>"><%=((GoodsBean)al.get(6)).getGoodsName() %>a>
    td>
    <td width="30%" align="center" class="abc"><p><img src="images/<%=((GoodsBean)al.get(7)).getPhoto() %>" width="100" height="100" />p>
    <a href="ShowGoodsClServlet?type=showItem&id=<%=((GoodsBean)al.get(7)).getGoodsId() %>"><%=((GoodsBean)al.get(7)).getGoodsName() %>a>
    td>
    <td width="38%" align="center" class="abc"><p><img src="images/<%=((GoodsBean)al.get(8)).getPhoto() %>" width="100" height="100" />p>
    <a href="ShowGoodsClServlet?type=showItem&id=<%=((GoodsBean)al.get(8)).getGoodsId() %>"><%=((GoodsBean)al.get(8)).getGoodsName() %>a>
    td>
  tr>
<tr>
<td colspan="3" align="center">
<%if(pageNow!=1){%><a href="ShowGoodsClServlet?type=fenye&pageNow=<%=pageNow-1%>">上一页a> <%}%>

<%	for(int i=1;i<=pageCount;i++){
		%>
		<a href="ShowGoodsClServlet?type=fenye&pageNow=<%=i %>">[<%=i %>]a>
		<% 
	}
 %>
 <%if(pageNow!=pageCount){%><a href="ShowGoodsClServlet?type=fenye&pageNow=<%=pageNow+1%>">下一页a> <%}%>
td>
tr>
table>

JSP教程第9讲笔记_第3张图片
showItem.jsp

<%@ page language="java" import="java.util.*,com.tingwei.model.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//取出要显示的信息
GoodsBean gb=(GoodsBean)request.getAttribute("goodsInfo");
%>


<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'showItem.jsp' starting pagetitle>
	<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="mycss/Untitled-3.css">
	<script type="text/javascript">
	//响应返回购物大厅事件
		function returnHall(){
			window.open("index.jsp","_self");
		}
		
		//响应点击购买货物的事件,用此函数检测window.alert(goodsId);
		function addGoods(goodsId){
			window.open("ShoppingClServlet?type=addGoods&goodsId="+goodsId,"_self");
		}
	script>
  head>

  <body>
  <center>
  <table width="80%" border=0 align="center">
  <tr>
    <td align="center">
    <jsp:include flush="true" page="head.jsp">jsp:include>
    td>
  tr>
  <tr>
    <td height="309" align="center">
    <table width="100%" border="1px">
      <tr>
        <td colspan="2"> td>
        tr>
      <tr>
        <td width="25%" rowspan="7"><img src="images/<%=gb.getPhoto() %>" width="267" height="166" />td>
        <td align="center"><%=gb.getGoodsName() %>td>
      tr>
      <tr>
        <td align="left">价格:<%=gb.getGoodsPrice() %> td>
      tr>
      <tr>
        <td align="left"> td>
      tr>
      <tr>
        <td align="left">ISBN:<%=gb.getGoodsId()%>td>
      tr>
      <tr>
        <td align="left">类型:<%=gb.getType() %>td>
      tr>
      <tr>
        <td align="left">出版商:<%=gb.getPublisher() %>td>
      tr>
      <tr>
        <td align="left">简介:<%=gb.getGoodsIntro() %>td>
      tr>
      
      <tr>
        <td colspan="2"> td>
        tr>
      <tr>
        <td height="43" colspan="2"><form id="form1" name="form1" method="post" action="返回购物大厅">
          <label>
          <input type="button" name="Submit" onclick="addGoods(<%=gb.getGoodsId() %>);" value="购买" />
          label>
          <input type="button" name="Submit2" onclick="returnHall();" value="返回购物大厅" />
        form>
        td>
        tr>
    table>td>
  tr>
  <tr>
    <td height="22" align="center">
    <jsp:include flush="true" page="tail.jsp">jsp:include>td>
  tr>
table>
  center>
  body>
html>

JSP教程第9讲笔记_第4张图片
showShoppingCar.jsp

<%@ page language="java" import="java.util.*,com.tingwei.model.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//取出ArrayList里的购物信息
ArrayList al=(ArrayList)request.getAttribute("myCarInfo");
//从session中取出购物车
ShoppingBO sbo=(ShoppingBO)session.getAttribute("mycar");
%>


<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'showShoppingCar.jsp' starting pagetitle>
    
	<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="mycss/Untitled-3.css">

  <script type="text/javascript">
  function delAll(){
  	window.open("ShoppingClServlet?type=delAll","-self");
  }
  script>
  head>
  
  <body>
    <center>
    <table width="80%" border="1" align="center">
  <tr>
    <td align="center">
    <jsp:include flush="true" page="head.jsp">jsp:include>
    td>
  tr>
  <tr>
    <td align="center">
    <form action="ShoppingClServlet?type=updateGoods" method="post">
    <table width="100%" border="1">
      <tr>
        <td colspan="6" align="center"><img src="images/logo3.jpg" width="756" height="66" align="middle" />td>
        tr>
      <tr>
        <td width="29%" align="center" valign="middle">编号td>
        <td width="16%" align="center" valign="middle">书名td>
        <td width="16%" align="center" valign="middle">单价td>
        <td colspan="3" align="left" valign="middle">数量td>
      tr>
      <%
      	for(int i=0;i<al.size();i++){
      	GoodsBean gb=(GoodsBean)al.get(i);
      	%>
      	<tr>
        <td align="center" valign="middle"><%=gb.getGoodsId() %>td>
        <td align="center" valign="middle"><%=gb.getGoodsName() %>td>
        <td align="center" valign="middle">¥<%=gb.getGoodsPrice() %>td>
        <td width="13%" ><input type="hidden" name="goodsId" value="<%=gb.getGoodsId() %>"/>" size="7"/> td>
        <td width="13%" ><a href="ShoppingClServlet?type=delGoods&goodsId=<%=gb.getGoodsId() %>">删除a>td>
        <td width="13%" ><a href="ShowGoodsClServlet?type=showItem&id=<%=gb.getGoodsId() %>">查看a>td>
      	tr>
      	<%
      	}
       %>
      <tr>
        <td align="center" valign="middle"> td>
        <td align="center" valign="middle">
            <input type="submit" name="Submit" onclick="delAll();" value="删除全部书籍" />  
        td>
        <td align="center" valign="middle"> <input type="submit" name="Submit2" value="修改数量" />td>
        <td colspan="3" align="center" valign="middle"> td>
      tr>
      <tr>
        <td colspan="6" align="center" valign="middle"> td>
        tr>
      table>
      form>
      <tr>
        <td height="20" colspan="2" align="left" valign="middle">您共选择了价值¥<font color=red><%=sbo.getTotalPrice() %>font>的商品,点击<a href="index.jsp">此处a>继续购物。td>
        <td height="20" colspan="4" align="right" valign="middle"><a href="IsLoginServlet"><img src="images/logo25.jpg" width="85" height="30" />a>td>
        tr>
    table>
    td>
  tr>
  <tr>
    <td align="center">
    <jsp:include flush="true" page="tail.jsp">jsp:include>
    td>
  tr>
table>
center>
  body>
html>

JSP教程第9讲笔记_第5张图片

userLogin.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'userLogin.jsp' starting pagetitle>
    
	<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="mycss/Untitled-3.css">
  head>
  
  <body>
    <center>
    <table width="80%" border="1" align="center">
  <tr>
    <td align="center">
  <jsp:include flush="true" page="head.jsp">jsp:include>  
  td>
  tr>
  <tr>
    <td align="center"><table width="100%" border="1">
      <tr>
        <td align="center"><img src="images/logo3.jpg" width="756" height="66" />td>
      tr>
      <tr>
        <td align="center">
        <form action="LoginDealServlet" method="post">
        <table width="40%" border="1" bordercolor="#6699CC">
          <tr>
            <td colspan="2" align="center"><img src="images/logo26.jpg" width="212" height="55" />td>
            tr>
          <tr>
            <td align="right">用户名:td>
            <td align="left"><input name="username" type="text" size="15" />td>
          tr>
          <tr>
            <td align="right"> 码:td>
            <td><input name="passwd" type="text" size="15" />td>
          tr>
          <tr>
            <td align="right"><input type="submit" name="Submit" value="用户登录"/>td>
            <td align="left"><input type="submit" name="Submit2" value="用户注册" />td>
          tr>
        table>
        form>
        td>
      tr>
      <tr>
        <td align="right"><img src="images/logo25.jpg" width="85" height="30" />td>
      tr>
    table>td>
  tr>
  <tr>
    <td align="center">
    <jsp:include flush="true" page="tail.jsp">jsp:include>
  	td>
  tr>
table>
    center>
  body>
html>

JSP教程第9讲笔记_第6张图片
userInfo.jsp

<%@ page language="java" import="java.util.*,com.tingwei.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("mycarInfo");
ShoppingBO sbo=(ShoppingBO)session.getAttribute("mycar");
%>


<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'userInfo.jsp' starting pagetitle>
    
	<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="mycss/Untitled-3.css">
  head>
  
  <body>
  <center>
  <table width="80%" border="1" align="center">
  <tr>
    <td align="center">
    <jsp:include flush="true" page="head.jsp">jsp:include>
    td>
  tr>
  <tr>
    <td align="center"><table width="100%" border="1">
      <tr>
        <td align="center"><img src="images/logo3.jpg" width="756" height="66" />td>
      tr>
      <tr>
        <td align="center"><table width="70%" border="1" class="abc">
          <tr>
            <td colspan="2" align="center">购买人信息td>
            tr>
          <tr>
            <td align="right">用户名:td>
            <td align="left">
              <input type="text" name="textfield" value="<%=ub.getUsername() %>"/>
            td>
          tr>
          <tr>
            <td align="right">*真实姓名td>
            <td align="left"><input type="text" name="textfield2" value="<%=ub.getTruename() %>"/>td>
          tr>
          <tr>
            <td align="right">*收获地址td>
            <td align="left"><input type="text" name="textfield3" value="<%=ub.getAddress() %>"/>td>
          tr>
          <tr>
            <td align="right">*联系电话td>
            <td align="left"><input type="text" name="textfield4" value="<%=ub.getPhone() %>"/>td>
          tr>
          <tr>
            <td align="right">*电子邮件td>
            <td align="left"><input type="text" name="textfield5" value="<%=ub.getEmail() %>"/>td>
          tr>
          <tr>
            <td align="right">*邮  编td>
            <td align="left"><input type="text" name="textfield6" value="<%=ub.getPostcode() %>"/>td>
          tr>
          <tr>
            <td align="right"><form id="form1" name="form1" method="post" action="">
              
                <input type="submit" name="Submit" value="完成订单" />
                form>
            td>
            <td align="left"><input type="submit" name="Submit2" value="修改个人信息" />td>
          tr>
        table>td>
      tr>
      <tr>
        <td align="center"><table width="70%" border="1">
          <tr>
            <td colspan="4" align="center">我的购物车情况td>
            tr>
          <tr>
            <td align="center">商品编号td>
            <td align="center">商品名称td>
            <td align="center">商品单价td>
            <td align="center">商品数量td>
          tr>
          <%
          for(int i=0;i<al.size();i++){
          	GoodsBean gb=(GoodsBean)al.get(i);;
          	%>
          	<tr>
            <td align="center"><%=gb.getGoodsId() %>td>
            <td align="center"><%=gb.getGoodsName() %>td>
            <td align="center"><%=gb.getGoodsPrice() %>td>
            <td align="center"><%=sbo.getGoodsNumById(gb.getGoodsId()+"") %>td>
          tr>
          	<% 
          }
           %>
          <tr>
            <td colspan="4" align="center">您一共购买了价值¥<%=sbo.getTotalPrice() %>的商品td>
            tr>
          <tr>
            <td colspan="4" align="center"><a href="showShoppingCar.jsp">返回购物车a>td>
            tr>
        table>td>
      tr>
      <tr>
        <td align="right"><img src="images/logo27.jpg" width="85" height="31" /><a href="OrderServlet"><img border="0" src="images/logo25.jpg" width="85" height="30" />a>td>
      tr>
    table>td>
  tr>
  <tr>
    <td align="center">
    <jsp:include flush="true" page="tail.jsp">jsp:include>
    td>
  tr>
table>
  center>
  body>
html>

JSP教程第9讲笔记_第7张图片
shoppingOrder.jsp

<%@ page language="java" import="java.util.*,com.tingwei.model.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
OrderInfoBean oib=(OrderInfoBean)request.getAttribute("orderInfo");
%>


<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'shoppingOrder.jsp' starting pagetitle>
    
	<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="mycss/Untitled-3.css">
	

  head>
  
  <body>
  <center>
  <table width="80%" border="1" align="center">
  <tr>
    <td align="center">
    <jsp:include flush="true" page="head.jsp">jsp:include>
    td>
  tr>
  <tr>
    <td align="center"><table width="100%" border="1">
      <tr>
        <td colspan="9" align="center">图片td>
        tr>
      <tr>
        <td colspan="9" align="center">订单详细信息td>
        tr>
      <tr>
        <td align="center">订单号td>
        <td align="center">收货人td>
        <td align="center">收获地址td>
        <td align="center">邮编td>
        <td align="center">电话td>
        <td align="center">总价td>
        <td align="center">用户名td>
        <td align="center">电子邮件td>
        <td align="center"> td>
      tr>
      <tr>
        <td align="center"><%=oib.getOrdersId() %>td>
        <td align="center"><%=oib.getTruename() %>td>
        <td align="center"><%=oib.getAddress() %>td>
        <td align="center"><%=oib.getPostcode() %>td>
        <td align="center"><%=oib.getPhone() %>td>
        <td align="center"><%=oib.getTotalPrice() %>td>
        <td align="center"><%=oib.getUsername() %>td>
        <td align="center"><%=oib.getEmail() %>td>
        <td align="center"><a href="userInfo.jsp">查看详情a>td>
      tr>
      <tr>
        <td colspan="9" align="center">您的订单已完成,稍后将将发送邮件给您,并确认订单信息。td>
        tr>
    table>td>
  tr>
  <tr>
    <td height="17" align="center">
    <jsp:include flush="true" page="tail.jsp">jsp:include>
    td>
  tr>
table>
center>
  body>
html>

JSP教程第9讲笔记_第8张图片

Java模型部分

ConnDB.java

package com.tingwei.model;
import java.sql.*;
public class ConnDB {
	private Connection ct=null;
	public Connection getConn(){
		try {
			Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
			String url="jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=testdb";
			String user="sa";
			String pass="tingwei";
			ct=DriverManager.getConnection(url,user,pass);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return ct;
	}
}

GoodsBean.java

package com.tingwei.model;

public class GoodsBean {
	private long goodsId;
	private String goodsName;
	private String goodsIntro;
	private float goodsPrice;
	private int goodsNum;
	private String publisher;
	private String photo;
	private String type;
	public long getGoodsId() {
		return goodsId;
	}
	public void setGoodsId(long goodsId) {
		this.goodsId = goodsId;
	}
	public String getGoodsIntro() {
		return goodsIntro;
	}
	public void setGoodsIntro(String goodsIntro) {
		this.goodsIntro = goodsIntro;
	}
	public String getGoodsName() {
		return goodsName;
	}
	public void setGoodsName(String goodsName) {
		this.goodsName = goodsName;
	}
	public float getGoodsPrice() {
		return goodsPrice;
	}
	public void setGoodsPrice(float goodsPrice) {
		this.goodsPrice = goodsPrice;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public String getPublisher() {
		return publisher;
	}
	public void setPublisher(String publisher) {
		this.publisher = publisher;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public int getGoodsNum() {
		return goodsNum;
	}
	public void setGoodsNum(int goodsNum) {
		this.goodsNum = goodsNum;
	}
}

GoodsBeanBO.java

//处理与goods表相关的操作
package com.tingwei.model;
import java.sql.*;
import java.util.ArrayList;
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()){
				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.setType(rs.getString(8));
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			//关闭资源
			this.close();
		}
		return gb;
	}
	
	/*
	 * 分页显示货物信息
	 * @parameter int pageSize;每页显示记录数
	 * @author someone
	 * @parameter int pageNow 显示第几页
	 * ctrl+shift+m自动引包
	 */
	public ArrayList getGoodsByPage(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 "+(pageNow-1)*pageSize+" goodsId from goods)");
			rs=ps.executeQuery();
			while(rs.next()){
				GoodsBean gb=new GoodsBean();
				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.setType(rs.getString(8));
				al.add(gb); //very important,don't forget 
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			this.close();
		}
		return al;
	}
	//得到总共有多少页
	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) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return pageCount;
	}
	
	//关闭数据库方法
	public void close(){
		try {
			if(rs!=null)rs.close();
			if(ps!=null)ps.close();
			if(ct!=null)ct.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			
		}
	}
}

ShoppingBO.java

//处理与购物有关的逻辑
//添加商品、删除商品、清空商品、修改货物数量、显示已选商品清单
package com.tingwei.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
public class ShoppingBO {
	private float totalPrice=0;//购物车商品总价
	private ResultSet rs=null;
	private Connection ct=null;
	private PreparedStatement ps=null;
	HashMap <String,String>hm=new HashMap<String,String>();//泛型,明确告诉编译器key值和value值都是String类型的
	//添加商品
	public void addGoods(String goodsId,String goodsNum){
		hm.put(goodsId,goodsNum);
	}
	//删除商品
	public void delGoods(String goodsId){
		hm.remove(goodsId);
	}
	//清空商品
	public void clearGoods(){
		hm.clear();
	}
	//修改货物数量
	public void updateGoods(String goodsId,String newNum){
		hm.put(goodsId, newNum);
	}
	//显示已选商品清单
	public ArrayList showMyCar(){
		ArrayList <GoodsBean>al=new ArrayList<GoodsBean>();//明确告诉编译器,ArrayList放的是GoodsBean
		try {
			String sub="";
			String sql="select * from goods where goodsId in";
			//使用迭代器,完成从HashMap中取出货物id
			Iterator it=hm.keySet().iterator();
			sub="(";
			while(it.hasNext()){
				//取出goodsId
				String goodsId=(String)it.next();
				//判断goodsId是否是最后一个id
				if(it.hasNext()){
					sub+=goodsId+",";
				}else{
					sub+=goodsId+")";
				}
			}
			sql+=sub;//不可少
			System.out.println("执行的sql语句"+sql);
			ct=new ConnDB().getConn();
			ps=ct.prepareStatement(sql);
			rs=ps.executeQuery();
			//总价清空
			this.totalPrice=0;
			while(rs.next()){
				GoodsBean gb=new GoodsBean();
				int goodsId=rs.getInt(1);
				gb.setGoodsId(goodsId);
				gb.setGoodsName(rs.getString(2));
				gb.setGoodsIntro(rs.getString(3));
				gb.setGoodsPrice(rs.getFloat(4));
				float unit=rs.getFloat(4);
				gb.setGoodsNum(rs.getInt(5));
				gb.setPublisher(rs.getString(6));
				gb.setPhoto(rs.getString(7));
				gb.setType(rs.getString(8));
				this.totalPrice+=unit*Integer.parseInt(this.getGoodsNumById(goodsId+""));
				al.add(gb);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			this.close();
		}
		return al;
	}
	
	/*
	 * 根据商品id得到商品顾客选择的商品数量
	 * @param goodsId
	 * @return 商品数量
	 */
	public String getGoodsNumById(String goodsId){
		return (String)hm.get(goodsId);
	}
	//返回购物车总价的方法,不必单独写,可以在showMyCar中使用现成的数据来计算
	public float getTotalPrice(){
		return this.totalPrice;
	}
	
//	关闭数据库方法
	public void close(){
		try {
			if(rs!=null)rs.close();
			if(ps!=null)ps.close();
			if(ct!=null)ct.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			
		}
	}
}

UserBean.java

//表示users表
package com.tingwei.model;

public class UserBean {
	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;
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getPostcode() {
		return postcode;
	}
	public void setPostcode(String postcode) {
		this.postcode = postcode;
	}
	public String getTruename() {
		return truename;
	}
	public void setTruename(String truename) {
		this.truename = truename;
	}
	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;
	}
}

UserBeanBO.java

//表示对users表相关操作
package com.tingwei.model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;

public class UserBeanBO {
	private PreparedStatement ps=null; //PrepareStatement差不多,更快点
	private Connection ct=null;
	private ResultSet rs=null;
	//得到用户信息
	public UserBean getUserBean(String u){
		UserBean ub=new UserBean();
		try {
			ct=new ConnDB().getConn();
			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) {
			// TODO: handle exception
			e.printStackTrace();
		}
		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='"+u+"'");
			rs=ps.executeQuery();
			if(rs.next()){
				if(rs.getString(1).equals(p)){
					b=true;
				}
			}	
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			this.close();
		}
		return b;
	}
	
	public void close(){
		try {
			if(rs!=null)rs.close();
			if(ps!=null)ps.close();
			if(ct!=null)ct.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}

OrderBean.java

package com.tingwei.model;

public class OrderBean {
	private long ordersId;
	private long userId;
	private java.util.Date orderDate;
	private String payType;
	private byte isPayed;
	private float totalPrice;
	public byte getIsPayed() {
		return isPayed;
	}
	public void setIsPayed(byte isPayed) {
		this.isPayed = isPayed;
	}
	public java.util.Date getOrderDate() {
		return orderDate;
	}
	public void setOrderDate(java.util.Date orderDate) {
		this.orderDate = orderDate;
	}
	public long getOrdersId() {
		return ordersId;
	}
	public void setOrdersId(long ordersId) {
		this.ordersId = ordersId;
	}
	public String getPayType() {
		return payType;
	}
	public void setPayType(String payType) {
		this.payType = payType;
	}
	public float getTotalPrice() {
		return totalPrice;
	}
	public void setTotalPrice(float totalPrice) {
		this.totalPrice = totalPrice;
	}
	public long getUserId() {
		return userId;
	}
	public void setUserId(long userId) {
		this.userId = userId;
	}
}

OrderBeanBO.java

package com.tingwei.model;
import java.sql.*;
import java.util.ArrayList;
public class OrderBeanBO {
	private ResultSet rs=null;
	private Connection ct=null;
	private PreparedStatement ps=null;
	/*
	 * 生产订单信息
	 * @param sbo用户购物车处理对象
	 * @param userId用户id
	 * @return OrderInfoBean
	 */
	public OrderInfoBean addOrder(ShoppingBO sbo,String userId){
		OrderInfoBean oib=new OrderInfoBean();
		boolean b=true;
		try {

			ct=new ConnDB().getConn();
			ps=ct.prepareStatement("insert into orders (userId,isPayed,totalPrice) values(?,?,?)");
			ps.setString(1, userId);
			ps.setByte(2, (byte)0);
			ps.setFloat(3, sbo.getTotalPrice());
			if(ps.executeUpdate()==1){
				ps=ct.prepareStatement("select max(ordersId) from orders");
				rs=ps.executeQuery();
				int orderId=0;
				if(rs.next()){
					orderId=rs.getInt(1);
				}
				//添加orderDetail表
				//从购物车中取出商品
				ArrayList al=sbo.showMyCar();
				Statement sm=ct.createStatement();
				for(int i=0;i<al.size();i++){
					GoodsBean gb=(GoodsBean)al.get(i);
					System.out.println("insert into orderDetail values('"+orderId+"','"+gb.getGoodsId()+"','"+sbo.getGoodsNumById(gb.getGoodsId()+"")+"')");
					sm.addBatch("insert into orderDetail values('"+orderId+"','"+gb.getGoodsId()+"','"+sbo.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.setInt(1, orderId);
				ps.setInt(2, orderId);
				rs=ps.executeQuery();
				if(rs.next()){
					//将rs封装到OrderInfoBean 中
					oib.setOrdersId(rs.getInt(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));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			b=false;
			e.printStackTrace();
		}finally{
			this.close();
	}
		if(b){
			return oib;
		}else{
			return null;
		}
}
	

//关闭数据库方法
public void close(){
	try {
		if(rs!=null)rs.close();
		if(ps!=null)ps.close();
		if(ct!=null)ct.close();
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
		
	}
}
}


OrderInfoBean.java

//详细的订单信息
package com.tingwei.model;

public class OrderInfoBean {
	private int userId;
	private String username;
	private String truename;
	private String address;
	private String phone;
	private String Email;
	private String postcode;
	private int grade;
	private int ordersId;
	private java.util.Date orderDate;
	private String payType;
	private byte isPayed;
	private float totalPrice;
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
	public byte getIsPayed() {
		return isPayed;
	}
	public void setIsPayed(byte isPayed) {
		this.isPayed = isPayed;
	}
	public java.util.Date getOrderDate() {
		return orderDate;
	}
	public void setOrderDate(java.util.Date orderDate) {
		this.orderDate = orderDate;
	}
	public int getOrdersId() {
		return ordersId;
	}
	public void setOrdersId(int ordersId) {
		this.ordersId = ordersId;
	}
	public String getPayType() {
		return payType;
	}
	public void setPayType(String payType) {
		this.payType = payType;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getPostcode() {
		return postcode;
	}
	public void setPostcode(String postcode) {
		this.postcode = postcode;
	}

	public String getTruename() {
		return truename;
	}
	public void setTruename(String truename) {
		this.truename = truename;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getEmail() {
		return Email;
	}
	public void setEmail(String email) {
		Email = email;
	}
	public float getTotalPrice() {
		return totalPrice;
	}
	public void setTotalPrice(float totalPrice) {
		this.totalPrice = totalPrice;
	}
	
}

第三部分 Servlet控制器

ShowGoodsClServlet.java

//此控制器用来处理主页面信息显示请求
package com.tingwei.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 com.tingwei.model.*;
public class ShowGoodsClServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. 
* * 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 type=request.getParameter("type"); if(type.equals("showItem")){ // 得到要显示的商品id String goodsId=request.getParameter("id"); //调用BO GoodsBeanBO gbb=new GoodsBeanBO(); GoodsBean gb=gbb.getGoodsBean(goodsId); //把gb放入request request.setAttribute("goodsInfo",gb); request.getRequestDispatcher("showItem.jsp").forward(request, response); }else if(type.equals("fenye")){ String pageNow=request.getParameter("pageNow"); //把pageNow放入request request.setAttribute("pageNow", pageNow); //跳转回购物大厅 request.getRequestDispatcher("index.jsp").forward(request, response); } } /** * The doPost method of the servlet.
* * 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); } }

ShoppingClServle.java

//此控制器用来处理购物操作请求
package com.tingwei.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 com.tingwei.model.*;
import java.util.ArrayList;
public class ShoppingClServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. 
* * 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(); //得带type值,从而知道顾客需要的购物操作 String type=request.getParameter("type"); // 调用ShoppingBO,完成购物功能,??这里有问题,会造成有多个购物车,必须保证始终只有一个购物车,解决办法采用session //1.先试图从session中取出一个购物车 ShoppingBO sbo=(ShoppingBO)request.getSession().getAttribute("mycar"); if(sbo==null){ //创建一个购物车,并放入session sbo=new ShoppingBO(); request.getSession().setAttribute("mycar", sbo); } if(type.equals("addGoods")){ // 获得要购买的商品id String goodsId=request.getParameter("goodsId"); sbo.addGoods(goodsId, "1"); }else if(type.equals("delGoods")){ //得到要删除的商品id String goodsId=request.getParameter("goodsId"); //从购物车中删除 sbo.delGoods(goodsId); }else if(type.equals("show")){ //do nothing }else if(type.equals("delAll")){ sbo.clearGoods(); }else if(type.equals("updateGoods")){ //接收商品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]); sbo.updateGoods(goodsId[i], newNums[i]); } //sbo.updateGoods(goodsId, newNum) } // 把购物车的商品信息取出来,准备显示 ArrayList al=sbo.showMyCar(); //放入request中 request.setAttribute("myCarInfo", al); //跳转到showShoppingCar.jsp request.getRequestDispatcher("showShoppingCar.jsp").forward(request, response); } /** * The doPost method of the servlet.
* * 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); } }

IsLoginServlet.java

//此控制器用来识别用户是否登录过
package com.tingwei.servlet;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import com.tingwei.model.*;

public class IsLoginServlet extends HttpServlet {
	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){
			request.getRequestDispatcher("userLogin.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("shoppingOrder.jsp").forward(request, response);
		}
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response)
	throws ServletException,IOException {
		this.doGet(request, response);
	}
}

LoginDealServlet.java

//此控制器用来处理验证用户登录请求
package com.tingwei.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 com.tingwei.model.*;
import java.util.ArrayList;
public class LoginDealServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. 
* * 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"); System.out.println("用户"+u); UserBeanBO ubb=new UserBeanBO(); if(ubb.checkUser(u, p)){ //把登录成功的用户信息放入session UserBean ub=ubb.getUserBean(u); request.getSession().setAttribute("userInfo", ub); //取出购物车中的商品信息 ShoppingBO sbo=(ShoppingBO)request.getSession().getAttribute("mycar"); ArrayList al=sbo.showMyCar(); request.setAttribute("mycarInfo", al); request.getRequestDispatcher("userInfo.jsp").forward(request, response); }else{ request.getRequestDispatcher("userLogin.jsp").forward(request, response); } } /** * The doPost method of the servlet.
* * 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); } }

OrderServlet.java

//此控制器用来处理订单生成请求
package com.tingwei.servlet;
import com.tingwei.model.*;

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;

public class OrderServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. 
* * 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(); //得到购物车 ShoppingBO sbo=(ShoppingBO)request.getSession().getAttribute("mycar"); long userId=((UserBean)request.getSession().getAttribute("userInfo")).getUserId(); OrderInfoBean oib=obb.addOrder(sbo, userId+""); if(oib!=null){ //准备订单数据,做一个订单Bean request.setAttribute("orderInfo", oib); request.getRequestDispatcher("shoppingOrder.jsp").forward(request, response); }else{ //添加订单失败 request.getRequestDispatcher("userInfo.jsp").forward(request, response); } } /** * The doPost method of the servlet.
* * 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); } }

第四部分 配置文件

WEB-INF/web.xml


<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>ShowGoodsClServletservlet-name>
    <servlet-class>com.tingwei.servlet.ShowGoodsClServletservlet-class>
  servlet>
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>ShoppingClServletservlet-name>
    <servlet-class>com.tingwei.servlet.ShoppingClServletservlet-class>
  servlet>
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>IsLoginServletservlet-name>
    <servlet-class>com.tingwei.servlet.IsLoginServletservlet-class>
  servlet>
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>OrderServletservlet-name>
    <servlet-class>com.tingwei.servlet.OrderServletservlet-class>
  servlet>
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>LoginDealServletservlet-name>
    <servlet-class>com.tingwei.servlet.LoginDealServletservlet-class>
  servlet>



  <servlet-mapping>
    <servlet-name>ShowGoodsClServletservlet-name>
    <url-pattern>/ShowGoodsClServleturl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>ShoppingClServletservlet-name>
    <url-pattern>/ShoppingClServleturl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>IsLoginServletservlet-name>
    <url-pattern>/IsLoginServleturl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>OrderServletservlet-name>
    <url-pattern>/OrderServleturl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>LoginDealServletservlet-name>
    <url-pattern>/LoginDealServleturl-pattern>
  servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>
web-app>

mycss/Untitled-3.css

.abc {
	font-family: "新宋体";
	font-size: 9px;
}

.navi {
	font-family: "新宋体";
	font-size: 12px;
	background-color: #33FF00;
}

第五部分 sql语句


go
create database testdb
use testdb
--普通用户表users
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,--商品编号
goodsName varchar(40),--商品名称
goodsIntro varchar(500),--介绍
goodsPrice float,--价格
goodsNum int,--库存
publisher varchar(40),--出版社
photo varchar(40),--商品照片
type varchar(10),--商品种类
)
select *from goods
insert into goods values('《西游记》','讲述了唐僧师徒四人西天取经的故事',58,33,'中央电视台','01.jpg','大陆电视剧')
insert into goods values('《王者荣耀》','讲述了十个人游戏玩家的故事',58,33,'腾讯','02.jpg','国产游戏')
insert into goods values('《炉石传说》','讲述了炉石传说',99,33,'乐视','03.jpg','大陆电视剧')
insert into goods values('《肖申克的旧书》','讲述了肖申克二十年挖洞越狱的励志故事',58,33,'好莱坞','04.jpg','美国电影')

select *from users
insert into users values('YaLee','亚历','yali','[email protected]','153755','七星关中学','655223',2)
insert into users values('sunce','孙策','sunce','[email protected]','153755','琅琊路中学','655223',2)


--分页,若一页显示6条,排除0条选6条,即显示第一页
select top 6 * from goods where goodsId not in (select top 0 goodsId from goods);

--分页,若一页显示6条,排除6条选6条,即显示第二页
select top 6 * from goods where goodsId not in (select top 6 goodsId from goods);

update goods set photo='11.jpg' where goodsId=11

insert into goods(goodsName,goodsIntro,goodsPrice,goodsNum,publisher,photo,type)select goodsName,goodsIntro,goodsPrice,goodsNum,publisher,photo,type from goods

select * from goods where goodsId in(1,4);

use testdb
create table orders(
ordersId bigint primary identity(1,1),--订单号
userId bigint constraint fk_client_id,references users(userid),--哪个用户订的
orderDate datetime default getdate(),--下单时间
payType varchar(20) check(payType in('货到付款','支付宝付款'))default '货到付款',--付款方式
isPayed bit check (isPayed in(0,1)),--表示是否付款了
totalPrice float not null--数量	
)



use testdb


--订单细节表
create table orderDetail(
ordersI bigint constraint fk_order_id references orders(ordersId),--订单号(并是一个外键)指向orders表
goodsId bigint constraint fk_goods_id references goods(goodsId),--商品号
nums int not null--数量
)

select * from orderDetail
select * from orders
select * from users
select passwd from users where username='sunce'

JSP教程第9讲笔记_第9张图片
JSP教程第9讲笔记_第10张图片
JSP教程第9讲笔记_第11张图片

总结

你可能感兴趣的:(Java,EE实战教程)