Home> Java> javaTutorial> body text

Shopping cart developed based on Servlet+JSP+JavaBean

巴扎黑
Release: 2017-08-10 15:16:15
Original
2138 people have browsed it

The previous article used a most commonly used user login registration program to explain the Servlet+JSP+JavaBean development model, so we also have a preliminary understanding of the Servlet+JSP+JavaBean (MVC) model. Now let's review this development model with a shopping cart program for online shopping.

Create a Web project with MVC architecture

Create a new day10 project in Eclipse, import the development package (jar package) required for the project, create the package required for the project, in java development , the architecture levels are reflected in the form of packages.
Development package (jar package) required for the project:

Serial number Development package name Description
1 stl-1.2.jar jstl tag library and EL expression dependency package

Note: Different from the user login registration program in the previous article, this shopping cart program creates a class to represent the database, so there is no need to use other jar packages, just use Just go tostl-1.2.jar.
Packages required for the project:

The above are the packages created based on the actual situation of this project. You may also need to create other packages. This depends on the needs of the project.
Create a class representing the database:
Assume this is an online bookstore project, and the products purchased by users are books, so the products stored in the database are books. Create a DB class under the cn.itcast.DB package.
Shopping cart developed based on Servlet+JSP+JavaBean
The specific code of the DB class is as follows:

public class DB { private static Map map = new LinkedHashMap(); static { map.put("1", new Book("1", "javaweb开发", "老张", 38, "一本好书")); map.put("2", new Book("2", "jdbc开发", "老黎", 18, "一本好书")); map.put("3", new Book("3", "ajax开发", "老佟", 328, "一本好书")); map.put("4", new Book("4", "jbpm开发", "老毕", 58, "一本好书")); map.put("5", new Book("5", "struts开发", "老方", 28, "一本好书")); map.put("6", new Book("6", "spring开发", "老方", 98, "一本好书")); } public static Map getAll() { return map; } }1234567891011121314151617
Copy after login

Note: Regarding how to create a class representing the database - DB.java, please refer to my Using Cookies for Session Management.
Create a jsp directory in the WEB-INF directory. The jsp directory stores some protected jsp pages of the system (users are not allowed to access directly through URL addresses). If users want to access these protected jsp pages, they can only Through the Servlet in the cn.itcast.web.UI package.
The created project architecture is shown in the figure below:
Shopping cart developed based on Servlet+JSP+JavaBean

The code of the hierarchical architecture is written

The code of the hierarchical architecture is also based on the [domain model layer (domain )] → [Data access layer (dao, dao.impl)] → [Business logic layer (service, service.impl)] → [Presentation layer (web.controller, web.UI, web.filter, web.listener)] It is written in the order of → [Tool class (util)] → [Test class (junit.test)].

Develop domain layer

Create a Book class under the cn.itcast.domain package.
Shopping cart developed based on Servlet+JSP+JavaBean
The specific code of the Book class is as follows:

public class Book { private String id; private String name; private String author; private double price; private String description; public Book() { super(); // TODO Auto-generated constructor stub } public Book(String id, String name, String author, double price, String description) { super(); this.id = id; this.name = name; this.author = author; this.price = price; this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
Copy after login

Develop data access layer (dao, dao.impl)

Create a UserDao class under the cn.itcast.dao package.
Shopping cart developed based on Servlet+JSP+JavaBean
The specific code of the UserDao class is as follows:

public class BookDao { public Map getAll() { return DB.getAll(); } public Book find(String id) { return DB.getAll().get(id); } }1234567891011
Copy after login

Developing the service layer (the service layer provides all business services to the web layer)

When we first developed a new project, we were not clear about it. The functions of all projects to be developed, so we can first develop the functions that are easiest to think of, and then disguise ourselves as a user. During the process of browsing the website pages, we see what functions the user needs, and then our programmers will develop what functions , and then work step by step to complete the functions of the entire project.
For example, when I first developed this shopping cart function module, the first thing I thought of was to display all the books to the user and query the book information based on the book ID. I didn't expect other functions, so I can wait until these functions are completed and see what functions are needed based on the front-end page.
Create a BusinessService class under the cn.itcast.service package.
Shopping cart developed based on Servlet+JSP+JavaBean
First write the BusinessService class that implements the following two business services.

