使用session完成购物车代码

来源:互联网 发布:java跨域上传文件 编辑:程序博客网 时间:2024/05/14 19:09


裸奔代码之前,为了更好的理解,我们先进行案例分析.

万物皆对象编程

我们需要把购物车当成一个对象,购物车里面通常存在什么?


购物车里面存在者购物项,因为购物项不止一个,所以我们使用集合,那么问题来了,我们是选择list,还是选择map集合?因为购物车经常需要操作数据,所有我们会选择使用map,map的优点就是增删快,相信大家都懂的.map的key我们使用商品id,value使用购物项的对象


2.分析完购物车,我们开始分析购物项


所以我们可以分析出,每一个购物项里存在着商品信息,通常我们使用product 对象储存信息,还存在着商品数量,当前购物项的总金额 


购物车对象的变量

item是购物项

购物车的功能代码,

1.用户点击商品保存到购物车的功能

首先我们需要判断商品id是否在购物车里存在,if(存在){我们只需要增加购物车里面的商品数量} else { //如果不存在我们只需要把用户选择的商品id,和购物项存入集合里就好 },


当我们点击的时候,我们需要拿到商品的pid,和用户选择的数量 .我们可以通过这俩个参数,封装一个购物项. product 使用pid 在数据库里面查 ,count 参数里有,总价我们自己计算

product.getMoney * count;



做完准备工作,我们就可以写代码了.


下面是我servlet 的代码


我的BeanFactory 其实就相当与 new cataService 对象 ,,不用想太复杂    ,,


案例基本实现 我就跟大家分享一些我的BeanFactory

public class BeanFactory {
 
 public static Object getInstance(String id){
  try {
   SAXReader reader = new SAXReader();
   
   //System.out.println(BeanFactory.class.getResource(""));  //类路径
   
   //System.out.println(BeanFactory.class.getClassLoader().getResource("")); //包路径  ,范围更大
   
   System.out.println(BeanFactory.class.getClassLoader().getResource("Bean.xml"));
   URL path = BeanFactory.class.getClassLoader().getResource("Bean.xml");
   //使用解析器 读取
   Document doc = reader.read(path);
   
   //读取文件
   Element ele = (Element)doc.selectSingleNode("//bean[@id='"+id+"']");
   String tagName = ele.attributeValue("class");
   
   //加载文件,获取实例对象
   return Class.forName(tagName).newInstance();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   throw new RuntimeException("BeanFactory 的参数id错误 ");
  }
 }
}


需要配置xml ,和导入jar 包 分别是 xpath ,和 dom4j  有兴趣的可以去下载


<beans>
 <bean id="userService" class="com.itheima.service.userServiceimpl"/>
 <bean id="cateService" class="com.itheima.service.cateServiceImpl"/>
 <bean id="cateDao" class="com.itheima.dao.cateDaoImpl"/>
 <bean id="userDao" class="com.itheima.dao.UserDaoimlp"/>
 <bean id="OrderService" class="com.itheima.service.OrderServiceImpl"/>
 <bean id="OrderDao" class="com.itheima.dao.OrderDaoImpl"/>
</beans>

xml 的id 是类的名称 ,, class 是包名   xml的名字必须是Bean.xml  并且要放在当前当前src下,也就是最上级的包里面   




原创粉丝点击