对于最新的稳定版本,请使用 Spring Framework 6.2.4spring-doc.cadn.net.cn

@RequestParam

您可以使用@RequestParam注解绑定 Servlet 请求参数(即 查询参数或表单数据)添加到控制器中的方法参数。spring-doc.cadn.net.cn

以下示例显示了如何执行此作:spring-doc.cadn.net.cn

@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 @RequestParam绑定petId.
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"
	}

	// ...

}
1 Using @RequestParam to bind petId.

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.spring-doc.cadn.net.cn

Type conversion is automatically applied if the target method parameter type is not String. See Type Conversion.spring-doc.cadn.net.cn

Declaring the argument type as an array or list allows for resolving multiple parameter values for the same parameter name.spring-doc.cadn.net.cn

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.spring-doc.cadn.net.cn

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.spring-doc.cadn.net.cn