最简单的小型商城实现:Serlvet+Jsp经典案例

1. 前台client有关的页面

【header.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions"  prefix="fn"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>  
  	<link href="${pageContext.request.contextPath}/css/css.css" rel="stylesheet" type="text/css" />  
    <title>首页</title>   
  </head>
  
<body style="text-align:center">
<br />
	<a href="${pageContext.request.contextPath}">首页</a>
	<span style="width:800px"></span>
	<c:if test="${empty user}"><!-- 也可以是:${sessionScope.user==null} -->
		<a href="${pageContext.request.contextPath}/client/login.jsp">登录</a>
		<a href="${pageContext.request.contextPath}/client/regist.jsp">注册</a>
	</c:if>
	<c:if test="${!empty user}">
		欢迎您:${user.username}  <!-- ${sessionScope.user.username} -->
		<a href="${pageContext.request.contextPath}/clientServlet?operation=logout">注销</a>
	</c:if>
	<a href="${pageContext.request.contextPath}/clientServlet?operation=showUsersOrders">我的订单</a>  
	<a href="${pageContext.request.contextPath}/client/showCart.jsp">我的购物车</a>
<br />
<script language="javascript">
	function qiehuan(num){
		for(var id = 0;id<=9;id++)
		{
			if(id==num)
			{
				document.getElementById("qh_con"+id).style.display="block";
				document.getElementById("mynav"+id).className="nav_on";
			}
			else
			{
				document.getElementById("qh_con"+id).style.display="none";
				document.getElementById("mynav"+id).className="";
			}
		}
	}
</script>
<div id=menu_out>
  <div id=menu_in>
    <div id=menu>
      <UL id=nav>
        <LI><A class=nav_on id=mynav0 οnmοuseοver=javascript:qiehuan(0) href="#"><SPAN>所有分类</SPAN></A></LI>
        <LI class="menu_line"></LI>
    </UL>
      <div id=menu_con>
        <div id=qh_con0 style="DISPLAY: block">
          <UL>
          <c:forEach items="${sessionScope.cs}" var="c">
	            <LI><A href="${pageContext.request.contextPath}/clientServlet?operation=showCategoryBook&categoryId=${c.id}"><SPAN>${c.name }</SPAN></A></LI>
	            <LI class=menu_line2></LI>
            </c:forEach>
            </UL>
         </div>
      </div>
    </div>
  </div>
  </div>

【listOrder.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/client/header.jsp" %>
	<h1>您近期的订单如下:</h1>
		<table border="1" width="88%" style="text-align:center" align="center">
			<tr>
				<th>订单号</th>
				<th>金额</th>
				<th>订单状态</th>
				<th>明细</th>
			
			</tr>
			<c:forEach items="${ os}" var="o">
				<tr>
					<td>${o.ordernum}</td>
					<td>¥${o.price }元</td>
					<td>${o.state==0?'未发货':'已发货'}</td>
					<td>
						<a href="${pageContext.request.contextPath}/clientServlet?operation=showOrdersDetail&ordersId=${o.id}">订单详情</a>
					</td>
				</tr>
			</c:forEach>
		</table>
  </body>
</html>


【login.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/client/header.jsp" %>
	<h1>用户登录</h1>	
	<form action="${pageContext.request.contextPath}/clientServlet?operation=login" method="post"> 
		<table border="1" width="88%" style="text-align:center" align="center">
			<tr>
				<td>用户名</td>
				<td>
					<input type="text" name="username"/>
				</td>
			</tr>
			<tr>
				<td>密码</td>
				<td>
					<input type="password" name="password"/>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="登录"/>
				</td>
			</tr>
			
		</table>
	</form>
  </body>
</html>


【orderMsg.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/client/header.jsp" %>
	订单号:${o.ordernum}  </br>金额:¥${o.price }元</br>
	明细如下:</br>
		<table border="1" width="88%" style="text-align:center" align="center">
			<tr>
				<th>书名</th>
				<th>作者</th>
				<th>单价</th>
				<th>小计</th>
				<th>数量</th>
			</tr>
			<c:forEach items="${o.items }" var="i">
				<tr>
					<td>${i.book.name}</td>
					<td>${i.book.author}</td>
					<td>¥${i.book.price}元</td>
					<td>${i.num}</td>
					<td>¥${i.price}元</td>
				</tr>
			</c:forEach>
		</table>
   	收货信息如下:</br>
   		地址:${sessionScope.user.address}</br> 		
   		电话:${sessionScope.user.cellphone}</br>
  </body>
