小项目second-任务二-LMLPHP

任务1:添加商品类别

1)修改catelog/list.jsp上的添加超链接的路径

<a class="button border-main icon-plus-square-o"
href="${pageContext.request.contextPath}/catelog.action?method=toAdd">
添加商品类别</a>

2)在CatelogServlet中加入一个toAdd方法,跳转到添加页面

// 准备添加
	public void toAdd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 转发到catelog/add.jsp
		request.getRequestDispatcher("WEB-INF/jsp/catelog/add.jsp").forward(
				request, response);
	}

3)修改添加页面上表单的请求路径,以及元素的name

<form method="post" class="form-x"
				action="${pageContext.request.contextPath}/catelog.action?method=add">
				<div class="form-group">
					<div class="label">
						<label>类别名称:</label>
					</div>
					<div class="field">
						<input type="text" class="input w80" name="catelog_name"
							data-validate="required:请填写类别名称" />
						<div class="tips"></div>
					</div>
				</div>
    <div class="form-group">
					<div class="label">
						<label>类别描述:</label>
					</div>
					<div class="field">
						<input type="text" class="input w80" name="catelog_miaoshu"
							data-validate="required:请填写类别名称" />
						<div class="tips"></div>
					</div>

4)在CatelogDao中加入添加商品类别方法,实现类代码

@Override
	public int insert(Catelog catelog) {
		// TODO Auto-generated method stub
		String sql = "insert into t_catelog(catelog_name,catelog_miaoshu) values(?,?)";

		int i = JdbcUtil.executeUpdate(sql, catelog.getCatelog_name(),
				catelog.getCatelog_miaoshu());
		return i;
	}

5)在CatelogService中加入添加商品类别方法

@Override
	public boolean addCatelog(Catelog catelog) {
		// TODO Auto-generated method stub
		int i = dao.insert(catelog);
		return i>0;
	}

6)在CatelogServlet中添加add方法处理添加商品类别请求

//处理添加商品请求
	public void add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取表单传来的参数
		String catelog_name=request.getParameter("catelog_name");
		String catelog_miaoshu=request.getParameter("catelog_miaoshu");
		//封装成商品类别对象
		Catelog  catelog=new Catelog();
		catelog.setCatelog_name(catelog_name);
		catelog.setCatelog_miaoshu(catelog_miaoshu);
		//调用service中的方法,完成添加功能
		CatelogService  service=new CatelogServiceImpl();
		boolean flag = service.addCatelog(catelog);
		//跳转到列表页面
		if(flag){
			 response.sendRedirect("catelog.action?method=queryAll");
		}

任务2:分页查询商品

1)修改main/index.jsp上商品管理的超链接路径

<a href="${pageContext.request.contextPath}/goods.action?method=queryByPage"
	target="right"><span class="icon-caret-right"></span>商品管理</a>

2)创建GoodsDao,在里面加入分页查询的两个方法

@Override
	public List<Goods> queryData(PageBean<Goods> pb, String keyword) {
		// TODO Auto-generated method stub
		String sql = "select goods_id,goods_name,goods_pic,goods_miaoshu,"
				+ " catelog_name,market_price,mall_price,stock_num,enter_date  from   t_goods  t1 join  t_catelog t2 on t1.catelog_id=t2.catelog_id";
		if (!keyword.equals("")) {
			sql += " where goods_name like '%" + keyword + "%'";
		}

	sql += " order by goods_id limit  ?,?";		// 手动处理结果集
		Connection conn = JdbcUtil.getConnection();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		// 返回值
		List<Goods> list = new ArrayList<Goods>();
		try {
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, (pb.getCurrentPage() - 1) * pb.getPageSize());
			stmt.setInt(2, pb.getPageSize());
			rs = stmt.executeQuery();
			while (rs.next()) {
				// 创建Goods对象
				Goods goods = new Goods();
				goods.setGoods_id(rs.getInt(1));
				goods.setGoods_name(rs.getString(2));
				goods.setGoods_pic(rs.getString(3));
				goods.setGoods_miaoshu(rs.getString(4));
				// 创建Catelog对象
				Catelog catelog = new Catelog();
				catelog.setCatelog_name(rs.getString("catelog_name"));
				// 建立商品和Catelog对象之间关系
				goods.setCatelog(catelog);
				goods.setMarket_price(rs.getInt("market_price"));
				goods.setMall_price(rs.getInt("mall_price"));
				goods.setStock_num(rs.getInt("stock_num"));
				goods.setEnter_date(rs.getDate("enter_date"));
				// 添加到集合中
				list.add(goods);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JdbcUtil.closeAll(rs, stmt, conn);
		}
		return list;
	}
