用session实现购物车(含设计分析及源代码)part3

最后的servlet层的编写:



首先是简单商品展示页(IndexServlet.servlet):

package cn.zc.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zc.domain.Product;
import cn.zc.service.ProductServiceImpl;

public class IndexServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public IndexServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		ProductServiceImpl psi=new ProductServiceImpl();//数据库service层
		List<Product> entities=psi.findAll();//得到数据库数据
		
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE>");
		out.println("<style>a{text-decoration:none;color:#666;font-size:20px;}");
		out.println("a:hover{font-size:22px;color:#f00;}");
		out.println("</style>");
		out.println("</HEAD>");
		out.println("  <BODY>");
		
		out.println("    <ul style=\"list-style:none;text-align:left;\">");
		for (int i=0;i<entities.size();i++){
			out.println("<li><a href=\"BuyServlet?id="+(i+1)+"\">"+"商品名称:  "+
			//每个列出商品的名称和价格做成超链接点击时提交给BuyServlet
					entities.get(i).getName()+"    参考价格:  "+
					entities.get(i).getPrice()+"</a></li>");
		}
		out.println("    </ul>");
		
		out.println("<br><br>");
		out.println("<a href=\"ShowCart\">查看购物车</a>");// 查看购物车连接跳转到ShowCart.servlet
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

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

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}




点击商品超链接后显示商品的详细信息(BuyServlet.servlet):

package cn.zc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zc.domain.Product;
import cn.zc.service.ProductServiceImpl;

public class BuyServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public BuyServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		ProductServiceImpl psi=new ProductServiceImpl();//数据库service层
		int id=Integer.parseInt(request.getParameter("id"));
		Product entity=psi.findById(id);//查找出指定id的商品
		
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		
		out.println("    <table border=\"1px\" width=\"500px\" height=\"200px\">");
		out.println("      <tr height=\"50px\">");
		out.println("        <td>商品名:</td>");
		out.println("        <td>"+entity.getName()+"</td>");
		out.println("        <td>实惠价:</td>");
		out.println("        <td>"+entity.getPrice()+"</td>");
		out.println("      </tr>");
		out.println("      <tr>");
		out.println("        <td>介绍:</td>");
		out.println("        <td colspan=\"3\">"+entity.getSummary()+"</td>");
		out.println("       </tr>");
		out.println("    </table>");
		out.println("<br>");
		out.println("<form action=\"CarServlet\" method=\"post\">");
                //点击下面的“加入购物车”提交按钮将数据提交给CarServlet提示用户已添加至购物车
		out.println("<input type=\"hidden\" value=\""+id+"\" name=\"id\">");
		out.println("购买数量:<input type=\"input\" name=\"buyNum\">");
		out.println("<input type=\"submit\" value=\"加入购物车\">");
		out.println("<br><br>");
		out.println("<a href=\"IndexServlet\">返回首页继续购物</a>");
		out.println("</form>");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

			doGet(request,response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}



确认信息(CartServlet.servlet):

package cn.zc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

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 cn.zc.domain.CarProduct;
import cn.zc.domain.Product;
import cn.zc.service.ProductServiceImpl;

public class CarServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public CarServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		ProductServiceImpl psi = new ProductServiceImpl();// 数据库service层
		int id = Integer.parseInt(request.getParameter("id"));
		Product entity = psi.findById(id);// 查找出指定id的商品
		HttpSession session = request.getSession();// 创建session

		/* 将加入购物车的商品id和购买数量存储到car购物车对象中 */
		CarProduct carProduct = new CarProduct(entity, Integer.parseInt(request
				.getParameter("buyNum")));
		List<CarProduct> car = (List<CarProduct>) session.getAttribute("product");// 用列表存储CarProduct对象
		if(car==null){
			car=new ArrayList<CarProduct>();
		}
		car.add(carProduct);// 添加新加入购物车的商品
		session.setAttribute("product", car);

		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("   物品 :  " + carProduct.getName()
				+ "  已加入购物车!购买数量是:  "
				+ carProduct.getBuyNum());
		out.println("<br><br>");
		out.println("<a href=\"IndexServlet\">返回首页继续购物</a>");
		out.println("<a href=\"ShowCart\">查看购物车</a>");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}


购物车信息(ShowCart.servlet):


package cn.zc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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 cn.zc.domain.CarProduct;

public class ShowCart extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public ShowCart() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		showCar(request, response);// 调用查看购车函数
		out.println("  <br><br><a href=\"IndexServlet\">返回首页继续购物</a>");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	public void showCar(HttpServletRequest request, HttpServletResponse response)
			throws IOException {// 查看购物车函数
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		List<CarProduct> car;

		HttpSession session = request.getSession();
		if (session.getAttribute("product") == null) {
			out.println("  你还没有买东西哟!");
		} else {
			car = (List<CarProduct>) session.getAttribute("product");
			Double totalMoney = 0.00;// 消费总金额
			out.println("    <table border=1px>");
			for (CarProduct entity : car) {//以表格形式显示以购买商品信息
				out.println("     <tr><td>商品名:</td><td>" + entity.getName()
						+ "</td><td>单价:</td><td>" + entity.getPrice()
						+ "<td>购买数量:</td><td>" + entity.getBuyNum()
						+ "</td></tr>");
				totalMoney += entity.getBuyNum() * entity.getPrice();
			}

			out.println("      <tr><td colspan=5>消费总额小计(RMB):</td><td>"
					+ totalMoney + "</td></tr>");
			out.println("    </table>");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

这样我们的session购物车就简单的完成了。还有许多小缺点和bug希望各位积极提出意见。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值