四、示例
下面是一个使用Spring Boot实现数据绑定和参数传递的示例。该示例演示了如何使用数据绑定和参数传递来实现RESTful API。
创建User类
代码语言:javascript复制public class User {
private String name;
private Integer age;
private Date birthday;
// getter and setter
}
创建控制器
代码语言:javascript复制@RestController
public class UserController {
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
@GetMapping("/user")
public User getUser(@RequestParam(value = "name", defaultValue = "Tom") String name,
@RequestParam(value = "age", defaultValue = "18") Integer age,
@RequestParam(value = "birthday", defaultValue = "1990-01-01") Date birthday) {
User user = new User();
user.setName(name);
user.setAge(age);
user.setBirthday(birthday);
return user;
}
@PostMapping("/user")
public User createUser(@RequestBody User user) {
return user;
}
@GetMapping("/user/{name}")
public User getUserByName(@PathVariable("name") String name) {
User user = new User();
user.setName(name);
user.setAge(20);
user.setBirthday(new Date());
return user;
}
}
在上面的控制器中,我们使用了@RequestParam注解、@RequestBody注解和@PathVariable注解来传递参数。同时,我们也使用了@InitBinder注解来进行数据绑定。
测试RESTful API
我们可以使用Postman等工具来测试RESTful API。下面是一些测试示例:
获取默认用户:
代码语言:javascript复制GET http://localhost:8080/user
响应:
代码语言:javascript复制{
"name": "Tom",
"age": 18,
"birthday": "1990-01-01"
}
获取指定用户:
代码语言:javascript复制GET http://localhost:8080/user/Jerry
响应:
代码语言:javascript复制{
"name": "Jerry",
"age": 20,
"birthday": "2023-04-05"
}
创建用户:
代码语言:javascript复制OST http://localhost:8080/user
{
"name": "Lucy",
"age": 25,
"birthday": "1998-05-23"
}
响应:
代码语言:javascript复制{
"name": "Lucy",
"age": 25,
"birthday": "1998-05-23"
}