常规一个商品一个订单
多个商品一个订单订单只有提交才能结算
付款页面
代码实现,主要是Servlet代码和Service业务层的代码,此处业务层,对多个dao的操作更为明显,体现业务二字!!!
package com.cart.web;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cart.entity.Order;
import com.cart.entity.Userinfo;
import com.cart.service.OrderService;
public class OrderServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//1.业务,将购物车中的数据删除,同时增加数据进订单表和订单详情表;
String[]bids=req.getParameterValues("bid");
StringBuilder sbbid=new StringBuilder();
for(String bid:bids){
sbbid.append(bid+",");
}
String sbid=sbbid.substring(0,sbbid.length()-1);
//已经获取了你复选框的订单,到商品id数组中,此处是bids(大家可以是pids/gids等)
OrderService orderService=new OrderService();
Order order=new Order();
Userinfo user=(Userinfo)req.getSession().getAttribute("userinfo");
order.setUserid(user.getId());
order.setContactphone(user.getPhone());
order.setCreatetime(new Date());
order.setTotal(Double.parseDouble(req.getParameter("total")));
order.setShipaddress(user.getAddress());
order.setStatus("未发货");
//orderService.insertOrder(order); //保存订单;
//让service继续去执行保存订单的操作;
orderService.delCartAndSaveOrder(sbid,user,order);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
package com.cart.service;
import java.sql.*;
import com.cart.dao.*;
import com.cart.dao.impl.*;
import com.cart.entity.Order;
import com.cart.entity.Userinfo;
import com.cart.util.DaoFactory;
public class OrderService {
//1.定义属性:对dao进行操作;
OrderDao orderDao=new OrderDaoImpl();
CartDao cartDao=new CartDaoImpl();
//2.对订单,进行增删该查
public void delCartAndSaveOrder(String sbid,Userinfo user,Order order){
//使用事务操作,业务层可以这样操作,对不同的dao操作;
Connection con=null;
PreparedStatement pstmt=null;
try{
StringBuilder sbSql=new StringBuilder();
sbSql.append("delete from cartitem where uid=? and bid in(");
sbSql.append(sbid);
sbSql.append(")");
String sql=sbSql.toString();
con=DaoFactory.getConnection();
pstmt=con.prepareStatement(sql);
con.setAutoCommit(false);//设置自动提交事务,为false
orderDao.insertOrder(order);//调用插入订单方法;,同时删除原来的购物车数据方法;
Object[] params={user.getId()};
DaoFactory.setParams(pstmt, params);
DaoFactory.executeUpdate(sql, params);
//System.out.println(sbSql);
con.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
DaoFactory.closeAll(null, null, con);
}
}
public int insertOrder(Order order){
//ct.deletecartItem(uid, bid);
return orderDao.insertOrder(order);
}
public int updateOrder(int id){
return orderDao.updateOrder(id);
}
public int deleteOrder(int id){
return orderDao.deleteOrder(id);
}
public Order findOrderById(int id){
return orderDao.findOrderById(id);
}
}