</html>

【regist.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/client/header.jsp" %>
	<h1>新用户注册</h1>	
	<form action="${pageContext.request.contextPath}/clientServlet?operation=regist" method="post"> 
		<table border="1" width="88%" style="text-align:center" align="center">
			<tr>
				<td>用户名</td>
				<td>
					<input type="text" name="username" />
				</td>
			</tr>
			<tr>
				<td>密码</td>
				<td>
					<input type="password" name="password" />
				</td>
			</tr>
			<tr>
				<td>确认密码</td>
				<td>
					<input type="password" name="password1" />
				</td>
			</tr>
			<tr>
				<td>电话</td>
				<td>
					<input type="text" name="cellphone" />
				</td>
			</tr>
			<tr>
				<td>手机</td>
				<td>
					<input type="text" name="mobilephone" />
				</td>
			</tr>
			<tr>
				<td>住址</td>
				<td>
					<input type="text" name="address" />
				</td>
			</tr>
			<tr>
				<td>邮箱</td>
				<td>
					<input type="text" name="email" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="注册" />
				</td>
			</tr>
		</table>	
	</form>
  </body>
</html>


【showChart.jsp】


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/client/header.jsp" %>
	<h1>您购买的商品如下</h1>
	<c:if test="${empty sessionScope.cart.items}">
		<img height="180" width="120" src="${pageContext.request.contextPath }/files/0.jpg"/><br/>对不起,您没有购买任何商品
	</c:if>
	<c:if test="${!empty sessionScope.cart.items}">
		<table border="1" width="88%" style="text-align:center" align="center">
			<tr>
				<th>书名</th>
				<th>作者</th>
				<th>单价</th>
				<th>数量</th>
				<th>小计</th>
				<th>操作</th>
			</tr>
			<c:forEach items="${ sessionScope.cart.items}" var="me">
				<tr>
					<td>${me.value.book.name}</td>
					<td>${me.value.book.author }</td>
					<td>${me.value.book.price }</td>
					<td>${me.value.num }</td>
					<td>${me.value.price}</td>
					<td>
						<a href="#" >删除</a>
					</td>
				</tr>
			</c:forEach>
			<tr>
				<td colspan="6" align="right">
					总数量:${sessionScope.cart.num}  
					付款金额:${sessionScope.cart.price}  
					<a href="${pageContext.request.contextPath }/clientServlet?operation=genOrders">生成订单</a>
				</td>
			</tr>
		</table>
	</c:if>
  </body>
</html>

【welcome.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/client/header.jsp" %>
<h1>欢迎光临</h1>
	<!-- 显示分页数据,不分类的 -->
	<table align="center">
		<tr >
			<c:forEach items="${page.records}" var="b">
				<td>
					<table>
						<tr>
							<td>
								<img src="${pageContext.request.contextPath}/files/${b.image}"/>
							</td>
						</tr>
						<tr>
							<td>
								书名:${b.name }<br />
								作者:${b.author }<br />
								原价:<strike>888</strike><br/>
								震撼价:${b.price}
							</td>
						</tr>
						<tr>
							<td>
								<a href="${pageContext.request.contextPath}/clientServlet?operation=buyBook&bookId=${b.id}">购买</a>
							</td>
						</tr>
					</table>
				</td>
			</c:forEach>
		</tr>
	</table>
			
		<tr align="center">
			<td>
				<%@ include file="/commons/page.jsp" %>
			</td>
		</tr>
	
  </body>
</html>

2. 前台manager相关页面

【header.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://hw.com/jsp/jstl/myfunctions" prefix="myfn" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<link href="${pageContext.request.contextPath}/css/css.css" rel="stylesheet" type="text/css" />
  <head>  
    <title>首页</title>   
  </head>
  
  <body style="text-align:center">
  
  <br />
