事实证明,放假久了真的会让人变懒,我写个购物车,写了两天,无语死了。写一会,玩一会。
一、大致模块:
- 商品pojo类。
- 添加商品到购物车页面。
- 添加商品到购物车Servlet。
- 显示购物车页面。
- 显示购物车Servlet。
二,实现思路:
首先建立pojp,然后进行一定的特殊化重写方法。
添加商品页面使用js判断是否勾选添加的类容。
添加商品Servlet进行一些基本的判断,处理,将本次的添加商品放入session中。
而显示购物车就是和第一个页面差距不大,多了一个js的 求和。
显示购物车Servlet则进行取出session。
三、代码:
pojo代码:
- package Pojo;
-
- public class Shopping {
- private int on;// 编号
- private String name;// 名称
- private double price;// 价格
- private String date;// 出厂日期
- private String type;// 类型
-
- public Shopping() {
-
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {// 完全相同的对象
- return true;
- }
- if (obj instanceof Shopping) {
- Shopping shopping = (Shopping) obj;
- if (this.getOn() == shopping.getOn()) {// 编号相同
- return true;
- }
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- Integer t = this.getOn();
- return t.hashCode();
- }
-
- @Override
- public String toString() {
- return "Shopping [on=" + on + ", name=" + name + ", price=" + price + ", date=" + date + ", type=" + type + "]";
- }
-
- public Shopping(int on, String name, double price, String date, String type) {
- super();
- this.on = on;
- this.name = name;
- this.price = price;
- this.date = date;
- this.type = type;
- }
-
- public int getOn() {
- return on;
- }
-
- public void setOn(int on) {
- this.on = on;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public double getPrice() {
- return price;
- }
-
- public void setPrice(double price) {
- this.price = price;
- }
-
- public String getDate() {
- return date;
- }
-
- public void setDate(String date) {
- this.date = date;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
- }
基本的物品信息,值得注意的是,重写了equals,用于判断这俩商品是否为同一个,判断条件是on编号。后面使用hashset去重是将会调用这个hashCode方法,所以它也要重写为以on编号进行比较是否相同。
显示商品信息页面:
- <%@page import="Pojo.Shopping"%>
- <%@page import="java.util.ArrayList"%>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>商品信息添加title>
- <style>
- #table1 {
- margin: 0px auto;
- }
-
- #tr>td {
- width: 200px;
- }
-
- * {
- margin: 0px;
- padding: 0px;
- }
-
- body {
- width: 60%;
- margin: 0px auto;
- }
- style>
- head>
- <body>
- <%
- ArrayList<Shopping> list = (ArrayList<Shopping>) request.getAttribute("scl");
- String msg = (String) (request.getAttribute("msg"));
- %>
-
- <div style="margin-top: 5%;">
- <p>商品信息添加p>
- <form action="add" method="POST">
- <div>
- <input type="submit" value="加入购物车" style="float: left;"
- onclick="return addF()">
- <input type="button" value="查看购物车"
- style="float: right;" onclick="location.href='ShowShoppingServlet'">
- div>
- <table border=1px style="clear: both;" id="table1">
- <tr id="tr">
- <td align="center">序号td>
- <td align="center">选择td>
- <td align="center">商品编号td>
- <td align="center">商品名称td>
- <td align="center">商品价格td>
- <td align="center">出厂日期td>
- <td align="center">商品类型td>
- tr>
- <%
- for (int i = 0; i < list.size(); i++) {
- Shopping sp = list.get(i);
- %>
- <tr>
- <td align="center"><%=i + 1%>td>
- <td align="center"><input type="checkbox" name="yes"
- value="<%=sp.getOn() + ":" + sp.getName() + ":" + sp.getPrice() + ":" + sp.getDate() + ":" + sp.getType()%>">td>
- <td align="center"><%=sp.getOn()%>td>
- <td align="center"><%=sp.getName()%>td>
- <td align="center"><%=sp.getPrice()%>td>
- <td align="center"><%=sp.getDate()%>td>
- <td align="center"><%=sp.getType()%>td>
- tr>
- <%
- }
- %>
- table>
- <%
- if (msg != null) {
- %>
- <p style="color: red"><%=msg%>p>
- <%
- }
- %>
- <a href="tuichu">退出账号a>
-
-
- form>
- div>
- <script>
- function addF() {
- var t = false;
- var anNiu = document.getElementsByName('yes');
- for (var i = 0; i < anNiu.length; i++) {
- if (anNiu[i].checked) {
- t = true;
- break;
- }
- }
- if (t) {
- return true;
- } else {
- alert("您未选着信息!");
- return false;
- s
- }
- }
- script>
- body>
- html>
有一个简单的js判断是否勾选:
和一个后端是否传回提示语句:
<%
if (msg != null) {
%>
<%=msg%>
<%
}
%>msg的获取在上面
显示商品信息页面Servlet代码:
- package Servlet;
-
- import java.io.IOException;
- import java.net.URLDecoder;
- import java.util.ArrayList;
-
- import Pojo.Shopping;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.annotation.WebServlet;
- import jakarta.servlet.http.HttpServlet;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
-
- /**
- * Servlet implementation class ShoppingServlet
- */
- public class ShoppingServlet extends HttpServlet {
- private static ArrayList
shoppingList = new ArrayList(); - private static final long serialVersionUID = 1L;
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- @Override
- public void init() throws ServletException {
- Shopping shopping1 = new Shopping(1, "椰汁", 10, "2021-5-6", "海南XX制造厂");
- Shopping shopping2 = new Shopping(2, "酸奶", 20, "2022-6-7", "湖南长沙XX制造厂");
- Shopping shopping3 = new Shopping(3, "雪碧", 30, "2021-11-4", "湖北武汉XX制造厂");
- shoppingList.add(shopping1);
- shoppingList.add(shopping2);
- shoppingList.add(shopping3);
- }
-
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
-
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setAttribute("scl", shoppingList);
- String msg = request.getParameter("msg");
- if (msg != null) {
- msg = URLDecoder.decode(msg, "utf-8");
- request.setAttribute("msg", msg);
- }
- request.getRequestDispatcher("showList.jsp").forward(request, response);
- }
-
- }
将数据通过转发的方法传回前端:
request.getRequestDispatcher("showList.jsp").forward(request, response);
将数据添加到购物车Servicelet:
- package Servlet;
-
- import java.io.IOException;
- import java.net.URLEncoder;
- import java.util.ArrayList;
-
- import Pojo.Shopping;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.annotation.WebServlet;
- import jakarta.servlet.http.HttpServlet;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import jakarta.servlet.http.HttpSession;
-
- /**
- * Servlet implementation class AddShoppingServlet
- */
- @WebServlet("/add")
- public class AddShoppingServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * Default constructor.
- */
- public AddShoppingServlet() {
- // TODO Auto-generated constructor stub
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- HttpSession session = request.getSession();
- ArrayList
list = (ArrayList) session.getAttribute("catList"); - if (list == null) {
- list = new ArrayList
(); - }
- String[] arrs = request.getParameterValues("yes");
- for (int i = 0; i < arrs.length; i++) {
- String[] split = arrs[i].split(":");
- Shopping shopping = new Shopping();
- shopping.setOn(Integer.parseInt(split[0]));
- shopping.setName(split[1]);
- shopping.setPrice(Double.parseDouble(split[2]));
- shopping.setDate(split[3]);
- shopping.setType(split[4]);
- list.add(shopping);
- }
- session.setAttribute("catList", list);
- // System.out.println(list.size());//ok
- request.setAttribute("msg", "添加成功");
- request.getRequestDispatcher("shoppingServlet").forward(request, response);
- }
-
- }
后端通过多选框的value传回的String数据,切割存储进list中,在存入特定的session。
显示购物车:
- <%@page import="java.util.HashSet"%>
- <%@page import="java.util.Set"%>
- <%@page import="Pojo.Shopping"%>
- <%@page import="java.util.ArrayList"%>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>我的购物车title>
- <style>
- #table1 {
- margin: 0px auto;
- }
-
- #tr>td {
- width: 200px;
- }
-
- * {
- margin: 0px;
- padding: 0px;
- }
-
- body {
- width: 60%;
- margin: 0px auto;
- }
- style>
- head>
- <body>
- <%
- HashSet<Shopping> set = (HashSet<Shopping>) session.getAttribute("setCat");
- ArrayList<Integer> list = (ArrayList<Integer>) session.getAttribute("nums");
- %>
-
- <div style="margin-top: 5%;">
- <p>我的购物车p>
- <form action="add" method="POST">
- <table border=1px style="clear: both;" id="table1">
- <tr id="tr">
- <td align="center">数量td>
- <td align="center">商品编号td>
- <td align="center">商品名称td>
- <td align="center">商品价格td>
- <td align="center">出厂日期td>
- <td align="center">商品类型td>
- tr>
-
- <%
- int cont = 0;
- for (Shopping shopping : set) {
- Shopping sp = shopping;
- %>
- <tr>
- <td name="num" align="center"><%=list.get(cont++)%>td>
- <td align="center"><%=sp.getOn()%>td>
- <td align="center"><%=sp.getName()%>td>
- <td name="qian" align="center"><%=sp.getPrice()%>td>
- <td align="center"><%=sp.getDate()%>td>
- <td align="center"><%=sp.getType()%>td>
- tr>
- <%
- }
- %>
-
- table>
- form>
- <p id="sumqian">p>
- <a href="shoppingServlet">返回商品信息a>
- <script>
- var a=document.getElementsByName("num");
- var m=document.getElementsByName("qian");
- var sum=0;
- for(var i=0;i
length;i++){ - sum+=parseInt(a[i].innerHTML)*parseFloat(m[i].innerHTML);
- }
- document.getElementById("sumqian").innerHTML="总价格:"+sum+"元。";
- script>
- div>
- body>
- html>
set用于获取购物车的信息
list用于获取个数
这两个都在后端判断并储存好了,传回前端了。
下方有一个js用于求和购物车的钱。
查看购物车Servlet:
- package Servlet;
-
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.HashSet;
- import java.util.Set;
-
- import Pojo.Shopping;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.annotation.WebServlet;
- import jakarta.servlet.http.HttpServlet;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import jakarta.servlet.http.HttpSession;
-
- /**
- * Servlet implementation class ShowShoppingServlet
- */
- @WebServlet("/ShowShoppingServlet")
- public class ShowShoppingServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * Default constructor.
- */
- public ShowShoppingServlet() {
- // TODO Auto-generated constructor stub
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- HttpSession session = request.getSession();
- ArrayList
list = (ArrayList) session.getAttribute("catList"); - if (list == null) {
- request.setAttribute("msg", "购物车为空");
- request.getRequestDispatcher("shoppingServlet").forward(request, response);
- } else {
- HashSet
set = new HashSet(list); - ArrayList
nums = new ArrayList(); - for (Shopping s : set) {
- int cont = Collections.frequency(list, s);
- nums.add(cont);
- }
- session.setAttribute("setCat", set);
- session.setAttribute("nums", nums);
- request.getRequestDispatcher("ShowCat.jsp").forward(request, response);
- }
- }
-
- }
查出每个数据出现的个数:
Collections.frequency(list, s);存入list集合中。
再通过set特性存储去重,
把这两个数据传回前端,就有个购物的具体数据。
退出账号servlet:
- package Servlet;
-
- import java.io.IOException;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.annotation.WebServlet;
- import jakarta.servlet.http.HttpServlet;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import jakarta.servlet.http.HttpSession;
-
- /**
- * Servlet implementation class tuiChuServlet
- */
- public class tuiChuServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * Default constructor.
- */
- public tuiChuServlet() {
- // TODO Auto-generated constructor stub
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- HttpSession session = request.getSession();
- request.getSession().removeAttribute("scl");
- request.getSession().removeAttribute("setCat");
- request.getSession().removeAttribute("nums");
- request.getSession().removeAttribute("catList");
- response.sendRedirect("Index.jsp");
- }
-
- }
退出账号就比较简单,清除指定的session,然后跳转页面。
以上便是一个简单的购物车程序,也许大佬们看着bug百出,不过作为初学者的我们,一步一个脚印,慢慢来。加油~~~