@Override
	public int queryCount(String keyword) {
		// TODO Auto-generated method stub
		String sql="select count(*) from    t_goods  t1 join  t_catelog t2 on t1.catelog_id=t2.catelog_id";
		if (!keyword.equals("")) {
			sql += " where goods_name like '%" + keyword + "%'";
		}
		int total = this.getTotal(sql);
		return total;
	}

3)创建GoodService,加入模糊查询结合分页查询的方法getPageBean

@Override
	public void getPageBean(PageBean<Goods> pb, String keyword) {
		// TODO Auto-generated method stub
         List<Goods> list = goodsDao.queryData(pb, keyword);
         int totalCount = goodsDao.queryCount(keyword);
         pb.setData(list);
         pb.setTotalCount(totalCount);
	}

4)在GoodsServlet中加入处理分页查询商品的方法

// 商品分页查询
	public void queryByPage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 获取请求的页号,即要查询第几页数据,假设请求参数名currentPage
		String pageStr = request.getParameter("currentPage");
		// 保存请求的页号
		int currentPage = 1;
		if (pageStr != null) {
			currentPage = Integer.parseInt(pageStr);
		}
		// 每页条数
		int pageSize = 5;
		// 获取名称关键字
		String keyword = request.getParameter("keyword");
		if (keyword == null) {
			keyword = "";
		}
		// 封装一个pageBean对象,它只有2个数据currentPage和pageSize
		PageBean<Goods> pb = new PageBean<>();
		pb.setCurrentPage(currentPage);
		pb.setPageSize(pageSize);
		// 调用Service的方法,传入PageBean对象
		GoodsService service = new GoodsServiceImpl();
		service.getPageBean(pb, keyword);
		// 把pageBean存到request域中
		request.setAttribute("pb", pb);
		// 把关键字存到request域中
		request.setAttribute("keyword", keyword);
		// 转发到商品列表页面
		request.getRequestDispatcher("WEB-INF/jsp/goods/list.jsp").forward(
				request, response);
	}

5)修改goods/list.jsp,将商品名关键字及搜索超链接包裹在一个表单中

<form
						action="${pageContext.request.contextPath}/goods.action?method=queryByPage"  id="searchForm"
						method="post">
						<!-- 隐藏域保存页号 -->
						 <input type="hidden"  name="currentPage" id="currentPage"  value="1">
						请输入商品名称关键字:<input type="text" name="keyword" id="keyword"
							class="input"
							style="width:200px; line-height:17px;display:inline-block" value="${keyword }" /> <a
							href="javascript:void(0)" class="button border-main icon-search"
							onclick="changePageNum(1)"> 搜索</a>
					</form>
定义函数changePageNum()
//点击“分页”超链接后,跳转到指定的页面
	function changePageNum(pageNum) {
		//给保存页号的隐藏域赋值
		$("#currentPage").val(pageNum);
		//提交表单
		$("#searchForm").submit();
	}

任务3:添加商品

1)修改商品列表上”添加商品”超链接的路径

<a class="button border-main icon-plus-square-o"
href="${pageContext.request.contextPath}/goods.action?method=toAdd">
						添加商品</a>

2)在GoodsServlet中添加方法toAdd,转发到商品添加页面

