JSP教程第7、8讲笔记

继续开发网上购物商城
先解决页面显示的问题
显示商品的具体信息
首页面的分页功能
用户登录、注册界面设计
将商品添加到购物车,将商品从购物车删除,清空购物车,修改购物车的数量,购物流程mvc设计
难点,修改需要购买的商品数量,使用隐藏表单

在这里插入图片描述
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">
	<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>
    <td width="74%"><jsp:include flush="true" page="right.jsp"></jsp:include></td></td>
  </tr>
  <tr>
    <td height="121" colspan="2" align="center">
    <jsp:include flush="true" page="tail.jsp"></jsp:include></td>
  </tr>
</table>
  </body>
</html>

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">&nbsp;</td>
        <td width="13%" align="center" class="navi">香港电影</td>
        <td width="13%" align="center">&nbsp;</td>
        <td width="13%" align="center" class="navi">大陆电影</td>
        <td width="10%" align="center">&nbsp;</td>
        <td width="11%" align="center" class="navi">关于我们</td>
        <td width="12%" align="center">&nbsp;</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-8820</td>
  </tr>
  <tr>
    <td align="center" class="abc">邮编:100000 客服邮箱:fashionshopping@sina.com</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">滚动的图片</script></td>
      </tr>
    </table></td>
  </tr>
  <tr>
    <td valign="middle" bgcolor="#FF66FF">&nbsp;</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">1</td>
        <td align="center" class="abc"><a href="head.html">倚天屠龙记</a></td>
        <td align="center" class="abc">55</td>
      </tr>
      <tr>
        <td align="center" class="abc">2</td>
        <td align="center" class="abc">西游记</td>
        <td align="center" class="abc">11</td>
      </tr>
      <tr>
        <td align="center" class="abc">3</td>
        <td align="center" class="abc">笑傲江湖</td>
        <td align="center" class="abc">5</td>
      </tr>
      <tr>
        <td align="center" class="abc">4</td>
        <td align="center" class="abc">西厢记</td>
        <td align="center" class="abc">4</td>
      </tr>
      <tr>
        <td align="center" class="abc">5</td>
        <td align="center" class="abc">红楼梦</td>
        <td align="center" class="abc">3</td>
      </tr>
      <tr>
        <td align="center" class="abc">6</td>
        <td align="center" class="abc">水浒传</td>
        <td align="center" class="abc">2</td>
      </tr>
      <tr>
        <td align="center" class="abc">7</td>
        <td align="center" class="abc">射雕英雄传</td>
        <td align="center" class="abc">1</td>
      </tr>
    </table></td>
  </tr>
</table>

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>&nbsp;<%}%>

<%	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>&nbsp;<%}%>
</td>
</tr>
</table>

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");
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'showItem.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="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>
<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">&nbsp;</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">&nbsp;</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">&nbsp;</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>
  </body>
</html>

shoppingCar.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");
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'showShoppingCar.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="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() %>"/><input name="newNums" type="text" value="<%=sbo.getGoodsNumById(gb.getGoodsId()+"") %>" size="7"/>&nbsp;</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">&nbsp;</td>
        <td align="center" valign="middle">
            <input type="submit" name="Submit" onclick="delAll();" value="删除全部书籍" />  
        </td>
        <td align="center" valign="middle">&nbsp;<input type="submit" name="Submit2" value="修改数量" /></td>
        <td colspan="3" align="center" valign="middle">&nbsp;</td>
      </tr>
      <tr>
        <td colspan="6" align="center" valign="middle">&nbsp;</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"><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>

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();
			
		}
	}
}
//用于演示HashMap的用法,在此项目中不需要此文件
package com.tingwei.model;
import java.util.*;
public class TestHashMap {
	public static void main(String []args){
		HashMap hm=new HashMap();
		hm.put("1", "3");
		hm.put("2", "4");
		hm.put("5", "100");
		
		//删除"2"
		hm.remove("2");
		
		//取出所有key
		//使用迭代器
		Iterator it=hm.keySet().iterator();
		while(it.hasNext()){
			//取出key
			String key=(String)it.next();
			System.out.println("key=="+key);
			//根据key取出value
			String nums=(String)hm.get(key);
			System.out.println("nums=="+nums);
		}
	}

}

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. <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 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. <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);
	}

}

ShoppingClServlet.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. <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();
		
		//得带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. <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);
	}

}

WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ShowGoodsClServlet</servlet-name>
    <servlet-class>com.tingwei.servlet.ShowGoodsClServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ShoppingClServlet</servlet-name>
    <servlet-class>com.tingwei.servlet.ShoppingClServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>ShowGoodsClServlet</servlet-name>
    <url-pattern>/ShowGoodsClServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ShoppingClServlet</servlet-name>
    <url-pattern>/ShoppingClServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-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;
}

运行结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值