<br />
<script language="javascript">
	function qiehuan(num){
		for(var id = 0;id<=9;id++)
		{
			if(id==num)
			{
				document.getElementById("qh_con"+id).style.display="block";
				document.getElementById("mynav"+id).className="nav_on";
			}
			else
			{
				document.getElementById("qh_con"+id).style.display="none";
				document.getElementById("mynav"+id).className="";
			}
		}
	}
</script>
<div id=menu_out>
  <div id=menu_in>
    <div id=menu>
      <UL id=nav>
        <LI><A class=nav_on id=mynav0 οnmοuseοver=javascript:qiehuan(0) href="#"><SPAN>分类管理</SPAN></A></LI>
        <LI class="menu_line"></LI>
        <li><a href="#" οnmοuseοver="javascript:qiehuan(1)" id="mynav1" class="nav_off"><span>图书管理</span></a></li>
        <li class="menu_line"></li>
        <li><a href="#" οnmοuseοver="javascript:qiehuan( 2)" id="mynav2" class="nav_off"><span>订单管理</span></a></li>
        <li class="menu_line"></li>
        
        
      </UL>
      <div id=menu_con>
        <div id=qh_con0 style="DISPLAY: block">
          <UL>
            <LI><a href="${pageContext.request.contextPath}/manage/addCategory.jsp"><span>添加分类</span></A></LI>
            <LI class=menu_line2></LI>
            <LI><A href="${pageContext.request.contextPath}/manageServlet?operation=listCategory"><SPAN>查询分类</SPAN></A></LI>
            <LI class=menu_line2></LI>
           
          </UL>
        </div>
        <div id=qh_con1 style="DISPLAY: none">
          <UL>
            <LI><a href="${pageContext.request.contextPath}/manageServlet?operation=showCategoryUI"><span>添加图书</span></A></LI>
            <LI class=menu_line2></LI>
            <LI><A href="${pageContext.request.contextPath}/manageServlet?operation=showAllBook"><SPAN>查询图书</SPAN></A></LI>
            <LI class=menu_line2></LI>
           
          </UL>
        </div>
        <div id=qh_con2 style="DISPLAY: none">
          <UL>
            <LI><a href="${pageContext.request.contextPath}/manageServlet?operation=showAllOrders0"><span>待处理订单</span></A></LI>
            <LI class=menu_line2></LI>
            <LI><A href="${pageContext.request.contextPath}/manageServlet?operation=showAllOrders1"><SPAN>已处理订单</SPAN></A></LI>
            <LI class=menu_line2></LI>
          </UL>
        </div>  
      </div>
    </div>
  </div>
</div>


【listBook.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/manage/header.jsp" %>
<h3>书籍列表</h3>
	<table border="1" width="88%" align="center" style="text-align:center">
		<tr>
			<th>书名</th>
			<th>作者</th>
			<th>描述</th>
			<th>所属分类</th>
			<th>图片</th>
			<th>操作</th>
		</tr>
		<c:forEach items="${page.records}" var="b">
			<tr>
				<td>${ b.name}</td>
				<td>${b.author }</td>
				<td>${b.description }</td>
				<td>${myfn:getCategoryNameByIdEL(b.category_id)}</td>
				<td>
					<a href="${pageContext.request.contextPath}/files/${b.image}">查看图片</a>
				</td>
				<td>
					<a href="#" >[修改]</a>  
					<a href="#" >[删除]</a>
				</td>
			</tr>
		</c:forEach>
	</table>
	<!-- 视频内容简单分页内容开始 -->
	<!--  
	第${page.pagenum}页/共${page.totalpage}页  
	<a href="${pageContext.request.contextPath}/manageServlet?operation=showAllBook&pagenum=
		${page.pagenum-1>0?pagenum-1:1}">上一页</a>
	<a href="${pageContext.request.contextPath}/manageServlet?operation=showAllBook&pagenum=
		${page.pagenum+1>page.totalpage?page.totalpage:(page.pagenum+1)}">下一页</a>
		-->
	<%@ include file="/commons/page.jsp" %>
		
	<!-- 视频内容简单分页内容结束 -->
  </body>
</html>


【listCategory.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/manage/header.jsp" %>
	<h2>分类列表</h2>
	<c:if test="${empty cs}">
		对不起,没有分类,请先添加
	</c:if>
	<c:if test="${!empty cs}">
	<table border="1" width="88%" style="text-align:center" align="center">
		<tr>
			<th>选择</th>
			<th>分类名称</th>
			<th>描述</th>
			<th>操作</th>
		</tr>
		<c:forEach items="${cs}" var="c">
			<tr>
				<td>
					<input type="checkbox" name="cids" value="${c.id }"/>
				</td>
				<td>${c.name }</td>
				<td>${c.description }</td>
				<td>
					<a href="#" >更改</a>
					<a href="#" >删除</a>
				</td>
			<tr>
		</c:forEach>
	</table>
	</c:if>
  </body>
</html>


【addBook.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/manage/header.jsp" %>
	<h2 align="center">添加图书</h2>
	<form action="${pageContext.request.contextPath}/manageServlet?operation=addBook" method="post" enctype="multipart/form-data" >
		<table border="0" width="88%" align="center">
			<tr>
				<td>书名</td>
				<td>
					<input type="text" name="name"/>
				</td>
			</tr>
			<tr>
				<td>作者</td>
				<td>
					<input type="text" name="author"/>
				</td>
			</tr>
			<tr>
				<td>售价</td>
				<td>
					<input type="text" name="price"/>
				</td>
			</tr>
			<tr>
				<td>图片</td>
				<td>
					<input type="file" name="img"/> <!-- ★和javabean的名字不一样 -->
				</td>
			</tr>
			<tr>
				<td>描述</td>
				<td>
					<textarea rows="3" cols="38" name="description"></textarea>
				</td>
			</tr>
			<tr>
				<td>所属分类</td>
				<td>
					<select name="category_id">
						<c:forEach items="${cs}" var="c">
							<option value="${c.id}">${c.name}</option> 
						</c:forEach>
					</select>
				</td>
			</tr>
			<tr>
				<td>
					<input type="submit" value="添加图书"></td>
			</tr>
		</table>
	</form>
	${message}
  </body>
</html>


【addCategory.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/manage/header.jsp" %>
	<form action="${pageContext.request.contextPath}/manageServlet?operation=addCategory" method="post">  
		<table align="center"  border="1" width="88%" >
			<tr>
				<td>*分类名称</td>
				<td>
					<input type="text" name="name"/>
				</td>
			</tr>
			<tr>
				<td>概述</td>
				<td>
					<textarea rows="3" cols="34" name="description"></textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="添加"/>
				</td>
			</tr>
		
		</table>
	</form>
  </body>
</html>

【showOrders.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/client/header.jsp" %>
	<h1>未发货订单如下:</h1>
		<table border="1" width="88%" style="text-align:center" align="center">
			<tr>
				<th>用户</th>
				<th>订单号</th>
				<th>金额</th>
				<th>订单状态</th>
				<th>明细</th>
			
			</tr>
			<c:forEach items="${ os}" var="o">
				<tr>
					<td>${o.user.username}
					<td>${o.ordernum}</td>
					<td>¥${o.price }元</td>
					<td>${o.state==0?'未发货':'已发货'}</td>
					<td>
						<a href="${pageContext.request.contextPath}/manageServlet?operation=showOrdersDetail&ordersId=${o.id}">订单详情</a>
					</td>
				</tr>
			</c:forEach>
		</table>
  </body>
</html>

【orderMsg.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/manage/header.jsp" %>
	订单号:${o.ordernum}  </br>金额:¥${o.price }元</br>
	明细如下:</br>
		<table border="1" width="88%" style="text-align:center" align="center">
			<tr>
				<th>书名</th>
				<th>作者</th>
				<th>单价</th>
				<th>小计</th>
				<th>数量</th>
			</tr>
			<c:forEach items="${o.items }" var="i">
				<tr>
					<td>${i.book.name}</td>
					<td>${i.book.author}</td>
					<td>¥${i.book.price}元</td>
					<td>${i.num}</td>
					<td>¥${i.price}元</td>
				</tr>
			</c:forEach>
		</table>
   	收货信息如下:</br>
   		地址:${o.user.address}</br> 		
   		电话:${o.user.cellphone}</br>
   		</hr>
   		<c:if test="${o.state==0 }">
   		<a href="${pageContext.request.contextPath}/manageServlet?operation=sureSend&ordersId=${o.id}">确认发货</a>
 	</c:if>
  </body>
