Spring MVC 接收请求参数的方式包括:
-
请求参数直接映射到 Controller 方法的参数。例如:
@RequestMapping("/hello") public String hello(String name, Integer age) {// ... }
-
通过
@RequestParam
注解指定参数名和是否必须的方式接收请求参数。例如:@RequestMapping("/hello") public String hello(@RequestParam("name") String username, @RequestParam(required = false) Integer age) {// ... }
-
通过
@PathVariable
注解获取 URL 中的参数。例如:@RequestMapping("/hello/{name}") public String hello(@PathVariable String name) {// ... }
-
通过
@ModelAttribute
注解将请求参数绑定到一个 Java 对象上。例如:@RequestMapping("/hello") public String hello(@ModelAttribute User user) {// ... }
-
通过
@RequestBody
注解将请求体中的 JSON 数据绑定到一个 Java 对象上。例如:@RequestMapping(value = "/hello", method = RequestMethod.POST) public String hello(@RequestBody User user) {// ... }
-
在 Controller 中通过
HttpServletRequest
或MultipartHttpServletRequest
对象获取请求参数。例如:@RequestMapping(value = "/upload", method = RequestMethod.POST) public void upload(HttpServletRequest request) {MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;// ... }