//准备添加
	public void toAdd(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
			IOException {
		//获取所有的商品分类
		 CatelogService  service=new CatelogServiceImpl();
		 List<Catelog> allCatelogs = service.getAllCatelogs();
        //存到request域中
		 request.setAttribute("catelogs", allCatelogs);
		// 转发到商品添加页面
		request.getRequestDispatcher("WEB-
		INF/jsp/goods/add.jsp").forward(
				request, response);
	}

3)修改goods/add.jsp页面,把表单补全

<form method="post" class="form-x"
			enctype="multipart/form-data"	action="${pageContext.request.contextPath}/goods.action?method=add">
				<div class="form-group">
					<div class="label">
						<label>商品名称:</label>
					</div>
					<div class="field">
						<input type="text" class="input w80" name="goods_name"
							data-validate="required:请填写商品名称" />
						<div class="tips"></div>
					</div>
				</div>...
重点部分:表单里的下拉框中要回显所有商品分类
<select name="catelog_id">
							<c:forEach var="ct" items="${catelogs }">
								<option value="${ct.catelog_id }">${ct.catelog_name }</option>
							</c:forEach>
						</select>

补充:文件上传技术
1)文件上传表单必须加上 enctype=“multipart/form-data”,如果没有该属性则无法提交文件的二进制数据

  <form action="sf.action"  enctype="multipart/form-data" method="post">
       选择文件:<input type="file" name="myimg"  ><br>
    <input type="submit" value="上传" >
     </form>

2)创建UploadServlet处理文件上传请求,需要添加支持文件上传的注解

//@MultipartConfig:servlet3.0支持文件上传的注解
@MultipartConfig
public class UploadServlet extends HttpServlet {
  	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 文件上传:将本地的文件保存在服务器上面去,本质是IO流操作
		// 1.获取服务器端保存上传文件的upload目录的绝对路径
		String savePath = this.getServletContext().getRealPath("/upload");
		System.out.println(savePath);
		// 2.获取表单中传过来的文件域参数,
		// getPart("表单元素的name"):获取文件域元素
		// getParameter("元素的name"):获取普通元素的值
		// getParts():获取所有元素(普通元素+文件域)
		Part myimg = request.getPart("myimg");

		System.out.println(myimg);
		/*
		 * Collection<Part> parts = request.getParts(); for (Part part : parts)
		 * {
		 *
		 * System.out.println("表单元素的名称:"+part.getName()); }
		 */
		// 3.从Part对象中去解析文件名
		// 文件上传的表单提交后,会将表单参数封装在Request Payload中,每个元素都有一个头Content-Disposition
		// 使用part的getHeader("Content-Disposition")获取它的值,格式:
		// form-data; name="myimg"; filename="1457614349430.jpg"

		String header = myimg.getHeader("Content-Disposition");
		//获取文件原始名称
		String oldName = this.getOldName(header);
         //4.调用Part对象的write方法将文件写入到服务器的savePath目录下,参数是文件的绝对路径
		myimg.write(savePath+"/"+oldName);
		System.out.println("上传成功");
	}
	// 从Content-Disposition头的值中提取出文件的原始名称
	public String getOldName(String header) {
		String[] strs = header.split(";");
		String filename = strs[2];
		filename = filename.substring(filename.indexOf("\"") + 1,
				filename.length() - 1);
		return filename;
	}
}

接着完成添加商品的后台Servlet–>Dao处理
4 )在GoodsDao中加入insert方法

	@Override
	public int insert(Goods goods) {
		String sql = "insert into t_goods(goods_name,goods_miaoshu,goods_pic,market_price,mall_price,catelog_id,stock_num,goods_address,enter_date) values(?,?,?,?,?,?,?,?,?)";
		Object[] params = { goods.getGoods_name(), goods.getGoods_miaoshu(),
				goods.getGoods_pic(), goods.getMarket_price(),
				goods.getMall_price(), goods.getCatelog().getCatelog_id(),
				goods.getStock_num(), goods.getGoods_address(),
				goods.getEnter_date() };
		int i=JdbcUtil.executeUpdate(sql, params);
		return i;
	}