  • Show all books to users

  • Query book information based on book ID

Specific The code is as follows:

// 业务类,统一对web层提供所有服务public class BusinessService { private BookDao dao = new BookDao(); public Map getAllBook() { return dao.getAll(); } public Book findBook(String id) { return dao.find(id); } }12345678910111213
Copy after login

Develop the Web layer

Develop the function of displaying all books to users

Written under the cn.itcast.web.controller package to process and display to users ListBookServlet for all books.
Shopping cart developed based on Servlet+JSP+JavaBean
The specific code of the ListBookServlet class is as follows:

// 获取所有书public class ListBookServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BusinessService service = new BusinessService(); Map map = service.getAllBook(); request.setAttribute("map", map); request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }12345678910111213141516171819
Copy after login

Write the jsp page listbook.jsp in the /WEB-INF/jsp/ directory to display all books to the user.
Shopping cart developed based on Servlet+JSP+JavaBean
Any jsp page located in the WEB-INF directory cannot be accessed directly through the URL address. During development, if there are some sensitive web resources in the project that you do not want to be directly accessed by the outside world, you can consider placing these sensitive web resources in the WEB-INF directory, so that outsiders can be prohibited from accessing them directly through URLs. The code of the
listbook.jsp page is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>书籍列表页面

书籍列表

书名 作者 售价 描述 操作
${entry.value.name } ${entry.value.author } ${entry.value.price } ${entry.value.description } 购买
12345678910111213141516171819202122232425262728293031323334
Copy after login

Websites generally have a homepage. In this project, in our homepage index.jsp, the user clicks theBrowse Bookshyperlink. All books on the website can be browsed. The code of the
index.jsp page is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>网站首页
浏览书籍123456789101112
Copy after login

At this point, the development of the function of displaying all books to users is completed! Let’s test the developed function:
Shopping cart developed based on Servlet+JSP+JavaBean

开发购买书籍的功能

在现实中购买商品时,用户都是将商品放到购物车中,所以我们应该按照现实中的情况设计一个代表用户购物车的类——Cart.java。
现在再来思考一个问题:在设计代表用户购物车的Cart类时,应该使用private Book book字段(或属性)来代表用户所购买的商品吗?
答案显然不是。若是使用这样的字段,结果就是不可避免地在购物车中出现重复商品,即用户如果购买一本书多次,那么购物车中就出现一本书多次,显然在现实中这是不合理的。那么到底该怎么做呢?——为了避免在购物车里面出现重复商品,我们这时会设计一个专门的对象——CartItem(购物项,代表某个商品以及这个商品出现的次数)
在cn.itcast.domain包下创建一个CartItem类,用于代表某个商品,以及商品出现的次数(购物项)。
Shopping cart developed based on Servlet+JSP+JavaBean
CartItem类的具体代码如下:

// 用于代表某个商品,以及商品出现的次数(购物项)public class CartItem { private Book book; private int quantity; private double price; public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; this.price = this.book.getPrice() * this.quantity; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }12345678910111213141516171819202122232425262728
Copy after login

在cn.itcast.domain包中创建一个代表用户购物车的Cart类。
Shopping cart developed based on Servlet+JSP+JavaBean
Cart类的具体代码如下:

// 代表用户的购物车public class Cart { /* * 为了避免在购物车里面出现重复商品, * 我们这时会设计一个专门的对象——CartItem(购物项,代表某个商品以及这个商品出现的次数) */ private Map map = new LinkedHashMap<>(); private double price; // 记住购物车中的所有商品多少钱 public void add(Book book) { // 看购物车中有没有,要添加的书对应的购物项 CartItem item = map.get(book.getId()); if(item==null) { item = new CartItem(); item.setBook(book); item.setQuantity(1); map.put(book.getId(), item); } else { item.setQuantity(item.getQuantity()+1); } } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } public double getPrice() { double totalprice = 0; for(Map.Entry entry : map.entrySet()) { CartItem item = entry.getValue(); totalprice += item.getPrice(); } this.price = totalprice; return price; } public void setPrice(double price) { this.price = price; } }12345678910111213141516171819202122232425262728293031323334353637383940414243
Copy after login

用户浏览网站首页时,会看到网站所有书籍,用户即可对自己感兴趣的书籍进行购买,点击购物超链接时,跳转到一个servlet对用户的请求进行处理。所以在cn.itcast.web.controller包中创建一个代表完成书籍购买的BuyServlet类。
Shopping cart developed based on Servlet+JSP+JavaBean
BuyServlet类的具体代码如下:

// 完成书籍购买@WebServlet("/BuyServlet")public class BuyServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); BusinessService service = new BusinessService(); Book book = service.findBook(id); // 得到用户的购物车 Cart cart = (Cart) request.getSession().getAttribute("cart"); // 用户第一次购买,为用户创建购物车 if(cart==null) { cart = new Cart(); request.getSession().setAttribute("cart", cart); } // 把书加到用户的购物车中,完成购买 cart.add(book); /* * 浏览器重新访问地址:/WEB-INF/jsp/listcart.jsp * 但这个地址被保护起来,外面是无法直接访问的, * 要实现的话,会比较麻烦,需要先跳到servlet,然后再转到jsp。 */ // response.sendRedirect("/WEB-INF/jsp/listcart.jsp"); request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }1234567891011121314151617181920212223242526272829303132333435363738
Copy after login

注意:显示购物车时,记住千万不要用请求转发,而应该使用重定向技术。若不是产生的后果可参考我的笔记Session——使用Session完成简单的购物功能。我上面的代码使用的是请求转发,这是不行的,读者要注意了啊!既然要使用重定向技术,下面这行代码可行吗?

response.sendRedirect("/WEB-INF/jsp/listcart.jsp");1
Copy after login

答案不言而喻,这是不行的。因为这是浏览器重新访问地址/WEB-INF/jsp/listcart.jsp,listcart.jsp页面是被保护起来了,外界是无法直接访问的。如果一定要实现的话,会比较麻烦,还需要先跳到一个servlet,然后再跳转到listcart.jsp。所以正规的做法是:BuyServlet类中使用重定向技术,即添加如下代码:

response.sendRedirect(request.getContextPath()+"/ListCartUIServlet");1
Copy after login

然后在cn.itcast.web.UI包下创建一个ListCartUIServlet类,专门用来接收请求之后转到jsp,给用户提供用户界面。
Shopping cart developed based on Servlet+JSP+JavaBean
ListCartUIServlet类的具体代码如下:

public class ListCartUIServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }12345678910111213
Copy after login

这毕竟不是一个真实项目,所以不想把其搞得这么复杂哈!所以就干脆用了请求转发,但是读者一定要知道这还是不行的,要知道用重定向技术,怎么使用我也已经写的很明白了!
购物车显示页面listcart.jsp代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>购物车列表

购物车列表

您没有购买任何商品!!!
书名 作者 单价 数量 小计 操作
${entry.value.book.name } ${entry.value.book.author } ${entry.value.book.price } ${entry.value.price } 删除
总价 ${cart.price }元 清空购物车
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
Copy after login

至此,用户购买书籍的功能就算是开发完成了!下面测试一下开发好的该功能:
Shopping cart developed based on Servlet+JSP+JavaBean

开发删除购物车中购物项的功能

编写实现如下业务服务的BusinessService类。

