在Spring MVC中,当需要重定向(Redirect)时传递参数给Thymeleaf视图,可以通过以下几种方式实现。以下是详细说明、示例代码和应用场景分析:
RedirectAttributes
这是Spring MVC推荐的方式,通过RedirectAttributes
对象添加参数,参数会自动附加到重定向URL后(作为查询参数),或在Flash属性中临时存储。
@Controller
public class MyController {
@GetMapping("/source")
public String redirectWithParams(RedirectAttributes redirectAttributes) {
// 方式1:通过URL查询参数传递(暴露在URL中)
redirectAttributes.addAttribute("param1", "value1"); // 自动拼接到URL
// 方式2:通过Flash属性传递(临时存储,不暴露在URL)
redirectAttributes.addFlashAttribute("param2", "value2");
return "redirect:/target";
}
@GetMapping("/target")
public String target(@RequestParam(required = false) String param1,
Model model) {
// param1通过URL传递,param2通过Flash传递(自动添加到Model中)
return "target-view"; // Thymeleaf模板
}
}
target-view.html
):<p>URL参数: <span th:text="${param1}"></span></p>
<p>Flash参数: <span th:text="${param2}"></span></p>
addAttribute
:参数会以?param1=value1
形式出现在URL中,适合非敏感数据。addFlashAttribute
:参数存储在Session中,重定向后自动销毁,适合敏感数据或临时数据。直接拼接URL参数,适用于少量简单参数:
@GetMapping("/source")
public String redirectWithParams() {
return "redirect:/target?param1=value1¶m2=value2";
}
通过路径占位符传递参数:
@GetMapping("/source/{id}")
public String redirectWithPath(@PathVariable String id) {
return "redirect:/target/" + id;
}
@GetMapping("/target/{id}")
public String target(@PathVariable String id, Model model) {
model.addAttribute("id", id);
return "target-view";
}
<p>ID: <span th:text="${id}"></span></p>
<mvc:annotation-driven />
或@EnableWebMvc
。UriUtils.encode()
或手动编码:UriUtils.encode()
或手动编码:| 方式 | 适用场景 | 安全性 | 数据量限制 |
|------------------------|----------------------------------|------------------|----------------|
| RedirectAttributes
| 通用场景,支持复杂数据 | 中(URL暴露) | 受URL长度限制 |
| Flash属性 | 敏感数据或临时数据 | 高(Session存储)| 受Session大小 |
| 手动拼接URL | 简单参数、快速实现 | 低 | 严格限制 |
| Path变量 | RESTful风格URL | 中 | 无特殊限制 |
RedirectAttributes
的addFlashAttribute
传递敏感数据,addAttribute
传递普通参数。${param}
或模型属性访问参数,无需额外配置。没有搜到相关的文章