@RequestParam

您可以使用 @RequestParam 注解将查询参数绑定到控制器中的方法参数。以下代码段展示了用法:

You can use the @RequestParam annotation to bind query parameters to a method argument in a controller. The following code snippet shows the usage:

Java
@Controller
@RequestMapping("/pets")
public class EditPetForm {

	// ...

	@GetMapping
	public String setupForm(@RequestParam("petId") int petId, Model model) { 1
		Pet pet = this.clinic.loadPet(petId);
		model.addAttribute("pet", pet);
		return "petForm";
	}

	// ...
}
1 Using @RequestParam.
Kotlin
import org.springframework.ui.set

@Controller
@RequestMapping("/pets")
class EditPetForm {

	// ...

	@GetMapping
	fun setupForm(@RequestParam("petId") petId: Int, model: Model): String { (1)
		val pet = clinic.loadPet(petId)
		model["pet"] = pet
		return "petForm"
	}

	// ...
}
2 Using @RequestParam.

Servlet API “request parameter” 概念将查询参数、表单数据和多部分合并为一个。但是,在 WebFlux 中,每个部分都是通过 ServerWebExchange 单独访问的。虽然 @RequestParam 仅绑定到查询参数,但可以使用数据绑定将查询参数、表单数据和多部分应用于 command object

The Servlet API “request parameter” concept conflates query parameters, form data, and multiparts into one. However, in WebFlux, each is accessed individually through ServerWebExchange. While @RequestParam binds to query parameters only, you can use data binding to apply query parameters, form data, and multiparts to a command object.

默认情况下,使用 @RequestParam 注解的方法参数是必需的,但您可以通过将 @RequestParam 的必填标志设为 false 或声明一个采用 java.util.Optional 封装器类型的自变量来指定方法参数是可选的。

Method parameters that use the @RequestParam annotation are required by default, but you can specify that a method parameter is optional by setting the required flag of a @RequestParam to false or by declaring the argument with a java.util.Optional wrapper.

如果目标方法参数类型不是 String,则会自动应用类型转换。请参阅 Type Conversion

Type conversion is applied automatically if the target method parameter type is not String. See Type Conversion.

当在 Map<String, String>MultiValueMap<String, String> 自变量上声明 @RequestParam 注解时,地图将填充所有查询参数。

When a @RequestParam annotation is declared on a Map<String, String> or MultiValueMap<String, String> argument, the map is populated with all query parameters.

请注意,使用 @RequestParam 是可选的,例如,设置其属性。 默认情况下,任何简单值类型的参数(根据 BeanUtils#isSimpleProperty 确定),并且并未通过任何其他参数解析器解析,都将视为用 @RequestParam 注释。

Note that use of @RequestParam is optional — for example, to set its attributes. By default, any argument that is a simple value type (as determined by BeanUtils#isSimpleProperty) and is not resolved by any other argument resolver is treated as if it were annotated with @RequestParam.