  • 删除购物车中购物项

此时BusinessService类的具体代码如下:

// 业务类,统一对web层提供所有服务public class BusinessService { private BookDao dao = new BookDao(); public Map getAllBook() { return dao.getAll(); } public Book findBook(String id) { return dao.find(id); } // 删除购物车中购物项 public void deleteCartItem(String id, Cart cart) { cart.getMap().remove(id); } }12345678910111213141516171819
Copy after login

在cn.itcast.web.controller下创建一个DeleteItemServlet类。
Shopping cart developed based on Servlet+JSP+JavaBean
DeleteItemServlet类的具体代码如下:

public class DeleteItemServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); Cart cart = (Cart) request.getSession().getAttribute("cart"); BusinessService service = new BusinessService(); service.deleteCartItem(id, cart); // 删除成功,还是跳转到listcart.jsp页面 request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }123456789101112131415161718192021
Copy after login

注意:我上面的代码使用的是请求转发,这依然是不行的,读者要注意了啊!仍然要使用请求重定向,考虑到这毕竟不是一个真实项目,所以尽量不要搞得那么复杂,一切从简。
在购物车显示页面listcart.jsp中还要写入以下JavaScript代码:

123456789
Copy after login

不然的话,用户手贱,不小心删除了所选的购物项,辛辛苦苦购买的商品又要重新购买,用户的感受肯定巨不爽,所以在用户不小心删除了所选的购物项时,还要问用户是否确认删除。只有用户点击确认按钮才会删除,这样对用户来说,体验会更好。
至此,删除购物车中购物项的功能就算是开发完成了!下面测试一下开发好的该功能:
Shopping cart developed based on Servlet+JSP+JavaBean

