• 简单的购物车


    事实证明,放假久了真的会让人变懒,我写个购物车,写了两天,无语死了。写一会,玩一会。

    一、大致模块:

    1. 商品pojo类。
    2. 添加商品到购物车页面。
    3. 添加商品到购物车Servlet。
    4. 显示购物车页面。
    5. 显示购物车Servlet。

    二,实现思路:

    首先建立pojp,然后进行一定的特殊化重写方法。

    添加商品页面使用js判断是否勾选添加的类容。

    添加商品Servlet进行一些基本的判断,处理,将本次的添加商品放入session中。

    而显示购物车就是和第一个页面差距不大,多了一个js的 求和。

    显示购物车Servlet则进行取出session

     三、代码:

    pojo代码:

    1. package Pojo;
    2. public class Shopping {
    3. private int on;// 编号
    4. private String name;// 名称
    5. private double price;// 价格
    6. private String date;// 出厂日期
    7. private String type;// 类型
    8. public Shopping() {
    9. }
    10. @Override
    11. public boolean equals(Object obj) {
    12. if (this == obj) {// 完全相同的对象
    13. return true;
    14. }
    15. if (obj instanceof Shopping) {
    16. Shopping shopping = (Shopping) obj;
    17. if (this.getOn() == shopping.getOn()) {// 编号相同
    18. return true;
    19. }
    20. }
    21. return false;
    22. }
    23. @Override
    24. public int hashCode() {
    25. Integer t = this.getOn();
    26. return t.hashCode();
    27. }
    28. @Override
    29. public String toString() {
    30. return "Shopping [on=" + on + ", name=" + name + ", price=" + price + ", date=" + date + ", type=" + type + "]";
    31. }
    32. public Shopping(int on, String name, double price, String date, String type) {
    33. super();
    34. this.on = on;
    35. this.name = name;
    36. this.price = price;
    37. this.date = date;
    38. this.type = type;
    39. }
    40. public int getOn() {
    41. return on;
    42. }
    43. public void setOn(int on) {
    44. this.on = on;
    45. }
    46. public String getName() {
    47. return name;
    48. }
    49. public void setName(String name) {
    50. this.name = name;
    51. }
    52. public double getPrice() {
    53. return price;
    54. }
    55. public void setPrice(double price) {
    56. this.price = price;
    57. }
    58. public String getDate() {
    59. return date;
    60. }
    61. public void setDate(String date) {
    62. this.date = date;
    63. }
    64. public String getType() {
    65. return type;
    66. }
    67. public void setType(String type) {
    68. this.type = type;
    69. }
    70. }

    基本的物品信息,值得注意的是,重写了equals,用于判断这俩商品是否为同一个,判断条件是on编号。后面使用hashset去重是将会调用这个hashCode方法,所以它也要重写为以on编号进行比较是否相同。

    显示商品信息页面:

    1. <%@page import="Pojo.Shopping"%>
    2. <%@page import="java.util.ArrayList"%>
    3. <%@ page language="java" contentType="text/html; charset=UTF-8"
    4. pageEncoding="UTF-8"%>
    5. html>
    6. <html>
    7. <head>
    8. <meta charset="UTF-8">
    9. <title>商品信息添加title>
    10. <style>
    11. #table1 {
    12. margin: 0px auto;
    13. }
    14. #tr>td {
    15. width: 200px;
    16. }
    17. * {
    18. margin: 0px;
    19. padding: 0px;
    20. }
    21. body {
    22. width: 60%;
    23. margin: 0px auto;
    24. }
    25. style>
    26. head>
    27. <body>
    28. <%
    29. ArrayList<Shopping> list = (ArrayList<Shopping>) request.getAttribute("scl");
    30. String msg = (String) (request.getAttribute("msg"));
    31. %>
    32. <div style="margin-top: 5%;">
    33. <p>商品信息添加p>
    34. <form action="add" method="POST">
    35. <div>
    36. <input type="submit" value="加入购物车" style="float: left;"
    37. onclick="return addF()">
    38. <input type="button" value="查看购物车"
    39. style="float: right;" onclick="location.href='ShowShoppingServlet'">
    40. div>
    41. <table border=1px style="clear: both;" id="table1">
    42. <tr id="tr">
    43. <td align="center">序号td>
    44. <td align="center">选择td>
    45. <td align="center">商品编号td>
    46. <td align="center">商品名称td>
    47. <td align="center">商品价格td>
    48. <td align="center">出厂日期td>
    49. <td align="center">商品类型td>
    50. tr>
    51. <%
    52. for (int i = 0; i < list.size(); i++) {
    53. Shopping sp = list.get(i);
    54. %>
    55. <tr>
    56. <td align="center"><%=i + 1%>td>
    57. <td align="center"><input type="checkbox" name="yes"
    58. value="<%=sp.getOn() + ":" + sp.getName() + ":" + sp.getPrice() + ":" + sp.getDate() + ":" + sp.getType()%>">td>
    59. <td align="center"><%=sp.getOn()%>td>
    60. <td align="center"><%=sp.getName()%>td>
    61. <td align="center"><%=sp.getPrice()%>td>
    62. <td align="center"><%=sp.getDate()%>td>
    63. <td align="center"><%=sp.getType()%>td>
    64. tr>
    65. <%
    66. }
    67. %>
    68. table>
    69. <%
    70. if (msg != null) {
    71. %>
    72. <p style="color: red"><%=msg%>p>
    73. <%
    74. }
    75. %>
    76. <a href="tuichu">退出账号a>
    77. form>
    78. div>
    79. <script>
    80. function addF() {
    81. var t = false;
    82. var anNiu = document.getElementsByName('yes');
    83. for (var i = 0; i < anNiu.length; i++) {
    84. if (anNiu[i].checked) {
    85. t = true;
    86. break;
    87. }
    88. }
    89. if (t) {
    90. return true;
    91. } else {
    92. alert("您未选着信息!");
    93. return false;
    94. s
    95. }
    96. }
    97. script>
    98. body>
    99. html>

    有一个简单的js判断是否勾选:

    和一个后端是否传回提示语句:

        <%
                if (msg != null) {
                %>
                

    <%=msg%>


                <%
                }
                %>

    msg的获取在上面

     显示商品信息页面Servlet代码:

    1. package Servlet;
    2. import java.io.IOException;
    3. import java.net.URLDecoder;
    4. import java.util.ArrayList;
    5. import Pojo.Shopping;
    6. import jakarta.servlet.ServletException;
    7. import jakarta.servlet.annotation.WebServlet;
    8. import jakarta.servlet.http.HttpServlet;
    9. import jakarta.servlet.http.HttpServletRequest;
    10. import jakarta.servlet.http.HttpServletResponse;
    11. /**
    12. * Servlet implementation class ShoppingServlet
    13. */
    14. public class ShoppingServlet extends HttpServlet {
    15. private static ArrayList shoppingList = new ArrayList();
    16. private static final long serialVersionUID = 1L;
    17. /**
    18. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    19. * response)
    20. */
    21. @Override
    22. public void init() throws ServletException {
    23. Shopping shopping1 = new Shopping(1, "椰汁", 10, "2021-5-6", "海南XX制造厂");
    24. Shopping shopping2 = new Shopping(2, "酸奶", 20, "2022-6-7", "湖南长沙XX制造厂");
    25. Shopping shopping3 = new Shopping(3, "雪碧", 30, "2021-11-4", "湖北武汉XX制造厂");
    26. shoppingList.add(shopping1);
    27. shoppingList.add(shopping2);
    28. shoppingList.add(shopping3);
    29. }
    30. protected void doGet(HttpServletRequest request, HttpServletResponse response)
    31. throws ServletException, IOException {
    32. doPost(request, response);
    33. }
    34. /**
    35. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    36. * response)
    37. */
    38. protected void doPost(HttpServletRequest request, HttpServletResponse response)
    39. throws ServletException, IOException {
    40. request.setAttribute("scl", shoppingList);
    41. String msg = request.getParameter("msg");
    42. if (msg != null) {
    43. msg = URLDecoder.decode(msg, "utf-8");
    44. request.setAttribute("msg", msg);
    45. }
    46. request.getRequestDispatcher("showList.jsp").forward(request, response);
    47. }
    48. }

    将数据通过转发的方法传回前端:

    request.getRequestDispatcher("showList.jsp").forward(request, response);

     将数据添加到购物车Servicelet:

    1. package Servlet;
    2. import java.io.IOException;
    3. import java.net.URLEncoder;
    4. import java.util.ArrayList;
    5. import Pojo.Shopping;
    6. import jakarta.servlet.ServletException;
    7. import jakarta.servlet.annotation.WebServlet;
    8. import jakarta.servlet.http.HttpServlet;
    9. import jakarta.servlet.http.HttpServletRequest;
    10. import jakarta.servlet.http.HttpServletResponse;
    11. import jakarta.servlet.http.HttpSession;
    12. /**
    13. * Servlet implementation class AddShoppingServlet
    14. */
    15. @WebServlet("/add")
    16. public class AddShoppingServlet extends HttpServlet {
    17. private static final long serialVersionUID = 1L;
    18. /**
    19. * Default constructor.
    20. */
    21. public AddShoppingServlet() {
    22. // TODO Auto-generated constructor stub
    23. }
    24. /**
    25. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    26. * response)
    27. */
    28. protected void doGet(HttpServletRequest request, HttpServletResponse response)
    29. throws ServletException, IOException {
    30. doPost(request, response);
    31. }
    32. /**
    33. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    34. * response)
    35. */
    36. protected void doPost(HttpServletRequest request, HttpServletResponse response)
    37. throws ServletException, IOException {
    38. HttpSession session = request.getSession();
    39. ArrayList list = (ArrayList) session.getAttribute("catList");
    40. if (list == null) {
    41. list = new ArrayList();
    42. }
    43. String[] arrs = request.getParameterValues("yes");
    44. for (int i = 0; i < arrs.length; i++) {
    45. String[] split = arrs[i].split(":");
    46. Shopping shopping = new Shopping();
    47. shopping.setOn(Integer.parseInt(split[0]));
    48. shopping.setName(split[1]);
    49. shopping.setPrice(Double.parseDouble(split[2]));
    50. shopping.setDate(split[3]);
    51. shopping.setType(split[4]);
    52. list.add(shopping);
    53. }
    54. session.setAttribute("catList", list);
    55. // System.out.println(list.size());//ok
    56. request.setAttribute("msg", "添加成功");
    57. request.getRequestDispatcher("shoppingServlet").forward(request, response);
    58. }
    59. }

    后端通过多选框的value传回的String数据,切割存储进list中,在存入特定的session。

    显示购物车:

    1. <%@page import="java.util.HashSet"%>
    2. <%@page import="java.util.Set"%>
    3. <%@page import="Pojo.Shopping"%>
    4. <%@page import="java.util.ArrayList"%>
    5. <%@ page language="java" contentType="text/html; charset=UTF-8"
    6. pageEncoding="UTF-8"%>
    7. html>
    8. <html>
    9. <head>
    10. <meta charset="UTF-8">
    11. <title>我的购物车title>
    12. <style>
    13. #table1 {
    14. margin: 0px auto;
    15. }
    16. #tr>td {
    17. width: 200px;
    18. }
    19. * {
    20. margin: 0px;
    21. padding: 0px;
    22. }
    23. body {
    24. width: 60%;
    25. margin: 0px auto;
    26. }
    27. style>
    28. head>
    29. <body>
    30. <%
    31. HashSet<Shopping> set = (HashSet<Shopping>) session.getAttribute("setCat");
    32. ArrayList<Integer> list = (ArrayList<Integer>) session.getAttribute("nums");
    33. %>
    34. <div style="margin-top: 5%;">
    35. <p>我的购物车p>
    36. <form action="add" method="POST">
    37. <table border=1px style="clear: both;" id="table1">
    38. <tr id="tr">
    39. <td align="center">数量td>
    40. <td align="center">商品编号td>
    41. <td align="center">商品名称td>
    42. <td align="center">商品价格td>
    43. <td align="center">出厂日期td>
    44. <td align="center">商品类型td>
    45. tr>
    46. <%
    47. int cont = 0;
    48. for (Shopping shopping : set) {
    49. Shopping sp = shopping;
    50. %>
    51. <tr>
    52. <td name="num" align="center"><%=list.get(cont++)%>td>
    53. <td align="center"><%=sp.getOn()%>td>
    54. <td align="center"><%=sp.getName()%>td>
    55. <td name="qian" align="center"><%=sp.getPrice()%>td>
    56. <td align="center"><%=sp.getDate()%>td>
    57. <td align="center"><%=sp.getType()%>td>
    58. tr>
    59. <%
    60. }
    61. %>
    62. table>
    63. form>
    64. <p id="sumqian">p>
    65. <a href="shoppingServlet">返回商品信息a>
    66. <script>
    67. var a=document.getElementsByName("num");
    68. var m=document.getElementsByName("qian");
    69. var sum=0;
    70. for(var i=0;ilength;i++){
    71. sum+=parseInt(a[i].innerHTML)*parseFloat(m[i].innerHTML);
    72. }
    73. document.getElementById("sumqian").innerHTML="总价格:"+sum+"元。";
    74. script>
    75. div>
    76. body>
    77. html>

    set用于获取购物车的信息

    list用于获取个数

    这两个都在后端判断并储存好了,传回前端了。

    下方有一个js用于求和购物车的钱。

    查看购物车Servlet:

     

    1. package Servlet;
    2. import java.io.IOException;
    3. import java.util.ArrayList;
    4. import java.util.Collections;
    5. import java.util.HashSet;
    6. import java.util.Set;
    7. import Pojo.Shopping;
    8. import jakarta.servlet.ServletException;
    9. import jakarta.servlet.annotation.WebServlet;
    10. import jakarta.servlet.http.HttpServlet;
    11. import jakarta.servlet.http.HttpServletRequest;
    12. import jakarta.servlet.http.HttpServletResponse;
    13. import jakarta.servlet.http.HttpSession;
    14. /**
    15. * Servlet implementation class ShowShoppingServlet
    16. */
    17. @WebServlet("/ShowShoppingServlet")
    18. public class ShowShoppingServlet extends HttpServlet {
    19. private static final long serialVersionUID = 1L;
    20. /**
    21. * Default constructor.
    22. */
    23. public ShowShoppingServlet() {
    24. // TODO Auto-generated constructor stub
    25. }
    26. /**
    27. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    28. * response)
    29. */
    30. protected void doGet(HttpServletRequest request, HttpServletResponse response)
    31. throws ServletException, IOException {
    32. doPost(request, response);
    33. }
    34. /**
    35. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    36. * response)
    37. */
    38. protected void doPost(HttpServletRequest request, HttpServletResponse response)
    39. throws ServletException, IOException {
    40. HttpSession session = request.getSession();
    41. ArrayList list = (ArrayList) session.getAttribute("catList");
    42. if (list == null) {
    43. request.setAttribute("msg", "购物车为空");
    44. request.getRequestDispatcher("shoppingServlet").forward(request, response);
    45. } else {
    46. HashSet set = new HashSet(list);
    47. ArrayList nums = new ArrayList();
    48. for (Shopping s : set) {
    49. int cont = Collections.frequency(list, s);
    50. nums.add(cont);
    51. }
    52. session.setAttribute("setCat", set);
    53. session.setAttribute("nums", nums);
    54. request.getRequestDispatcher("ShowCat.jsp").forward(request, response);
    55. }
    56. }
    57. }

    查出每个数据出现的个数:

    Collections.frequency(list, s);存入list集合中。

    再通过set特性存储去重,

    把这两个数据传回前端,就有个购物的具体数据。

    退出账号servlet:

    1. package Servlet;
    2. import java.io.IOException;
    3. import jakarta.servlet.ServletException;
    4. import jakarta.servlet.annotation.WebServlet;
    5. import jakarta.servlet.http.HttpServlet;
    6. import jakarta.servlet.http.HttpServletRequest;
    7. import jakarta.servlet.http.HttpServletResponse;
    8. import jakarta.servlet.http.HttpSession;
    9. /**
    10. * Servlet implementation class tuiChuServlet
    11. */
    12. public class tuiChuServlet extends HttpServlet {
    13. private static final long serialVersionUID = 1L;
    14. /**
    15. * Default constructor.
    16. */
    17. public tuiChuServlet() {
    18. // TODO Auto-generated constructor stub
    19. }
    20. /**
    21. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    22. * response)
    23. */
    24. protected void doGet(HttpServletRequest request, HttpServletResponse response)
    25. throws ServletException, IOException {
    26. doPost(request, response);
    27. }
    28. /**
    29. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    30. * response)
    31. */
    32. protected void doPost(HttpServletRequest request, HttpServletResponse response)
    33. throws ServletException, IOException {
    34. HttpSession session = request.getSession();
    35. request.getSession().removeAttribute("scl");
    36. request.getSession().removeAttribute("setCat");
    37. request.getSession().removeAttribute("nums");
    38. request.getSession().removeAttribute("catList");
    39. response.sendRedirect("Index.jsp");
    40. }
    41. }

     退出账号就比较简单,清除指定的session,然后跳转页面。

    以上便是一个简单的购物车程序,也许大佬们看着bug百出,不过作为初学者的我们,一步一个脚印,慢慢来。加油~~~ 

  • 相关阅读:
    HTML实现移动端布局与页面自适应
    Vue + Nodejs + socket.io 实现聊天
    前端开发技术栈(工具篇):2023深入了解webpack的安装和使用以及核心概念和启动流程(详细) 63.3k stars
    Linux 环境搭建
    Matlab转C++代码入门————附带详细代码和示例
    Webpack 如何安装依赖,-D 和 -S的区别?
    x265源码分析-estimateCUCost
    Linux 搭建Owncloud 私有云
    【设计模式】过滤器模式(Filter Pattern)
    python毕业设计项目源码选题(19)篮球、足球、羽毛球等运动场地预约系统毕业设计毕设作品开题报告开题答辩PPT
  • 原文地址:https://blog.csdn.net/qx020814/article/details/126270774