day05 --我的订单 自动登录 用户注销

一、我的订单

header.jsp(判断是否已经登录,session中是否已经存在用户)

    <div class="col-md-3" style="padding-top:20px">
		<ol class="list-inline">
			<c:if test="${empty user }">
				<li><a href="login.jsp">登录</a></li>
				<li><a href="register.jsp">注册</a></li>
			</c:if>
			<c:if test="${!empty user }">
				<li style="color:red">欢迎您,${user.username }</li>
				<li><a href="${pageContext.request.contextPath }/user?method=logout">退出</a></li>
			</c:if>
			
			<li><a href="cart.jsp">购物车</a></li>
			<li><a href="${pageContext.request.contextPath }/product?method=myOrders">我的订单</a></li>
		</ol>
	</div>

cart.jsp

	<div style="text-align:right;margin-top:10px;margin-bottom:10px;">
		<a href="javascript:void(0)" onlick="clearCart();" id="clear" class="clear">清空购物车</a>
		<a href="${pageContext.request.contextPath }/product?method=submitOrder">
			<input type="button" width="100" value="提交订单" name="submit" border="0" style="background: url('./images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
				height:35px;width:100px;color:white;">
		</a>
	</div>

ProductServlet

public class ProductServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		//获得请求的方法
		String methodName = request.getParameter("method");
		if("productList".equals(methodName)){
			productList(request,response);
		}else if("categoryList".equals(methodName)){
			categoryList(request,response);
		}else if("index".equals(methodName)){
			index(request,response);
		}else if("productInfo".equals(methodName)){
			productInfo(request,response);
		}else if("addProductToCart".equals(methodName)){
			addProductToCart(request,response);
		}else if("delProFromCart".equals(methodName)){
			delProFromCart(request,response);
		}else if("submitOrder".equals(methodName)){
			submitOrder(request,response);
		}else if("confirmOrder".equals(methodName)){
			confirmOrder(request,response);
		}else if("myOrders".equals(methodName)){
			myOrders(request,response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	} 

	//获得我的订单
	public void myOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		//判断用户是否登录
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if(user == null){
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return;
		}
		
		ProductService service = new ProductService();
		//查询该用户的所有的订单信息(单表查询orders)
		//集合中的每个Order对象的数据是不完整的,缺少List<OrderItem> orderItems数据
		List<Order> orderList = service.findAllOrders(user.getUid());
		//循环所有的订单,为每个订单填充订单项集合信息
		if(orderList != null){
			for(Order order : orderList){
				//获得每一个订单的oid
				String oid = order.getOid();
				//查询该订单的所有的订单项 --mapList封装的是多个订单项和该订单项中商品的信息
				List<Map<String,Object>> mapList = service.findAllOrderItemByOid(oid);
				//将mapList转换成List<OrderItem> orderItems
				for(Map<String,Object> map:mapList){
					
					try {
						//从map中取出count,subtotal封装到OrderItem中
						OrderItem item = new OrderItem();
						BeanUtils.populate(item, map);
						//从map中取出pimage,pname,shop_price封装到Product
						Product product = new Product();
						BeanUtils.populate(product, map);
						
						//将product封装到OrderItem中
						item.setProduct(product);
						
						//将orderitem封装到Order中的orderitems中
						order.getOrderItems().add(item);
;					} catch (IllegalAccessException | InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
				}
			}
		}
		
		//orderList封装完整
		request.setAttribute("orderList", orderList);
		
		request.getRequestDispatcher("order_list.jsp").forward(request, response);
		
	}
}

ProductService

public class ProductService {