</html>

【welcome.jsp】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
      contentType="text/html;charset=UTF-8"%>
<%@ include file="/manage/header.jsp" %>
	<h1 align="center">欢迎使用</h1>
  </body>
</html>

3. 后台代码

后台代码管理员和客户两种基本角色各自一个Servlet解决:

  • 客户servlet:ClientServlet

public class ClientServlet extends HttpServlet {
	private BusinessService bs = new BusinessServiceImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String operation = request.getParameter("operation");
		if("showIndexCategory".equals(operation)){
			showIndexCategory(request,response);
		}
		if("showCategoryBook".equals(operation)){
			showCategoryBook(request,response);
		}
		if("buyBook".equals(operation)){
			buyBook(request,response);
		}
		if("genOrders".equals(operation)){
			genOrders(request,response);
		}
		if("regist".equals(operation)){
			regist(request,response);
		}
		if("login".equals(operation)){
			login(request,response);
		}
		if("logout".equals(operation)){
			logout(request,response);
		}
		if("showUsersOrders".equals(operation)){
			showUsersOrders(request,response);
		}
		if("showOrdersDetail".equals(operation)){
			showOrdersDetail(request,response);
		}
	}
	private void showOrdersDetail(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//1.判断用户是否登录。1.1没有登录,转向登录页面
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		if(user==null){
			request.setAttribute("message", "请先登录!2秒后将自动转向登录页面。<meta http-equiv='Refresh' content='2;" +
					"URL="+request.getContextPath()+"/client/login.jsp'/>");
			request.getRequestDispatcher("/client/message.jsp").forward(request, response);
			return ;
		}
		String ordersId=request.getParameter("ordersId");
		Orders o = bs.findOrdersById(ordersId);//★★查询的是订单明细,与通过用户id查订单是不同的,明细中还要查出书的信息
		request.setAttribute("o", o);
		request.getRequestDispatcher("/client/ordersMsg.jsp").forward(request, response);
	}
	//依据用户id查询用户订单
	private void showUsersOrders(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//1.判断用户是否登录。1.1没有登录,转向登录页面
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		if(user==null){
			request.setAttribute("message", "请先登录!2秒后将自动转向登录页面。<meta http-equiv='Refresh' content='2;" +
					"URL="+request.getContextPath()+"/client/login.jsp'/>");
			request.getRequestDispatcher("/client/message.jsp").forward(request, response);
			return ;
		}
		List<Orders> os = bs.findOrdersByUserId(user.getId());
		request.getSession().setAttribute("os", os);
		request.getRequestDispatcher("client/listOrders.jsp").forward(request,response);//转向主页
	}
	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		//注意:注销时是直接到根目录下
		request.getRequestDispatcher("/").forward(request, response);
	}
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = bs.login(username,password);
		if(user==null){
			request.setAttribute("message", "用户名或密码错误!");
			request.getRequestDispatcher("/client/message.jsp").forward(request, response);
		}else{
			request.getSession().setAttribute("user", user);
			response.sendRedirect(request.getContextPath());//转向主页
		}
	}
	private void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user = WebUtil.fillBean(request, User.class);
		if(!(user.getPassword()).equals(user.getPassword1())){//这里是比较
			request.setAttribute("message", "两次密码输入不匹配");
			request.getRequestDispatcher("/client/message.jsp").forward(request, response);
		}
		bs.regist(user);
		request.setAttribute("message", "注册成功");
		request.getRequestDispatcher("/client/message.jsp").forward(request, response);
	}
	//生成订单,把订单和订单项的信息存到数据库中
	private void genOrders(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//1.判断用户是否登录。1.1没有登录,转向登录页面
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		if(user==null){
			request.setAttribute("message", "请先登录!2秒后将自动转向登录页面。<meta http-equiv='Refresh' content='2;" +
					"URL="+request.getContextPath()+"/client/login.jsp'/>");
			request.getRequestDispatcher("/client/message.jsp").forward(request, response);
			return ;
		}
		//2.如果已经登录,则将购物车里面的东西按规则生成订单信息
		//取出购物车:Cart Map<String,CartItem> 
		Cart cart  = (Cart)session.getAttribute("cart");//购物车<->订单
		Orders orders = new Orders();
		orders.setNum(cart.getNum());
		orders.setPrice(cart.getPrice());
		//★▲弄购物项
		List<OrdersItem> ordersItems = new ArrayList<OrdersItem>();//订单项<->订单项
		for(Map.Entry<String, CartItem> item:cart.getItems().entrySet()){//★▲▲填充模型
			CartItem i = item.getValue();//得到购物项
			OrdersItem orderItem = new OrdersItem();
			orderItem.setNum(i.getNum());
			orderItem.setPrice(i.getPrice());
			orderItem.setBook(i.getBook());
			ordersItems.add(orderItem);
		}
		orders.setItems(ordersItems);
		bs.addOrders(orders,user);
		//删除购物车
		request.getSession().removeAttribute("cart");
		request.setAttribute("message","订单生成成功!购物车为空");
		request.getRequestDispatcher("/client/message.jsp").forward(request, response);
	}

	private void buyBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//购买书的id
		String bookId = request.getParameter("bookId");
		//获取要购买的书
		Book book = bs.findBookById(bookId);
		HttpSession session = request.getSession();
		//★▲从HttpSession中取出购物车
		Cart cart = (Cart)session.getAttribute("cart");
		//>创建购物车(判断是否有购物车)并放到httpsession中(购物车)
		if(cart==null){
			cart = new Cart();
			session.setAttribute("cart",cart);
		}
		//把书放到购物车中
		cart.addBook(book);
		//提示购买成功
		request.setAttribute("message", "购买成功,2秒后返回主页面。<meta http-equiv='Refresh' content='2;" +
					"URL="+request.getContextPath());
		//页面转发
		request.getRequestDispatcher("/client/message.jsp").forward(request, response);
	}
	//按照分类进行分页书籍查询
	private void showCategoryBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String pagenum = request.getParameter("pagenum");
		String categoryId = request.getParameter("categoryId");//★1.相对于下面那个方法再添加的
		Page page = bs.findPageRecords(pagenum,categoryId);//★2.相对于下面那个方法再添加的
		page.setUrl("/clientServlet?operation=showCategoryBook&categoryId="+categoryId);//★3.相对于下面那个方法再添加的
		request.setAttribute("page", page);
		request.getRequestDispatcher("/client/welcome.jsp").forward(request,response);
	}
	//查询所有分类,封装后,便于前端主页的显示
	private void showIndexCategory(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Category> cs = bs.findAllCategory();
		request.getSession().setAttribute("cs", cs);//★★用session放大范围以保持header.jsp部分的数据维护
		//查询所有书籍,还要分页
		String pagenum = request.getParameter("pagenum");
		Page page = bs.findPageRecords(pagenum);
		page.setUrl("/clientServlet?operation=showIndexCategory");
		request.setAttribute("page", page);
		request.getRequestDispatcher("/client/welcome.jsp").forward(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		this.doGet(request, response);
	}
}
</span>

  • 解决管理员基本功能的servlet:ManageServlet