开发清空购物车的功能

编写实现如下业务服务的BusinessService类。

  • 清空购物车

编写对应的清空购物车的方法时,由于代表用户购物车的Cart类存在session中,是不是可以像下面这样写呢?

public void clearCart(HttpSession session) { ... }123
Copy after login

答:不可以。业务逻辑层用到Web层对象——session,业务逻辑层和Web层牢牢绑定在一起了,业务逻辑层离开Web层就跑不起来了,如果这样写,若要对业务层进行测试,需要把Web服务器起起来,传一个session进去,所以在各层之间传递的只能是JavaBean,不能让Web层的特殊对象侵入到业务逻辑层,污染业务逻辑层
此时BusinessService类的具体代码如下:

// 业务类,统一对web层提供所有服务public class BusinessService { private BookDao dao = new BookDao(); public Map getAllBook() { return dao.getAll(); } public Book findBook(String id) { return dao.find(id); } // 删除购物车中购物项 public void deleteCartItem(String id, Cart cart) { cart.getMap().remove(id); } // 清空购物车 public void clearCart(Cart cart) { cart.getMap().clear(); } }123456789101112131415161718192021222324
Copy after login

在cn.itcast.web.controller包下创建一个ClearCartServlet类。
Shopping cart developed based on Servlet+JSP+JavaBean
ClearCartServlet类的具体代码如下:

public class ClearCartServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cart cart = (Cart) request.getSession().getAttribute("cart"); BusinessService service = new BusinessService(); service.clearCart(cart); request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }12345678910111213141516171819
Copy after login

注意:我上面的代码使用的是请求转发,这依然是不行的,读者要注意了啊!仍然要使用请求重定向,考虑到这毕竟不是一个真实项目,所以尽量不要搞得那么复杂,一切从简。
在购物车显示页面listcart.jsp中还要写入以下JavaScript代码:

12345678
Copy after login

不然的话,用户手贱,不小心清空了购物车,辛辛苦苦购买的商品又要重新购买,用户的感受肯定巨不爽,所以在用户不小心清空了购物车时,还要问用户是否确认清空。只有用户点击确认按钮才会清空,这样对用户来说,体验会更好。
还有一点要注意:如果用户清空了购物车,那么购物车显示页面不能没有任何显示,这也是对用户体验的一种折磨,明智的做法应该是给用户显示您没有购买任何商品!!!,这样用户体验会更好。那怎样判断用户有没有购买商品呢?——可使用el表达式的函数:empty(object),检测object对象是否为null或”“,若是则返回true。这样购物车显示页面listcart.jsp页面中的关键代码如下:

