I have never been exposed to a shopping cart before, and I don’t know how to use a shopping cart, so I checked a lot of information and summarized the functional implementation of the shopping cart.
Query information and find three methods:
1. Use cookies to implement the shopping cart;
2. Use sessions to implement the shopping cart;
3. Use cookies and databases (shopping cart information persistence) to implement the shopping cart;
================================================== =========================
Analyze the advantages and disadvantages of these three methods:
1. Simply use cookies to implement the shopping cart, like this The shopping cart is not very ideal. Imagine if the client's browser disables cookies,
This method will fail here...
Save the shopping cart information in 2.session. This is only in one session. Available in, if the user adds a shopping cart without logging in, or after logging in, after closing the browser
or logging out, all the shopping carts added before will be aborted...
3. What I want to say here This is the method...
Main process:
A. Data flow before user login: When the user adds the items he likes to the shopping cart without logging in to the system, then at this time, we can Save the shopping cart information to cookies, which will involve adding and modifying cookies; that is, if the corresponding cookie does not exist in the cookie before, the cookie will be added.
If there is a corresponding cookie in the cookie, then at this time, the cookie needs to be modified (this involves the situation where the user adds the same product to the shopping cart multiple times).
B. Data flow after the user logs in: After the user logs in, the first thing the system does is to obtain the corresponding cookies. If there are relevant shopping cart cookies, then the shopping cart
information will be processed accordingly. The persistence operation of User is either adding or modifying. (Add operation: If the shopping cart corresponding to the user does not have corresponding information, add the operation; Modify operation: Similarly,
If there is shopping cart information corresponding to the user, perform the modification operation). After the user logs in, he can also add to the shopping cart. However, instead of adding it to the cookie, it is directly persisted to the
database. Note: The data after the user logs in is dealt with the database.
================================================== =========================
Code part:
================== ================================================== =====
Note:
1 Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME = "iduona_cashTicket_";
/** * 用户登录 * * @author hongten */ public void login() { //用户登录的时候,去读取cookies,并且进行持久话操作,更多的登录操作这里省略啦.... peristShoppingCartWhenUserLogin(newUser); } /** * 加入购物车<br> * ============================================<br> * 用户登录前:<br> * 用户在选择现金券的时候,点击现金券的加入购物车的时候,会把该现金券的信息(现金券的id,购买数量)<br> * 传递到这里,这时候,后台要做的就是从cookie中查询出是否有相同的记录,如果有相同的记录<br> * 则把相应的记录更新;否则,就添加新的记录<br> * 用户登录后:<br> * 用户在登录后,如果有添加购物车操作,则不用保存到cookie中,而是直接持久化购物车信息<br> * * @throws Exception */ public void addToShoppingCart() throws Exception { if (cashTicket == null || cashTicket.getId() == null || cashTicket.getId() < 1) { write("nullId"); } else if (q == null || q == "") { // 购买数量,默认情况下面为1 q = String.valueOf(1); } else { // 读取所有的cookie Cookie cookies[] = ServletActionContext.getRequest().getCookies(); if (cookies == null || cookies.length < 0) { // 没有cookie System.out.println("there is no any cookie .."); } else { // 判断用户是否登录 if (getUserInSession() == null) { boolean flag = true; for (Cookie c : cookies) { if (c.getName().equals(Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME + cashTicket.getId())) { // 说明已有的cookies中有相应的cookie,就进行更新操作 Integer oldValue = Integer.valueOf(c.getValue()); Integer newValue = Integer.valueOf(oldValue + Integer.valueOf(q)); fixCookie(c, newValue.toString().trim()); flag = false; } } // 说明已有的cookies中没有相应的cookie,就进行添加操作 if (flag) { addCookie(Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME + cashTicket.getId(), q.trim()); } // ================================================== // 测试用,读取所有的cookies readShoppingCartFromCookie(); // ================================================== write("success"); } else { // 如果用户登录,说明session存在user,这时就持久化购物车信息 CashTicket cashTicketTemp = cashTicketService.get(cashTicket.getId()); if (shoppingCartService.isExistUserAndCashTicket(getUserInSession(), cashTicketTemp)) { ShoppingCart oldShoppingCart = shoppingCartService.getByUserAndCashTicket(getUserInSession(), cashTicketTemp); oldShoppingCart.setAmount(oldShoppingCart.getAmount() + Integer.valueOf(q)); if (shoppingCartService.update(oldShoppingCart)) { write("success"); } } else { ShoppingCart shoppingCartTemp = new ShoppingCart(); shoppingCartTemp.setAmount(Integer.valueOf(q)); shoppingCartTemp.setUser(getUserInSession()); shoppingCartTemp.setCashTicket(cashTicketTemp); shoppingCartTemp.setCreateTime(new Date()); shoppingCartTemp.setStatusType(StatusType.POSITIVE); shoppingCartTemp.setUuid(UUID.randomUUID().toString()); if (shoppingCartService.save(shoppingCartTemp)) { write("success"); } } } } } } /** * 从cookie中读取购物车信息 * * @throws Exception * @return */ public void readShoppingCartFromCookie() throws Exception { System.out.println("======================================================"); Cookie cookies[] = ServletActionContext.getRequest().getCookies(); if (cookies == null || cookies.length < 0) { // System.out.println("there is no any cookie .."); // 没有cookie } else { for (Cookie c : cookies) { System.out.println("haha there are many cookies :" + c.getName() + " " + c.getValue()); } } } /** * 添加cookie操作 * * @param name * cookie的name * @param value * cookie的value */ public void addCookie(String name, String value) { Cookie cookie = new Cookie(name.trim(), value.trim()); cookie.setMaxAge(2 * 60 * 60 * 1000);// 设置为2个钟 ServletActionContext.getResponse().addCookie(cookie); } /** * 更新cookie操作 * * @param c * 要修改的cookie * @param value * 修改的cookie的值 */ public void fixCookie(Cookie c, String value) { c.setValue(value.trim()); c.setMaxAge(2 * 60 * 60 * 1000);// 设置为2个钟 ServletActionContext.getResponse().addCookie(c); } /** * 当用户登录的时候,持久化cookie中的购物车信息,更新为本用户的购物车信息 */ public void peristShoppingCartWhenUserLogin(User user) { if (null != user) { Cookie cookies[] = ServletActionContext.getRequest().getCookies(); if (cookies != null) { for (Cookie c : cookies) { if (c.getName().startsWith(Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME)) { // 获取cookie的名称:"iduona_cashTicket_45" 和 cookie的值: "21" String name = c.getName(); Integer amount = Integer.valueOf(Integer.valueOf(c.getValue())+Integer.valueOf(q)); Integer ct_id = Integer.valueOf(name.substring(name.lastIndexOf("_") + 1)); CashTicket temp = cashTicketService.get(ct_id); ShoppingCart shoppingCartTemp = new ShoppingCart(); if (null != temp) { if (shoppingCartService.isExistUserAndCashTicket(user, temp)) { // 进行更新操作 ShoppingCart oldShoppingCart = shoppingCartService.getByUserAndCashTicket(user, temp); oldShoppingCart.setAmount(amount); shoppingCartService.update(oldShoppingCart); } else { // 否则进行保存记录 shoppingCartTemp.setAmount(amount); shoppingCartTemp.setUser(user); shoppingCartTemp.setCashTicket(temp); shoppingCartTemp.setCreateTime(new Date()); shoppingCartTemp.setStatusType(StatusType.POSITIVE); shoppingCartTemp.setUuid(UUID.randomUUID().toString()); shoppingCartService.save(shoppingCartTemp); } } } } // 移除所有的现金券cookies removeAllCookies(); } } } /** * 移除所有的现金券cookies操作 */ public void removeAllCookies() { Cookie cookies[] = ServletActionContext.getRequest().getCookies(); if (cookies == null || cookies.length < 0) { // 没有cookie System.out.println("there is no any cookie .."); } else { System.out.println("开始删除cookies.."); for (Cookie c : cookies) { if (c.getName().startsWith(Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME)) { c.setMaxAge(0);// 设置为0 ServletActionContext.getResponse().addCookie(c); } } } }
This is part of the code....
Effect:
If the user is not logged in
user After logging in:
The situation in the database:
Data before logging in
For more articles related to java web development_shopping cart function implementation, please pay attention to PHP Chinese website!

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