public class ManageServlet extends HttpServlet {
	private BusinessService  bs = new BusinessServiceImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String operation = request.getParameter("operation");
		if("addCategory".equals(operation))
			addCategory(request,response);
		if("listCategory".equals(operation))
			listCategory(request,response);
		if("showCategoryUI".equals(operation))
			showCategoryUI(request,response);
		if("addBook".equals(operation))
			addBook(request,response);
		if("showAllBook".equals(operation))
			showAllBook(request,response);
		if("showAllOrders0".equals(operation)){
			showAllOrders0(request,response);
		}
		if("showAllOrders1".equals(operation)){
			showAllOrders1(request,response);
		}
		if("showOrdersDetail".equals(operation)){
			showOrdersDetail(request,response);
		}
		if("sureSend".equals(operation)){
			sureSend(request,response);
		}
	}
	private void sureSend(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String ordersId = request.getParameter("ordersId");
		bs.sureOrders(ordersId);
		request.setAttribute("message","成功发货");
		request.getRequestDispatcher("/message.jsp").forward(request, response);
	}
	private void showOrdersDetail(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//哪个用户的也要查询出来
		String ordersId = request.getParameter("ordersId");
		Orders o = bs.findOrdersById(ordersId);
		request.setAttribute("o", o);
		request.getRequestDispatcher("/manage/ordersMsg.jsp").forward(request, response);
	}
	private void showAllOrders1(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Orders> os = bs.findOrdersByState(1);
		request.setAttribute("os", os);
		request.getRequestDispatcher("/manage/showOrders.jsp").forward(request, response);
	}
	//显示所有为发货的订单
	private void showAllOrders0(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Orders> os = bs.findOrdersByState(0);
		request.setAttribute("os", os);
		request.getRequestDispatcher("/manage/showOrders.jsp").forward(request, response);
	}
	//后台查询所有图书分页
	private void showAllBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String pagenum = request.getParameter("pagenum");
		Page page = bs.findPageRecords(pagenum);
		page.setUrl("manageServlet?operation=showAllBook");//第二种分页方式传递到jsp页面的数据
		request.setAttribute("page",page);
		request.getRequestDispatcher("/manage/listBook.jsp").forward(request, response);
	}
	//添加书籍到数据库:jsp页面传过来的是mutipart类型
	private void addBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String resultPath = "";
		String storePath = getServletContext().getRealPath("/files");
		try {
			Book book = new Book();
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = upload.parseRequest(request);//获得待解析数据
			//解析数据
			for(FileItem item:items){
				if(item.isFormField()){
					//封装数据到javabean中
					String filedName = item.getFieldName();//字段名,即javabean的属性名,除了图片
					String filedValue = item.getString(request.getCharacterEncoding());//保证得到的字符串是UTF-8格式
					BeanUtils.setProperty(book,filedName,filedValue);//到这一步,除了图片路径,其它数据都有了
				}else{
					//处理文件上传
					InputStream in = item.getInputStream();
					String fileName = item.getName();//用户上传文件路径名
					//从用户上传的文件路径名中截取文件名。然后在加随机码,以防止用户上传的文件名相同发生冲突
					fileName = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("\\")+1);
					//设置存储的图片文件名
					book.setImage(fileName);
					OutputStream out = new FileOutputStream(storePath+"\\"+fileName);
					byte b[] = new byte[1024];
					int len = -1;
					while((len=in.read(b))!=-1){
						out.write(b,0,len);
					}
					out.close();
					in.close();
					item.delete();//★删除临时文件
				}
			}
			//System.out.println(book);
			bs.addBook(book);//★★先测试,然后看方法对不对,在写service和dao层中写该方法  
			List<Category> cs = bs.findAllCategory();
			request.setAttribute("cs", cs);//如果没有这两句,添加完成后添加页面将不会显示图书分类
			resultPath = "/manage/addBook.jsp";
			request.setAttribute("message","<script type='text/javascript'>alert('添加成功')</script>");
		} catch (Exception e) {
			e.printStackTrace();
			resultPath="/message.jsp";
			//TODO
			request.setAttribute("message", "上传出问题了");
		}
		request.getRequestDispatcher(resultPath).forward(request, response);
	}

	private void showCategoryUI(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Category> cs = bs.findAllCategory();
		request.setAttribute("cs", cs);
		request.getRequestDispatcher("/manage/addBook.jsp").forward(request, response);
	}

	private void listCategory(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Category> cs = bs.findAllCategory();
		request.setAttribute("cs", cs);
		request.getRequestDispatcher("/manage/listCategory.jsp").forward(request, response);	
	}

	private void addCategory(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Category ca = WebUtil.fillBean(request, Category.class);
		bs.addCategory(ca);
		request.setAttribute("message", "<script type='text/javascript'>alert('添加成功')</script>");
		request.getRequestDispatcher("/manage/addCategory.jsp").forward(request, response);		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		this.doGet(request, response);

	}

}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值