|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
@RequestParam
您可以使用@注解将查询参数绑定到控制器方法参数。以下代码片段展示了使用方法:
-
Java
-
Kotlin
@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。 |
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"
}
// ...
}
| 1 | 使用 @RequestParam。 |
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. |
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。请参见类型转换。
当一个@RequestParam注解被声明在Map<String, String>或
MultiValueMap<String, String>参数上时,该映射将填充所有查询参数。
请注意,使用 @RequestParam 是可选的——例如,设置其属性。默认情况下,任何简单值类型(由 BeanUtils#isSimpleProperty 确定)且未被任何其他参数解析器解析的参数将被视为带有 @RequestParam 注解。