	//获得指定用户的订单集合
	public List<Order> findAllOrders(String uid) {
		ProductDao dao = new ProductDao();
		List<Order> orderList = null;
		try {
			orderList = dao.findAllOrders(uid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return orderList;
	}

	//查询该订单下的订单项集合
	public List<Map<String, Object>> findAllOrderItemByOid(String oid) {
		ProductDao dao = new ProductDao();
		List<Map<String, Object>> orderItemList = null;
		try {
			orderItemList = dao.findAllOrderItemByOid(oid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return orderItemList;
	}
}

ProductDao

public class ProductDao {

	//查询指定用户的所有订单
	public List<Order> findAllOrders(String uid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from orders where uid=?";
		return runner.query(sql, new BeanListHandler<Order>(Order.class),uid);
	}

	//查询该订单下的订单项集合
	public List<Map<String,Object>> findAllOrderItemByOid(String oid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select i.count,i.subtotal,p.pimage,p.pname,p.shop_price from orderitem i,product p where i.pid=p.pid and i.oid=?";
		List<Map<String, Object>> mapList = runner.query(sql, new MapListHandler(),oid);
		return mapList;
	}
 
}

Order

public class Order {

	private String oid;//订单的订单号
	private Date ordertime;//下单时间
	private double total;//该订单总金额
	private int state;//订单状态 1代表已付款,0代表未付款
	private String addr;//收货地址
	private String name;//收货人
	private String telephone;//收货人电话 
	private User user;//该订单属于哪个用户
	
	//该订单中有多少订单项
	List<OrderItem> orderItems =  new ArrayList();

	public String getOid() {
		return oid;
	}

	public void setOid(String oid) {
		this.oid = oid;
	}

	public Date getOrdertime() {
		return ordertime;
	}

	public void setOrdertime(Date ordertime) {
		this.ordertime = ordertime;
	}

	public double getTotal() {
		return total;
	}

	public void setTotal(double total) {
		this.total = total;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public String getAddr() {
		return addr;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<OrderItem> getOrderItems() {
		return orderItems;
	}

	public void setOrderItems(List<OrderItem> orderItems) {
		this.orderItems = orderItems;
	}

	@Override
	public String toString() {
		return "Order [oid=" + oid + ", ordertime=" + ordertime + ", total=" + total + ", state=" + state + ", addr="
				+ addr + ", name=" + name + ", telephone=" + telephone + ", user=" + user + ", orderItems=" + orderItems
				+ "]";
	}
	
}

OrderItem

public class OrderItem {

	private String itemid;//订单项id
	private int count;//订单内商品的购买数量
	private double subtotal;//订单项小计
	private Product product;//订单项内部的商品
	private Order order;//该订单项属于哪个订单
	public String getItemid() {
		return itemid;
	}
	public void setItemid(String itemid) {
		this.itemid = itemid;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public double getSubtotal() {
		return subtotal;
	}
	public void setSubtotal(double subtotal) {
		this.subtotal = subtotal;
	}
	public Product getProduct() {
		return product;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	public Order getOrder() {
		return order;
	}
	public void setOrder(Order order) {
		this.order = order;
	}
	@Override
	public String toString() {
		return "OrderItem [itemid=" + itemid + ", count=" + count + ", subtotal=" + subtotal + ", product=" + product
				+ ", order=" + order + "]";
	}
	
}

order_list.jsp

<strong>我的订单</strong>
<table class="table table-bordered">
	<c:forEach items="${orderList}" var="order">
		<tbody>
		  <tr class="success">
			<th colspan="5">订单编号:${order.oid }</th>
		  </tr>
		  <tr class="warning">
			  <th>图片</th>
			  <th>商品</th>
			  <th>价格</th>
			  <th>数量</th>
			  <th>小计</th>
		  </tr>
		  <c:forEach items="${order.orderItems }" var="orderItem">
			<tr class="active">
			  <td width="60" width="40%"><input type="hidden" name="id" value="22"> 
				<img src="${pageContext.request.contextPath }/${orderItem.product.pimage}" width="70" height="60">
			  </td>
			  <td width="30%">
				<a target="_blank">${orderItem.product.pname }</a>
			  </td>
			  <td width="20%">${orderItem.product.shop_price }</td>
			  <td width="10%">${orderItem.count }</td>
			  <td width="15%"><span class="subtotal">${orderItem.subtotal}</span></td>
			</tr>
  </c:forEach> </tbody> </c:forEach> </table>

 

二、自动登录 注销

public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		String methodName = request.getParameter("method");
		if("login".equals(methodName)){
			login(request,response);
		}else if("logout".equals(methodName)){
			logout(request,response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		login(request, response);
	}

	//用户注销
	public void logout(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		
		//将存储在客户端的cookie删除(有自动登录功能时)
		Cookie cookie_username = new Cookie("cookie_username","");
		cookie_username.setMaxAge(0);
		
		Cookie cookie_password = new Cookie("cookie_password","");
		cookie_password.setMaxAge(0);
		
		response.addCookie(cookie_username);
		response.addCookie(cookie_password);
		
		response.sendRedirect(request.getContextPath()+"/login.jsp");
	}
	
	
	//用户登录
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		UserService service = new UserService();
		User user = null;
		try {
			user = service.login(username,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		//判断用户是否成功登录
		if(user!=null){
			//登录成功
			//判断用户是否勾选了自动登录
			String autoLogin = request.getParameter("autoLogin");
			if("true".equals(autoLogin)){
				//要自动登录
				//创建存储用户名的cookie
				Cookie cookie_username = new Cookie("cookie_username",user.getUsername());
				cookie_username.setMaxAge(10*60);
				//创建存储密码的cookie
				Cookie cookie_password = new Cookie("cookie_password",user.getPassword());
				cookie_password.setMaxAge(10*60);
			}
			
			//将user对象存到session中
			session.setAttribute("user", user);
			
			//重定向到首页
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		}else{
			request.setAttribute("loginError", "用户名或密码错误");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}
}

  

 

  

  

  

  

  

  

posted @ 2018-10-25 16:10  一日看尽长安花cxjj  阅读(277)  评论(0)    收藏  举报