练习要求:不使用jsp页面,只用servlet实现模拟购物车的需求。效果图:
初次访问时:
点击按钮添加了一件商品后:
多次点击按钮添加商品后:
?
练习分析:模拟购物车的需求较为简单,我们用一个单一的Sevlet实现。把“添加商品”按钮作为提交按钮,将请求转发给servlet本身。为了识别多次请求是否为同一个用户,我们需要在表单中加一个参数。由于传递的参数需要对用户不可见,我们需要用到隐藏表单域“<input type="hidden">”。每次商品的编号由随即函数生成。而用户已经选择的商品,我们用一个arraylist来记录。
?
最终代码:package netjava.raul.shop;
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class shopServlet */ public class shopServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Random r = new Random(); List<Integer> l = new ArrayList<Integer>(); /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=gbk"); PrintWriter out = response.getWriter(); out.print("<h2>购物车</h2><br/>"); String user = request.getParameter("user"); System.out.println(user); out.print("<form name='addgoods' action='shopServlet' method='get'>"); if(!"raul".equals(user)){ out.print("<p>您的购物车空空如也,快去挑选自己喜欢的商品吧</p>"); }else{ out.print("<p>欢迎您回来"+user+",以下是商品清单</p>"); int i = r.nextInt(100); l.add(i); for(int p=0;p<l.size();p++){ out.print("<p>商品"+l.get(p)+"</p>"); } } out.print("<input type='hidden' name='user' value='raul'/>"); out.print("<input type='submit' value='添加商品'/>"); out.print("</form>"); out.flush(); out.close(); } }