html网页代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>商品列表</title>
</head>
<body>
<h3>点击下面的商品链接, 可以将商品加入购物车</h3>
<p><a href="CartServlet?prod=iphone11">iphone11</a></p>
<p><a href="CartServlet?prod=vivonex3">vivonex3</a></p>
<p><a href="CartServlet?prod=xiaomishouji">xiaomishouji</a></p>
<p><a href="CartServlet?prod=huaweip30">huaweip30</a></p>
<h3>点击下面的支付链接, 可以对购物车中的商品进行结算</h3>
<a href="PayServlet">支付</a>
</body>
</html>
简单购物车页面的CartServlet程序如下
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String prodName = request.getParameter( "prod" );
Cookie cookie = new Cookie( "cart", prodName );
response.addCookie( cookie );
out.write( "成功将[ "+prodName+" ]加入了购物车..." );
}
简单支付页面的PayServlet如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Cookie[] cs = request.getCookies();
String prod = null;
if( cs != null ) {
for( Cookie c : cs ) {
if( "cart".equals( c.getName() ) ) {
prod = c.getValue();
}
}
}
if( prod != null ) {
out.write( "成功为{ "+prod+" }支付了1000元..." );
}else {
out.write( "您还没有将任何商品加入购物车..." );
}
}