Redirect Attributes

默认情况下,所有模型属性都被视为在重定向 URL 中作为 URI 模板变量公开。在剩余的属性中,基本类型或基本类型的集合或数组会自动作为查询参数附加。

By default, all model attributes are considered to be exposed as URI template variables in the redirect URL. Of the remaining attributes, those that are primitive types or collections or arrays of primitive types are automatically appended as query parameters.

如果模型实例专门为重定向而准备,那么将基本类型属性作为查询参数附加可能是期望的结果。但是,在带注释的控制器中,模型可以包含为渲染目的添加的其他属性(例如,下拉字段值)。为了避免出现此类属性在 URL 中的情况,@RequestMapping 方法可以声明 RedirectAttributes 类型的参数并使用它来指定要提供给 RedirectView 的确切属性。如果方法确实重定向,则将使用 RedirectAttributes 的内容。否则,将使用模型的内容。

Appending primitive type attributes as query parameters can be the desired result if a model instance was prepared specifically for the redirect. However, in annotated controllers, the model can contain additional attributes added for rendering purposes (for example, drop-down field values). To avoid the possibility of having such attributes appear in the URL, a @RequestMapping method can declare an argument of type RedirectAttributes and use it to specify the exact attributes to make available to RedirectView. If the method does redirect, the content of RedirectAttributes is used. Otherwise, the content of the model is used.

RequestMappingHandlerAdapter 提供了一个名为 ignoreDefaultModelOnRedirect 的标记,你可以使用它来指示如果控制器方法重定向则永远不应使用默认的 Model 的内容。相反,控制器方法应该声明 RedirectAttributes 类型的属性,或者,如果没有这样做,则不应将任何属性传递给 RedirectView。MVC 命名空间和 MVC Java 配置都将此标记设置为 false,以保持向后兼容性。但是,对于新应用程序,我们建议将其设置为 true

The RequestMappingHandlerAdapter provides a flag called ignoreDefaultModelOnRedirect, which you can use to indicate that the content of the default Model should never be used if a controller method redirects. Instead, the controller method should declare an attribute of type RedirectAttributes or, if it does not do so, no attributes should be passed on to RedirectView. Both the MVC namespace and the MVC Java configuration keep this flag set to false, to maintain backwards compatibility. However, for new applications, we recommend setting it to true.

请注意当展开重定向 URL 时,当前请求的 URI 模板变量会自动变为可用,不需要通过 ModelRedirectAttributes 显式添加它们。以下示例演示如何定义重定向:

Note that URI template variables from the present request are automatically made available when expanding a redirect URL, and you don’t need to explicitly add them through Model or RedirectAttributes. The following example shows how to define a redirect:

  • Java

  • Kotlin

@PostMapping("/files/{path}")
public String upload(...) {
	// ...
	return "redirect:files/{path}";
}
@PostMapping("/files/{path}")
fun upload(...): String {
	// ...
	return "redirect:files/{path}"
}

另一种方式是通过使用闪存属性将数据传递给重定向目标。与其他重定向属性不同的是,闪存属性保存在 HTTP 会话中(因此不会出现在 URL 中)。有关详细信息,请参阅 Flash Attributes

Another way of passing data to the redirect target is by using flash attributes. Unlike other redirect attributes, flash attributes are saved in the HTTP session (and, hence, do not appear in the URL). See Flash Attributes for more information.