以下面购物车几个页面传输数据为例html页面有index.html
后面是三个副页fuzhuang.html;shipin.html;dianzi.html
fuzhuang.html
1 2 3 4 517 回到首页18 26 27服装 6 7 8 9
dianzi.html
1 2 3 4 517 回到首页18 26 27电子 6 7 8 9
shipin.html
回到首页食品
Servlet中两个页面 Addlist.java
1 package control; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import javax.servlet.http.HttpSession; 9 import java.io.IOException;10 import java.io.PrintWriter;11 import java.util.ArrayList;12 import java.util.List;13 14 @WebServlet("/addList")15 public class AddList extends HttpServlet {16 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {17 request.setCharacterEncoding("utf-8");18 String[] goods=request.getParameterValues("fz");19 String[] goods1=request.getParameterValues("dz");20 String[] goods2=request.getParameterValues("sp");21 HttpSession session=request.getSession();22 Listlistgoods=(List ) session.getAttribute("goods");23 if (listgoods==null){24 listgoods=new ArrayList<>();25 session.setAttribute("goods",listgoods);26 }27 if(goods!=null){ for (String s:goods){28 System.out.println(s+" ");29 listgoods.add(s);30 }}31 if(goods1!=null){ for (String s:goods1){32 System.out.println(s+" ");33 listgoods.add(s);34 }}35 if(goods2!=null){ for (String s:goods2){36 System.out.println(s+" ");37 listgoods.add(s);38 }}39 response.setCharacterEncoding("utf-8");40 response.setContentType("application/json;charset=utf-8");41 PrintWriter out=response.getWriter();42 out.write("{\"status\":\"添加成功\"}");43 out.close();44 45 }46 47 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {48 49 }50 }
Getgoods.java
1 package control; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import javax.servlet.http.HttpSession; 9 import java.io.IOException;10 import java.io.PrintWriter;11 import java.util.List;12 13 @WebServlet("/getgoods")14 public class Getgoods extends HttpServlet {15 @Override16 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {17 HttpSession session=req.getSession();18 Listgoods=(List ) session.getAttribute("goods");19 resp.setContentType("application/json;charset=utf-8");20 PrintWriter out=resp.getWriter();21 if (goods==null){22 out.write("{\"goods\":"+null+"}");23 }else{24 Object[] arr=goods.toArray();25 String s="{\"goods\":[";26 for (int i=0;i