5)在GoodsService中加入添加商品方法

@Override
	public boolean addGoods(Goods goods) {
		// TODO Auto-generated method stub
		int i = goodsDao.insert(goods);
		return i>0;
	}

6)在GoodsServlet中加入处理添加商品的请求方法add

// 添加商品
		public void add(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			// 1.获取表单中的参数
			// 1.1.获取普通表单参数(除文件域以外的)
			String goods_name = request.getParameter("goods_name");
			String goods_miaoshu = request.getParameter("goods_miaoshu");
			int market_price = Integer.parseInt(request
					.getParameter("market_price"));
			int mall_price = Integer.parseInt(request.getParameter("mall_price"));
			int catelog_id = Integer.parseInt(request.getParameter("catelog_id"));
			int stock_num = Integer.parseInt(request.getParameter("stock_num"));
			String goods_address = request.getParameter("goods_address");
			String enter_dateStr = request.getParameter("enter_date");
			// 把上面的日期字符串转换为Date类型
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");
			Date enter_date = null;
			try {
				enter_date = sdf.parse(enter_dateStr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// 1.2.获取文件域,做上传处理
			Part part = request.getPart("goods_pic");
			String header = part.getHeader("Content-Disposition");
			// 获取文件原始名称
			String oldName = this.getOldName(header);
			// 基于原始名称来得到新文件名,第1种:用当前时间戳来生成文件名(yyyyMMddHHmmssSSS)
			// 第2种用U:UID来生成文件名
			// 根据原始文件名得到新文件名
			String newName = this.getNewName(oldName);

			// 获取服务器端保存上传文件的upload目录的绝对路径
			String savePath = this.getServletContext().getRealPath("/upload");
			// 调用Part对象的write方法将文件写入到服务器的savePath目录下,参数是文件的绝对路径
			part.write(savePath + "/" + newName);
			// 2.封装一个商品对象

			Goods goods = new Goods();
			goods.setGoods_name(goods_name);
			goods.setGoods_miaoshu(goods_miaoshu);
			goods.setMall_price(mall_price);
			goods.setMarket_price(market_price);

			Catelog catelog = new Catelog();
			catelog.setCatelog_id(catelog_id);
			goods.setCatelog(catelog);

			goods.setStock_num(stock_num);
			goods.setGoods_address(goods_address);
			goods.setEnter_date(enter_date);
			// 封装图片路径
			goods.setGoods_pic("upload/" + newName);

			// 3.调用Service的方法,传入商品对象
			GoodsService service = new GoodsServiceImpl();
			boolean flag = service.addGoods(goods);
			// 4.跳转到商品列表页面
			if (flag) {
				response.sendRedirect("goods.action?method=queryByPage");
			}

		}

任务4:修改商品

1)将列表页面上”修改”超链接改过来

<a class="button border-main"
href="${pageContext.request.contextPath}/goods.action?
method=toUpdate&goodsId=${gd.goods_id }"><span
			class="icon-edit"></span> 修改</a>

2)在GoodsDao中加入查询商品对象的方法queryById()

public Goods queryById(int goods_id) {
		// 查询商品编号,名称,市场价,商城价,分类编号
		String sql = "select goods_id,goods_name,market_price,mall_price,catelog_id  from t_goods where goods_id=?";
		// 手动处理结果集
		Connection conn = JdbcUtil.getConnection();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		// 返回值
		Goods goods = null;
		try {
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, goods_id);
			rs = stmt.executeQuery();
			if (rs.next()) {
				goods = new Goods();
				goods.setGoods_id(rs.getInt(1));
				goods.setGoods_name(rs.getString(2));
				goods.setMarket_price(rs.getInt(3));
				goods.setMall_price(rs.getInt(4));
				Catelog catelog = new Catelog();
				catelog.setCatelog_id(rs.getInt("catelog_id"));
				goods.setCatelog(catelog);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JdbcUtil.closeAll(rs, stmt, conn);
		}
		return goods;
	}

3)在GoodsService中加入获取商品对象的方法

@Override
	public Goods getGoodsById(int goods_id) {
		// TODO Auto-generated method stub
		 Goods goods = goodsDao.queryById(goods_id);
		return goods;
	}

4)在GoodsServlet中加入准备修改的方法toUpdate

// 准备修改
	public void toUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取商品编号
		int goodsId=Integer.parseInt(request.getParameter("goodsId"));
		//获取商品的信息,返回一个商品对象
		GoodsService  goodsService=new GoodsServiceImpl();
		Goods goods = goodsService.getGoodsById(goodsId);
		// 获取所有的商品分类
		CatelogService service = new CatelogServiceImpl();
		List<Catelog> allCatelogs = service.getAllCatelogs();
		//将商品对象,商品分类集合都存到request域中
		request.setAttribute("gd", goods);
		request.setAttribute("catelogs", allCatelogs);
		//跳转到update.jsp页面去回显数据
		request.getRequestDispatcher("WEB-INF/jsp/goods/update.jsp").forward(
				request, response);
	}

5)在update.jsp页面上回显商品数据
6)把update.jsp页面上表单的路径改一下

<form method="post" class="form-x"
action="${pageContext.request.contextPath}/goods.action?method=update">

7)GoodsDao中加入修改商品方法

@Override
	public int update(Goods goods) {
		// TODO Auto-generated method stub
		String sql="update t_goods set goods_name=?,market_price=?,mall_price=?,catelog_id=? where goods_id=?";
		int i=JdbcUtil.executeUpdate(sql, goods.getGoods_name(),goods.getMarket_price(),goods.getMall_price(),goods.getCatelog().getCatelog_id(),goods.getGoods_id());
		return i;
	}
	@Override
	public boolean updateGoods(Goods goods) {
		// TODO Auto-generated method stub
		int i = goodsDao.update(goods);
		return i>0;
	}

8)GoodsService中加入修改商品方法

@Override
	public boolean updateGoods(Goods goods) {
		// TODO Auto-generated method stub
		int i = goodsDao.update(goods);
		return i>0;
	}

9)在GoodsServlet中加入修改商品的方法

// 修改商品
	public void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
         //获取表单中的参数
		int goods_id=Integer.parseInt(request.getParameter("goodsId"));
		String goodsName=request.getParameter("goodsName");
		int market_price=Integer.parseInt(request.getParameter("market_price"));
		int mall_price=Integer.parseInt(request.getParameter("mall_price"));
		int catelog_id=Integer.parseInt(request.getParameter("catelog_id"));
		  //封装一个商品对象
		Goods  gd=new Goods();
		gd.setGoods_id(goods_id);
		gd.setGoods_name(goodsName);
		gd.setMarket_price(market_price);
		gd.setMall_price(mall_price);
		Catelog  catelog=new Catelog();
		catelog.setCatelog_id(catelog_id);
		gd.setCatelog(catelog);
		 //调用service的修改商品方法
		GoodsService service=new GoodsServiceImpl();
		boolean flag = service.updateGoods(gd);
		//跳转到列表页面
		if (flag) {
			response.sendRedirect("goods.action?method=queryByPage");
		}
	}

任务5:分页显示订单

1)修改main/index.jsp上的”订单管理”超链接

<a href="${pageContext.request.contextPath}/order.action?
method=queryByPage"
target="right"><span class="icon-caret-right"></span>订单管理</a>

2)创建OrderDao,添加针对分页查询的两个方法

public class OrderDaoImpl extends BaseDao<Order> implements OrderDao {

	@Override
	public List<Order> queryData(PageBean<Order> pb) {
		String sql="select order_id,order_jine,order_time,order_address,order_zhuangtai  from t_order  limit ?,?";

	List<Order> list = this.getList(Order.class, sql, (pb.getCurrentPage()-1)*pb.getPageSize(),pb.getPageSize());
		return list;
	}

