在 Spring MVC 里,处理请求参数绑定主要借助控制器方法的参数,Spring MVC 会自动把请求中的参数绑定到这些方法参数上。下面是几种常见的请求参数绑定方式以及对应的示例:
1. 基本类型参数绑定
基本类型参数绑定可直接把请求参数映射到控制器方法的基本类型参数上。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class BasicTypeBindingController {
@GetMapping("/basic")
@ResponseBody
public String basicBinding(@RequestParam("id") int id, @RequestParam("name") String name) {
return "ID: " + id + ", Name: " + name;
}
}
在上述代码中,@RequestParam
注解把请求中的 id
和 name
参数绑定到控制器方法的 id
和 name
参数上。
2. 实体类参数绑定
实体类参数绑定能把请求参数映射到一个实体类对象上,前提是请求参数名和实体类的属性名一致。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/entity")
public class EntityBindingController {
@GetMapping
@ResponseBody
public String entityBinding(User user) {
return "User ID: " + user.getId() + ", User Name: " + user.getName();
}
}
class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
在这个例子中,Spring MVC 会自动把请求中的 id
和 name
参数绑定到 User
对象的对应属性上。
3. 数组和集合参数绑定
数组和集合参数绑定可把请求中的多个同名参数绑定到控制器方法的数组或集合参数上。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class ArrayAndListBindingController {
@GetMapping("/array")
@ResponseBody
public String arrayBinding(@RequestParam("ids") int[] ids) {
StringBuilder result = new StringBuilder();
for (int id : ids) {
result.append(id).append(" ");
}
return "IDs: " + result.toString();
}
@GetMapping("/list")
@ResponseBody
public String listBinding(@RequestParam("names") List<String> names) {
return "Names: " + names.toString();
}
}
在上述代码中,ids
请求参数会被绑定到 int
数组,names
请求参数会被绑定到 List<String>
集合。
测试示例
假设使用 curl
命令来测试上述控制器:
- 基本类型参数绑定:
curl "http://localhost:8080/basic?id=1&name=John"
- 实体类参数绑定:
curl "http://localhost:8080/entity?id=2&name=Jane"
- 数组和集合参数绑定:
curl "http://localhost:8080/array?ids=1&ids=2&ids=3"
curl "http://localhost:8080/list?names=Alice&names=Bob"
这些示例展示了 Spring MVC 中不同类型的请求参数绑定方式,你可以依据实际需求选用合适的绑定方式。