Spring文档中重定向URL所有model属性作为URI模板变量暴露的含义是什么?
Spring重定向时Model属性暴露为URI模板变量的含义及实例
核心含义解读
all model attributes are considered to be exposed as URI template variables in the redirect URL
这是Spring MVC处理重定向逻辑的默认规则,直白来说就是:当Controller返回重定向地址时,Model中存储的所有属性会优先填充重定向URL中的占位符,未匹配到占位符的剩余属性会自动作为查询参数拼接在重定向URL末尾,不需要开发者手动拼接参数。
实际开发场景示例
场景1:基础重定向参数传递
比如常见的订单创建后跳转到订单详情页的需求,Controller代码如下:
@GetMapping("/generateOrder") public String generateOrder(Model model) { // 模拟业务逻辑生成订单 Long orderId = 2024001L; String payStatus = "paid"; // 属性存入Model model.addAttribute("orderId", orderId); model.addAttribute("status", payStatus); // 返回带占位符的重定向地址 return "redirect:/order/detail/{orderId}"; }
此时Spring会自动做两个处理:
- 用Model中的
orderId值2024001填充URL中的{orderId}占位符,得到路径/order/detail/2024001 - 剩余未匹配占位符的
status属性自动作为查询参数拼接,最终用户实际被重定向到的完整地址为:/order/detail/2024001?status=paid
场景2:敏感参数不暴露的处理方案
如果要传递的参数不适合出现在URL中(比如操作提示、敏感业务字段),可以用RedirectAttributes的addFlashAttribute方法规避自动暴露逻辑,Flash属性会临时存储在Session中,重定向完成后自动清除,不会出现在URL里:
@PostMapping("/submitPay") public String submitPay(RedirectAttributes redirectAttributes) { Long orderId = 2024002L; // addAttribute存储的属性还是会暴露到URL redirectAttributes.addAttribute("orderId", orderId); // addFlashAttribute存储的属性不会暴露到URL redirectAttributes.addFlashAttribute("tip", "支付成功,我们将在1小时内为您发货"); return "redirect:/pay/result/{orderId}"; } // 重定向后的目标接口可以直接获取Flash属性 @GetMapping("/pay/result/{orderId}") public String payResult(@PathVariable Long orderId, @ModelAttribute("tip") String tip, Model model) { model.addAttribute("orderId", orderId); model.addAttribute("tip", tip); return "payResult"; }
该场景下最终重定向地址为/pay/result/2024002,tip参数不会出现在URL中,同时目标页面可以正常拿到提示内容。
注意事项
- 该规则仅在返回
redirect:开头的重定向视图时生效,返回普通视图时不会触发 - 自动拼接的参数Spring会自动做URL转义处理,不需要开发者手动处理特殊字符
- 如果需要关闭自动暴露Model属性的逻辑,可以配置
RequestMappingHandlerAdapter的ignoreDefaultModelOnRedirect属性为true
内容的提问来源于stack exchange,提问作者javaway
相关产品推荐
相关产品推荐