购物车列表

您没有购买任何商品!!! ...12345678
Copy after login

至此,清空购物车的功能就算是开发完成了!下面测试一下开发好的该功能:
Shopping cart developed based on Servlet+JSP+JavaBean

开发改变购物车某购物项数量的功能

在现实中的购物中,当用户购买一件商品时,发现还需要购买这件商品,比如数量为100,用户不可能点击这件商品100次,若是这样,那这样的购物网站倒闭1万亿遍了。所以一般来说用户只需要改变其数量即可,这时就需要用到控件,而且用户要输入的数量要是一个正整数,不能是其他乱七八糟的东西。
编写实现如下业务服务的BusinessService类。

  • 改变购物车某购物项的数量

此时BusinessService类的具体代码如下:

// 业务类,统一对web层提供所有服务public class BusinessService { private BookDao dao = new BookDao(); public Map getAllBook() { return dao.getAll(); } public Book findBook(String id) { return dao.find(id); } // 删除购物车中购物项 public void deleteCartItem(String id, Cart cart) { cart.getMap().remove(id); } // 清空购物车 public void clearCart(Cart cart) { cart.getMap().clear(); } // 改变购物车某购物项的数量 public void changeItemQuantity(String id, String quantity, Cart cart) { CartItem item = cart.getMap().get(id); item.setQuantity(Integer.parseInt(quantity)); } }123456789101112131415161718192021222324252627282930
Copy after login

在cn.itcast.web.controller中创建ChangeQuantityServlet类。
Shopping cart developed based on Servlet+JSP+JavaBean
ChangeQuantityServlet类的具体代码如下:

// 把购物车中的书修改为指定数量public class ChangeQuantityServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); String quantity = request.getParameter("quantity"); Cart cart = (Cart) request.getSession().getAttribute("cart"); BusinessService service = new BusinessService(); service.changeItemQuantity(id, quantity, cart); request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }1234567891011121314151617181920212223
Copy after login

注意:我上面的代码使用的是请求转发,这依然是不行的,读者要注意了啊!仍然要使用请求重定向,考虑到这毕竟不是一个真实项目,所以尽量不要搞得那么复杂,一切从简。
在购物车显示页面listcart.jsp中还要写入以下JavaScript代码:

1234567891011121314151617
Copy after login

完整的购物车显示页面listcart.jsp代码前面已经给出了,这里不再赘写。
至此,改变购物车某购物项数量的功能就算是开发完成了!下面测试一下开发好的该功能:
Shopping cart developed based on Servlet+JSP+JavaBean

##1 cn.itcast.DB Store the class representing the database 2 cn.itcast.domain Stores the system's JavaBean class (only contains simple attributes and get properties corresponding to them) and set method (excluding specific business processing methods), provided to [Data Access Layer], [Business Logic Layer], [Web Layer] to use domain (domain model) layer 3 cn.itcast.dao Store the implementation class of the operation interface for accessing the database Data access layer 4 cn.itcast.service Store the implementation class of the business interface of the processing system Business logic layer 5 cn.itcast.web.controller Stores the Servlet as the system controller (servlet that handles requests) Web layer (presentation layer) 6 cn.itcast.web.UI Provide user interface to users. Because in the strict MVC mode, jsp is protected and direct access from the outside is prohibited. If a user wants to register, he needs to get a form page and use a servlet to transfer to the jsp. Some servlets are designed to provide users with a user interface, and That is to say, in actual development, some servlets are used to process requests, and some servlets are specially used to receive requests and then transfer to jsp to provide users with user interfaces Web layer (presentation layer) 7 cn.itcast.utils Stores the system’s general tool classes, which are provided to the [Data Access Layer], [Business Logic Layer], and [Web Layer] 】To use
Serial number Package name Description Affiliated level


The above is the detailed content of Shopping cart developed based on Servlet+JSP+JavaBean. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!