携带表单错误重定向
类似 laravel 的 return back ()->withErrors ([‘name’ => ‘必须填写’]) 实现方案
如果你希望在表单验证失败时执行重定向,同时保留错误信息和用户输入的数据,由于 HTTP 协议的无状态特性,直接通过重定向传递复杂数据(如错误信息和表单数据)并不直接支持。但是,你可以使用以下几种策略来实现这一需求:
1. 使用 Flash Attributes#
Spring 提供了 RedirectAttributes
来允许你在重定向之前存储一些临时数据(称为 flash attributes),这些数据可以在重定向后的请求中访问。
示例代码#
控制器#
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class FormController {
// 显示表单页面
@GetMapping("/form")
public String showForm(Model model) {
return "form-page"; // 指向你的 Thymeleaf 页面名
}
// 处理表单提交
@PostMapping("/submit")
public String handleFormSubmit(
@RequestParam("name") String name,
@RequestParam("email") String email,
RedirectAttributes redirectAttributes) {
boolean hasError = false;
if (name == null || name.trim().isEmpty()) {
redirectAttributes.addFlashAttribute("nameError", "姓名不能为空");
hasError = true;
}
if (email == null || !email.contains("@")) {
redirectAttributes.addFlashAttribute("emailError", "邮箱格式不正确");
hasError = true;
}
// 如果有错误,重定向回表单页面并携带错误信息
if (hasError) {
redirectAttributes.addFlashAttribute("oldName", name);
redirectAttributes.addFlashAttribute("oldEmail", email);
return "redirect:/form";
}
// 成功处理逻辑
return "redirect:/success";
}
}
Thymeleaf 页面 (form-page.html
)#
为了显示错误信息和旧值,Thymeleaf 页面需要稍微调整以适应从 flash attributes 获取数据的方式。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>表单提交</title>
</head>
<body>
<h2>用户注册</h2>
<!-- 显示错误 -->
<div th:if="${flash.nameError}" style="color:red" th:text="${flash.nameError}"></div>
<div th:if="${flash.emailError}" style="color:red" th:text="${flash.emailError}"></div>
<!-- 表单 -->
<form method="post" action="/submit">
<label for="name">姓名:</label><br/>
<input type="text" id="name" name="name" th:value="${flash.oldName}"/><br/><br/>
<label for="email">邮箱:</label><br/>
<input type="text" id="email" name="email" th:value="${flash.oldEmail}"/><br/><br/>
<button type="submit">提交</button>
</form>
</body>
</html>
注意,在 Thymeleaf 中,flash attributes 是自动添加到模型中的,并且可以通过 ${flash}
访问。
2. 使用 Session#
另一种方法是将错误信息和旧表单数据暂时存储在 session 中。这种方法不如使用 flash attributes 直观,但在某些情况下可能是必要的。
总结#
- Flash Attributes 是 Spring 提供的一种机制,用于在重定向过程中传递临时数据。
- 在控制器中,当验证失败时,可以使用
RedirectAttributes
添加 flash attributes 并执行重定向。 - 在前端模板引擎(如 Thymeleaf)中,可以通过特定的方式访问这些 flash attributes 来显示错误信息和恢复表单数据。
这种方式可以让你在表单验证失败后重定向回到表单页面,并同时显示错误信息和保留用户的输入。