我的订单
点击我的订单,跳转页面显示该用户的所有订单,先跳转到一个servlet,判断是否为登陆状态,session域中存在user对象,如未登录重定向到登陆页面,并return不执行下面代码.如已是登陆状态则要去数据库中查询该用户的订单,先查询该用户的所有订单到orders表中查询,经查询到的所有订单List,遍历集合获取所有订单,但是Order对象中有许多数据并没有封装,因为Orders表中没有,就要查询另两个表,进行Order的封装,多表查询查询到的结果不能直接封装到一个实体里所以使用MapListHandler 封装成List<Map<String,Object>>,list中是这一订单中的所有订单项,遍历List集合,把得到的map集合的数据封装到实体类中,用到BeanUtils,封装Product对象,与OrderItem对象把Product封装到OrderItem对象中,并把封装好的OrderItem添加到Order对象的List集合中,把最后封装好的List集合放入request域中,并转发到显示页面,用jstl嵌套循环el取值完成页面的显示
web
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();
List<Order> myOrders=service.findOrders(user.getUid());
for(Order order:myOrders){
List<Map<String,Object>> mapList=service.findOrderItems(order.getOid());
for(Map<String,Object> map:mapList){
Product pro=new Product();
OrderItem item=new OrderItem();
try {
BeanUtils.populate(pro, map);
BeanUtils.populate(item, map);
item.setProduct(pro);
order.getList().add(item);
} catch (Exception e) {
e.printStackTrace();
}
}
}
request.setAttribute("myOrders", myOrders);
request.getRequestDispatcher("/order_list.jsp").forward(request, response);
}
service
public List<Order> findOrders(String uid) {
ProductDao dao=new ProductDao();
List<Order> myOrders=null;
try {
myOrders = dao.findOrders(uid);
} catch (SQLException e) {
e.printStackTrace();
}
return myOrders;
}
public List<Map<String,Object>> findOrderItems(String oid) {
ProductDao dao=new ProductDao();
List<Map<String,Object>> mapList=null;
try {
mapList=dao.findOrderItems(oid);
} catch (SQLException e) {
e.printStackTrace();
}
return mapList;
}
dao
public List<Order> findOrders(String uid) throws SQLException {
QueryRunner runner=new QueryRunner();
String sql="select * from orders where uid=?";
return runner.query(sql, new BeanListHandler<Order>(Order.class), uid);
}
public List<Map<String,Object>> findOrderItems(String oid) throws SQLException {
QueryRunner runner=new QueryRunner();
String sql="select * from orderitem i,product p where i.pid=p.pid and oid=?";
List<Map<String,Object>> mapList=runner.query(sql,new MapListHandler(),oid);
return mapList;
}