@RequestParam

你可以使用 @RequestParam 注解将 Servlet 请求参数(即查询参数或表单数据)绑定到控制器中的方法参数。

You can use the @RequestParam annotation to bind Servlet request parameters (that is, query parameters or form data) to a method argument in a controller.

以下示例演示了如何执行此操作:

The following example shows how to do so:

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 to bind petId.
Kotlin
import org.springframework.ui.set

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

	// ...

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

	// ...

}
2 Using @RequestParam to bind petId.

默认情况下,使用此注解的方法参数是必需的,但可以通过将 @RequestParam 注解的 required 标志设置为 false 或使用 java.util.Optional 包装器声明参数来指定方法参数是可选的。

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

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

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

将参数类型声明为数组或列表允许解析同一参数名称的多个参数值。

Declaring the argument type as an array or list allows for resolving multiple parameter values for the same parameter name.

当将 @RequestParam 注解声明为 Map<String, String>MultiValueMap<String, String>,而未在注解中指定参数名称时,该映射会使用给定每个参数名称的请求参数值进行填充。

When an @RequestParam annotation is declared as a Map<String, String> or MultiValueMap<String, String>, without a parameter name specified in the annotation, then the map is populated with the request parameter values for each given parameter name.

请注意,@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.