	@Override
	public int queryCount() {
		// TODO Auto-generated method stub
		String sql="select count(*) from  t_order";
		int total = this.getTotal(sql);
		return total;
	}
}

3)创建OrderService,添加getPageBean方法

	@Override
	public void getPageBean(PageBean<Order> pb) {
		// TODO Auto-generated method stub
		List<Order> list = dao.queryData(pb);
		int totalCount = dao.queryCount();
		// 封装PageBean对象的另2个属性
		pb.setData(list);
		pb.setTotalCount(totalCount);
	}

4)创建OrderServlet,加入处理分页查询的方法

// 分页查询订单
	public void queryByPage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 获取请求的页号,即要查询第几页数据,假设请求参数名currentPage
		String pageStr = request.getParameter("currentPage");
		// 保存请求的页号
		int currentPage = 1;
		if (pageStr != null) {
			currentPage = Integer.parseInt(pageStr);
		}
		// 每页条数
		int pageSize = 5;
		//封装PageBean
		PageBean<Order>  pb=new PageBean<>();
		pb.setCurrentPage(currentPage);
		pb.setPageSize(pageSize);
		//调用service的分页查询方法,传入pageBean
		OrderService service=new OrderServiceImpl();
		service.getPageBean(pb);
		//将pageBean对象存到request域中
		 request.setAttribute("pb", pb);
		//转发到订单列表页面order/list.jsp
		 request.getRequestDispatcher("WEB-INF/jsp/order/list.jsp").forward(request, response);
	}

5)在order/list.jsp页面上显示数据,代码略

任务6:在订单页面上动态显示”发货”和”完成”超链接

 <!-- 如果当前订单状态是待发货,就显示“发货”超链接,状态是已收货时,显示"完成"超链接 -->
					  <c:choose>
					    <c:when test="${order.order_zhuangtai eq  0}">
					      	<a class="button border-main" href="#"><span
							class="icon-edit"></span>发货</a>
					    </c:when>
					     <c:when test="${order.order_zhuangtai eq  2}">
					      	<a class="button border-main" href="#"><span
							class="icon-edit"></span>完成</a>
					      </c:when>
					  </c:choose>

任务7:修改订单的状态

1)把”发货”和”完成”超链接的请求路径改过来

<c:when test="${order.order_zhuangtai eq  0}">
								<a class="button border-main"
									href="${pageContext.request.contextPath}/order.action?method=updateState&orderid=${order.order_id }&state=1"><span
									class="icon-edit"></span>发货</a>
							</c:when>
							<c:when test="${order.order_zhuangtai eq  2}">
								<a class="button border-main" href="${pageContext.request.contextPath}/order.action?method=updateState&orderid=${order.order_id }&state=3">
								<span
									class="icon-edit"></span>完成</a>
							</c:when>

2)在OrderDao中加入一个方法updateState

@Override
	public int updateState(Order order) {
		// TODO Auto-generated method stub
		String sql="update t_order set order_zhuangtai=? where order_id=?";
		int i=JdbcUtil.executeUpdate(sql, order.getOrder_zhuangtai(),order.getOrder_id());
		return i;
	}

3)OrderService中加一个修改状态方法updateOrderState

@Override
	public boolean updateOrderState(Order order) {
		// TODO Auto-generated method stub


		return dao.updateState(order)>0;
	}

4)OrderServlet中加入处理处理状态的方法

//修改订单的状态
	public void updateState(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//获取订单编号
		String orderid=request.getParameter("orderid");
		//获取订单修改后的状态
		int state=Integer.parseInt(request.getParameter("state"));
		//封装Order对象
		Order  order=new Order();
		order.setOrder_id(orderid);
		order.setOrder_zhuangtai(state);
		//调用service的修改订单状态方法,将编号,状态传进去
		OrderService  service=new OrderServiceImpl();
		boolean flag = service.updateOrderState(order);
	   //跳转到订单列表页面
		if(flag){
			response.sendRedirect("order.action?method=queryByPage");
		}
	}
02-28 06:51