JSP项目折扣功能实现求助:Spring MVC Controller类添加折扣码逻辑及JSP折扣实现方法咨询
Hey there! Let's get that discount code feature up and running for your pizza order Spring MVC app. I'll walk you through updating your controller first, then show you how to display the discounts in your JSP.
First, let's fix a couple small typos in your code (you wrote adress instead of address when adding the object to the model, and the class name had a typo: HomeContronller → HomeController—easy mistakes!). Then we'll add the discount code logic.
Here's the revised controller with full discount functionality:
package com.assignment; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class HomeController { // Define base pizza prices based on size (adjust these values to match your pricing!) private static final double SMALL_PRICE = 10.0; private static final double MEDIUM_PRICE = 15.0; private static final double LARGE_PRICE = 20.0; @RequestMapping("/order") public ModelAndView message(@RequestParam("name") String name, @RequestParam("email") String email, @RequestParam("pnumber") String pnumber, @RequestParam("address") String address, @RequestParam("pizztype") String pizzatype, @RequestParam("pizzasize") String pizzasize, @RequestParam("numpizza") String numpizza, @RequestParam(value = "discountCode", required = false) String discountCode) { ModelAndView m = new ModelAndView("page1"); // Add user input details to model (fixed the address typo!) m.addObject("name", name); m.addObject("email", email); m.addObject("pnumber", pnumber); m.addObject("address", address); m.addObject("pizzatype", pizzatype); m.addObject("pizzasize", pizzasize); m.addObject("numpizza", numpizza); // Calculate base pizza price based on size double basePrice = MEDIUM_PRICE; // Default to medium if size is invalid switch(pizzasize.toLowerCase()) { case "small": basePrice = SMALL_PRICE; break; case "large": basePrice = LARGE_PRICE; break; } // Handle number of pizzas (prevent crashes from non-numeric inputs) int numPizzas = 1; try { numPizzas = Integer.parseInt(numpizza); } catch (NumberFormatException e) { // If user enters non-numeric value, default to 1 pizza } // Calculate total before discount double totalBeforeDiscount = basePrice * numPizzas; // Determine discount rate based on code double discountRate = 0.0; if (discountCode != null) { switch(discountCode.trim()) { case "1111": discountRate = 0.10; // 10% off break; case "2222": discountRate = 0.30; // 30% off break; default: // No valid discount code entered discountRate = 0.0; } } // Calculate discount amounts and final total double discountAmount = totalBeforeDiscount * discountRate; double totalAfterDiscount = totalBeforeDiscount - discountAmount; // Add discount details to model for JSP display m.addObject("discountCode", discountCode); m.addObject("totalBeforeDiscount", totalBeforeDiscount); m.addObject("discountAmount", discountAmount); m.addObject("totalAfterDiscount", totalAfterDiscount); return m; } }
Key changes here:
- Fixed typos in class name and address object mapping
- Added an optional
discountCodeparameter - Added logic to calculate pizza prices based on size
- Added error handling for non-numeric pizza counts
- Calculated discount rates, discount amounts, and final totals
- Passed all discount-related data to the JSP via the model
Now we'll update your JSP to show the discount details. First, make sure you have the JSTL core taglib imported at the top of your JSP (we'll use it for conditional rendering):
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %>
Then, add the order confirmation and discount display section:
<html> <head> <title>Order Confirmation</title> <style> .order-details, .discount-section { margin: 20px 0; padding: 10px; border: 1px solid #ddd; } strong { color: #2c3e50; } </style> </head> <body> <h1>Your Pizza Order Confirmation</h1> <div class="order-details"> <p><strong>Name:</strong> ${name}</p> <p><strong>Email:</strong> ${email}</p> <p><strong>Phone:</strong> ${pnumber}</p> <p><strong>Address:</strong> ${address}</p> <p><strong>Pizza Type:</strong> ${pizzatype}</p> <p><strong>Pizza Size:</strong> ${pizzasize}</p> <p><strong>Number of Pizzas:</strong> ${numpizza}</p> </div> <hr> <!-- Discount Section --> <div class="discount-section"> <c:if test="${not empty discountCode and discountAmount > 0.0}"> <h3>✅ Discount Applied!</h3> <p><strong>Discount Code Used:</strong> ${discountCode}</p> <p>Total Before Discount: $${totalBeforeDiscount}</p> <p>Discount Amount: -$${discountAmount}</p> <h4><strong>Final Total: $${totalAfterDiscount}</strong></h4> </c:if> <c:if test="${empty discountCode or discountAmount == 0.0}"> <h3>Total</h3> <h4><strong>Final Total: $${totalBeforeDiscount}</strong></h4> <c:if test="${not empty discountCode}"> <p style="color: #e74c3c;">❌ Invalid discount code entered.</p> </c:if> </c:if> </div> </body> </html>
This will:
- Show all the user's order details in a clean format
- Conditionally display discount info only if a valid code was entered
- Show an error message if an invalid discount code is provided
- Highlight the final total for clarity
- Don't forget to add a discount code input field to your submission form:
<div> <label for="discountCode">Discount Code (Optional):</label> <input type="text" id="discountCode" name="discountCode" placeholder="Enter 1111 or 2222"> </div> - For better maintainability, you could move discount codes and pizza prices into a
application.propertiesfile instead of hardcoding them in the controller. - Consider adding server-side validation for the discount code (like showing an error message in the form if invalid) using Spring's validation features.
内容的提问来源于stack exchange,提问作者Scott Nguyen

