📄 shop_servlet.java
字号:
package com;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Shop_Servlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
request.setCharacterEncoding("gbk");//处理 乱码
PrintWriter out = response.getWriter();
out.println("<center><h1>你放在购物篮里的商品是:</h1><hr/>");
HttpSession session = request.getSession();//获得session
try{
String items[] = request.getParameterValues("item1"); //购买的商品列表
List list = (ArrayList) session.getAttribute("Shop_Table");//从session中获得已选的商品列表
if (list == null) {
list = new ArrayList();//还没购物车时,实例一个购物车
}
Product_car pc = new Product_car();
pc.setMybasket(list);
if (items != null) {
for (int i = 0; i < items.length; i++) {
Product_Bean pb = new Product_Bean();
pb.setName(items[i]);
pb.setNum(1);
pc.addProduct(pb); //加入一个电器
}
list = pc.getMybasket();//获得加后的购物车中的商品列表
session.setAttribute("Shop_Table",list);//把新的产品列表 放入session
}
//如果购物车中有商品则 显示出来
if(list!=null&&list.size()>0){
for (int i = 0; i < list.size(); i++) {
Product_Bean pb = (Product_Bean)list.get(i);
out.println(pb.getName() +":"+pb.getNum()+ "<br/>");
}
}else{
out.println("<h1>你购物篮里没有商品</h1>");
}
}catch(Exception e){
e.printStackTrace();
}
out.println("<hr/>");
out.println("<a href='product_list.htm'>继续购买商品</a>");
out.close();
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -