Post-Redirect-Get(PRG)是一种Web开发设计模式,用于解决表单重复提交问题。当用户提交表单(POST请求)后,服务器不是直接返回响应页面,而是返回一个重定向响应(302/303),让浏览器发起一个新的GET请求来获取结果页面。
@Controller
public class FormController {
@PostMapping("/submitForm")
public String handleFormSubmission(FormData formData, RedirectAttributes redirectAttributes) {
// 处理表单数据
String result = processForm(formData);
// 将结果添加到重定向属性中
redirectAttributes.addFlashAttribute("result", result);
// 重定向到结果页面
return "redirect:/resultPage";
}
@GetMapping("/resultPage")
public String showResultPage() {
return "result";
}
}
RedirectAttributes
是Spring提供的特殊接口,用于在重定向时传递数据:
addAttribute()
:将参数作为URL查询参数传递addFlashAttribute()
:将参数存储在会话中,重定向后自动移除原因:直接使用Model属性在重定向时会丢失
解决:使用RedirectAttributes
的addFlashAttribute()
原因:重定向目标路径配置错误 解决:检查重定向路径是否正确,确保不是指向自身
// 错误示例 - 会导致循环
@PostMapping("/submit")
public String handleSubmit() {
return "redirect:/submit";
}
// 正确示例
@PostMapping("/submit")
public String handleSubmit() {
return "redirect:/result";
}
原因:使用addAttribute()
会暴露参数在URL中
解决:敏感数据使用addFlashAttribute()
,非敏感数据可保留在URL中
原因:可能缺少必要的配置
解决:确保已配置<mvc:annotation-driven/>
或@EnableWebMvc
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
String fileId = fileService.store(file);
redirectAttributes.addFlashAttribute("message", "上传成功!");
return "redirect:/files/" + fileId;
}
@PostMapping("/checkout")
public String processCheckout(Order order, RedirectAttributes redirectAttributes) {
String orderId = orderService.process(order);
redirectAttributes.addFlashAttribute("orderId", orderId);
return "redirect:/orderConfirmation";
}
测试PRG模式时应注意:
PRG模式是Spring MVC中处理表单提交的最佳实践之一,能有效提升Web应用的健壮性和用户体验。
没有搜到相关的文章