Java Shopping Cart Implementation Using Cookies, Redis, and Spring MVC
This article explains how to implement a shopping cart in Java by handling four login scenarios, defining BuyerCart and BuyerItem beans, using JavaScript and Spring MVC controllers to add items, persisting cart data in cookies or Redis, converting objects to JSON with ObjectMapper, managing sessions, and validating stock before checkout.
Introduction: The article discusses four scenarios of a shopping cart based on user login status and browser behavior, using a JD.com template.
Data model: Two JavaBean classes, BuyerCart and BuyerItem , are defined. BuyerCart holds a list of BuyerItem objects and provides methods for adding items, calculating totals, and JSON‑ignore fields. BuyerItem contains a Sku , quantity, and availability flag, with proper equals and hashCode implementations.
Adding items: A JavaScript function addCart() builds a URL with skuId and amount . The Spring MVC controller method buyerCart(...) reads the existing cart from a cookie, creates a new cart if absent, adds the selected SKU, sorts items, and then either stores the cart in Redis (if the user is logged in) or writes it back to a cookie (if not logged in).
JSON conversion: The article shows how to use ObjectMapper with Include.NON_NULL to serialize objects to JSON strings and deserialize them back, demonstrating the process with a test class.
Session handling: A utility RequestUtils.getCSessionId() retrieves or creates a CSESSIONID cookie. SessionProviderService.getAttributterForUsername() fetches the username from Redis and refreshes its expiration.
Persisting the cart: insertBuyerCartToRedis() stores each SKU’s quantity in a Redis hash, merging quantities for duplicate SKUs. selectBuyerCartFromRedis() reconstructs a BuyerCart from the Redis hash.
Cart display: The toCart() controller loads the cart from cookie or Redis, fills each BuyerItem with full Sku details (color, product), and returns the “cart” view.
Checkout validation: The trueBuy() endpoint requires a logged‑in user, extracts the selected SKUs, verifies stock availability, and either returns the cart view with out‑of‑stock flags or proceeds to the order page.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.