@SessionAttributes 多个步骤订单表单业务案例
SessionAttributes
注解它用于指定哪些模型属性应该被存储在 HTTP 会话(Session)中。这对于在多个请求之间保持数据状态非常有用,尤其是在表单提交和数据回显的场景中。
业务说明:
考虑一个在线购物平台,用户需要填写一个包含多个步骤的订单表单。这个表单可能包括用户信息、收货地址、支付方式等部分。我们希望用户在填写过程中,即使在不同页面间跳转,之前填写的信息也能够被保留。
1. 定义订单表单的数据模型:
public class OrderForm {
private String customerName;
private String shippingAddress;
private PaymentMethod paymentMethod;
// 标准的 getter 和 setter
}
public enum PaymentMethod {
CREDIT_CARD, PAYPAL, BANK_TRANSFER
}
2. 创建控制器使用 @SessionAttributes
注解:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
@Controller
@SessionAttributes("orderForm") // 将 OrderForm 存储在会话中
public class OrderController {
@GetMapping("/order")
public ModelAndView showOrderForm(Model model) {
model.addAttribute("orderForm", new OrderForm());
return new ModelAndView("orderForm");
}
@PostMapping("/order/customer")
public String submitCustomerInfo(@ModelAttribute("orderForm") OrderForm orderForm, RedirectAttributes redirectAttributes) {
// 保存客户信息到数据库或其他存储
redirectAttributes.addFlashAttribute("orderForm", orderForm);
return "redirect:/order/shipping";
}
@GetMapping("/order/shipping")
public String showShippingForm(Model model) {
model.addAttribute("orderForm", model.asMap().get("orderForm"));
return "shippingForm";
}
@PostMapping("/order/payment")
public String submitPaymentInfo(@ModelAttribute("orderForm") OrderForm orderForm, SessionStatus status) {
// 处理支付信息
status.setComplete(); // 清除会话中的 OrderForm
return "paymentResult";
}
}
3. 创建表单的 HTML 页面:
orderForm.html - 客户信息表单:
<form action="/order/customer" method="post">
<label for="customerName">Customer Name:</label>
<input type="text" id="customerName" name="customerName" required>
<button type="submit">Continue</button>
</form>
shippingForm.html - 收货地址表单:
<form action="/order/shipping" method="post">
<label for="shippingAddress">Shipping Address:</label>
<input type="text" id="shippingAddress" name="shippingAddress" required>
<button type="submit">Continue</button>
</form>
paymentForm.html - 支付信息表单:
<form action="/order/payment" method="post">
<label for="paymentMethod">Payment Method:</label>
<select id="paymentMethod" name="paymentMethod" required>
<option value="CREDIT_CARD">Credit Card</option>
<option value="PAYPAL">PayPal</option>
<option value="BANK_TRANSFER">Bank Transfer</option>
</select>
<button type="submit">Submit Payment</button>
</form>
4. 处理表单提交:
在每个步骤中,表单数据被提交并通过 @ModelAttribute
绑定到 OrderForm
对象。使用 RedirectAttributes
在重定向后保留数据,然后在后续步骤中从会话中恢复数据。
总结:
@SessionAttributes
使得在用户完成多步骤流程时,可以在不同请求之间保持表单状态。- 它简化了表单处理的代码,特别是对于跨多个页面的表单。
- 通过使用
SessionStatus
,可以在完成表单处理后清理会话,避免不必要的数据保留。
转载自:https://juejin.cn/post/7382537293582549018