当前位置:文档之家› 应用Servlet实现购物车

应用Servlet实现购物车

应用Servlet实现购物车具体实现过程1、创建封装商品信息的值JavaBean---------GoodsSingle package com.yxq.valuebean;public class GoodsSingle {private String name; //保存商品名称private float price; //保存商品价格private int num; //保存商品购买数量public String getName() {return name;}public void setName(String name) { = name;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}}2、创建工具JavaBean-------- MyTools 实现字符型数据转换为整型及乱码处理package com.yxq.toolbean;import java.io.UnsupportedEncodingException;public class MyTools {public static int strToint(String str){ //将String型数据转换为int型数据的方法if(str==null||str.equals(""))str="0";int i=0;try{i=Integer.parseInt(str); //把str 转换成int 类型的变量}catch(NumberFormatException e){ // try-catch就是监视try中的语句,如果抛出catch中声明的异常类型i=0;e.printStackTrace(); //把Exception 的详细信息打印出来}return i;}public static String toChinese(String str){ //进行转码操作的方法if(str==null)str="";try {str=new String(str.getBytes("ISO-8859-1"),"gb2312");} catch (UnsupportedEncodingException e) {str="";e.printStackTrace();}return str;}}3、创建购物车JavaBean------ ShopCar实现添加、删除,购物车制作package com.yxq.toolbean;package com.yxq.toolbean;import java.util.ArrayList;import com.yxq.valuebean.GoodsSingle;public class ShopCar {private ArrayList buylist=new ArrayList();//用来存储购买的商品public void setBuylist(ArrayList buylist) {this.buylist = buylist;}/*** @功能向购物车中添加商品* @参数single为GoodsSingle类对象,封装了要添加的商品信息*/public void addItem(GoodsSingle single){if(single!=null){if(buylist.size()==0){//如果buylist中不存在任何商品GoodsSingle temp=new GoodsSingle();temp.setName(single.getName());temp.setPrice(single.getPrice());temp.setNum(single.getNum());buylist.add(temp); //存储商品}else{//如果buylist中存在商品int i=0;for(;i<buylist.size();i++){//遍历buylist集合对象,判断该集合中是否已经存在当前要添加的商品GoodsSingle temp=(GoodsSingle)buylist.get(i);//获取buylist集合中当前元素if(temp.getName().equals(single.getName())){ //判断从buylist集合中获取的当前商品的名称是否与要添加的商品的名称相同//如果相同,说明已经购买了该商品,只需要将商品的购买数量加1temp.setNum(temp.getNum()+1);//将商品购买数量加1break;//结束for循环}}if(i>=buylist.size()){//说明buylist中不存在要添加的商品GoodsSingle temp=new GoodsSingle();temp.setName(single.getName());temp.setPrice(single.getPrice());temp.setNum(single.getNum());buylist.add(temp);//存储商品}}}}/*** @功能从购物车中移除指定名称的商品* @参数name表示商品名称public void removeItem(String name){for(int i=0;i<buylist.size();i++){ //遍历buylist集合,查找指定名称的商品GoodsSingle temp=(GoodsSingle)buylist.get(i);//获取集合中当前位置的商品if(temp.getName().equals(name)){ //如果商品的名称为name参数指定的名称if(temp.getNum()>1){ //如果商品的购买数量大于1temp.setNum(temp.getNum()-1); //则将购买数量减1break; //结束for循环}else if(temp.getNum()==1){ //如果商品的购买数量为1buylist.remove(i); //从buylist集合对象中移除该商品}}}}4、创建实例首页面index.jsp,初始化商品信息<%@ page contentType="text/html;charset=gb2312"%><jsp:forward page="/index"/>5、创建处理用户访问首页面请求的Servlet---IndexServletpackage com.yxq.servlet;import java.io.IOException;import java.util.ArrayList;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import com.yxq.valuebean.GoodsSingle;public class IndexServlet extends HttpServlet {private static ArrayList goodslist=new ArrayList();protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request,response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session=request.getSession();session.setAttribute("goodslist",goodslist);response.sendRedirect("show.jsp");}static{ //静态代码块String[] names={"苹果","香蕉","梨","橘子"};float[] prices={2.8f,3.1f,2.5f,2.3f};for(int i=0;i<4;i++){GoodsSingle single=new GoodsSingle();single.setName(names[i]);single.setPrice(prices[i]);single.setNum(1);goodslist.add(single);}}}6、show.jsp显示商品信息<%@ page contentType="text/html;charset=gb2312"%> <%@ page import="java.util.ArrayList" %><%@ page import="com.yxq.valuebean.GoodsSingle" %> <% ArrayListgoodslist=(ArrayList)session.getAttribute("goodslist"); %><table border="1" width="450" rules="none" cellspacing="0" cellpadding="0"><tr height="50"><td colspan="3" align="center">提供商品如下</td></tr><tr align="center" height="30" bgcolor="lightgrey"> <td>名称</td><td>价格(元/斤)</td><td>购买</td></tr><% if(goodslist==null||goodslist.size()==0){ %><tr height="100"><td colspan="3" align="center">没有商品可显示!</td></tr><%}else{for(int i=0;i<goodslist.size();i++){GoodsSinglesingle=(GoodsSingle)goodslist.get(i);%><tr height="50" align="center"><td><%=single.getName()%></td><td><%=single.getPrice()%></td><td><a href="doCar?action=buy&id=<%=i%>">购买</a></td></tr><%}}%>7、创建处理用户购买、移除、清空购物车请求的ServletServlet----- BuyServletpackage com.yxq.servlet;import java.io.IOException;import java.util.ArrayList;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import com.yxq.toolbean.MyTools;import com.yxq.toolbean.ShopCar;import com.yxq.valuebean.GoodsSingle;public class BuyServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request,response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String action=request.getParameter("action"); //获取action参数值if(action==null)action="";if(action.equals("buy")) //触发了“购买”请求buy(request,response); //调用buy()方法实现商品的购买if(action.equals("remove")) //触发了“移除”请求remove(request,response); //调用remove()方法实现商品的移除if(action.equals("clear")) //触发了“清空购物车”请求clear(request,response); //调用clear()方法实现购物车的清空}//实现购买商品的方法protected void buy(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {HttpSession session=request.getSession();String strId=request.getParameter("id"); //获取触发“购买”请求时传递的id参数,该参数存储的是商品在goodslist对象中存储的位置int id=MyTools.strToint(strId);ArrayListgoodslist=(ArrayList)session.getAttribute("goodslist");GoodsSingle single=(GoodsSingle)goodslist.get(id);ArrayListbuylist=(ArrayList)session.getAttribute("buylist"); //从session范围内获取存储了用户已购买商品的集合对象if(buylist==null)buylist=new ArrayList();ShopCar myCar=new ShopCar();myCar.setBuylist(buylist); //将buylist对象赋值给ShopCar类实例中的属性myCar.addItem(single); //调用ShopCar类中addItem()方法实现商品添加操作session.setAttribute("buylist",buylist);response.sendRedirect("show.jsp"); //将请求重定向到show.jsp页面}//实现移除商品的方法protected void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session=request.getSession();ArrayListbuylist=(ArrayList)session.getAttribute("buylist");String name=request.getParameter("name");ShopCar myCar=new ShopCar();myCar.setBuylist(buylist); //将buylist对象赋值给ShopCar类实例中的属性myCar.removeItem(MyTools.toChinese(name)); //调用ShopCar类中removeItem ()方法实现商品移除操作response.sendRedirect("shopcar.jsp");}//实现清空购物车的方法protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session=request.getSession();ArrayListbuylist=(ArrayList)session.getAttribute("buylist"); //从session范围内获取存储了用户已购买商品的集合对象buylist.clear();//清空buylist集合对象,实现购物车清空的操作response.sendRedirect("shopcar.jsp");}}8、在web.xml文件中配置Servlet<?xml version="1.0" encoding="UTF-8"?><web-app><!-- 配置IndexServlet --><servlet><servlet-name>indexServlet</servlet-name><servlet-class>com.yxq.servlet.IndexServlet</servlet-class ></servlet><servlet-mapping><servlet-name>indexServlet</servlet-name><url-pattern>/index</url-pattern></servlet-mapping><!-- 配置BuyServlet --><servlet><servlet-name>buyServlet</servlet-name><servlet-class>com.yxq.servlet.BuyServlet</servlet-class> </servlet><servlet-mapping><servlet-name>buyServlet</servlet-name><url-pattern>/doCar</url-pattern></servlet-mapping></web-app>9、创建页面shopcar.jsp购物车<%@ page contentType="text/html;charset=gb2312"%> <%@ page import="java.util.ArrayList" %><%@ page import="com.yxq.valuebean.GoodsSingle" %> <%//获取存储在session中用来存储用户已购买商品的buylist 集合对象ArrayListbuylist=(ArrayList)session.getAttribute("buylist");float total=0; //用来存储应付金额%><table border="1" width="450" rules="none" cellspacing="0" cellpadding="0"><tr height="50"><td colspan="5" align="center">购买的商品如下</td></tr><tr align="center" height="30" bgcolor="lightgrey"> <td width="25%">名称</td><td>价格(元/斤)</td><td>数量</td><td>总价(元)</td><td>移除(-1/次)</td><% if(buylist==null||buylist.size()==0){ %><tr height="100"><td colspan="5" align="center">您的购物车为空!</td></tr><%}else{for(int i=0;i<buylist.size();i++){GoodsSingle single=(GoodsSingle)buylist.get(i);String name=single.getName(); //获取商品名称float price=single.getPrice(); //获取商品价格int num=single.getNum(); //获取购买数量//计算当前商品总价,并进行四舍五入float money=((int)((price*num+0.05f)*10))/10f;total+=money; //计算应付金额%><tr align="center" height="50"><td><%=name%></td><td><%=price%></td><td><%=num%></td><td><%=money%></td><td><ahref="doCar?action=remove&name=<%=single.getName() %>">移除</a></td></tr><%}}%><tr height="50" align="center"><td colspan="5">应付金额:<%=total%></td></tr><tr height="50" align="center"><td colspan="2"><a href="show.jsp">继续购物</a></td><td colspan="3"><a href="doCar?action=clear">清空购物车</a></td></tr></table>。

相关主题