RESTful请求与普通请求的区别
查询 controller/getUser?id=1 controller/user/1 get
添加 controller/createUser?name=xxx&age=23 controller/user post
删除 controller/deletUser?id=1 controller/user/1 delete
修改 controller/updateUser?id=1&name=xxx controller/user put
2.使用http方法描述行为,使用http状态码来表示不同的结果,通过http的请求为post或put决定执行什么方法。
3.使用json交互数据。
PathVariable 的用法
@PathVariable 获取URL资源中的参数,可使用正则表达式控制参数类型。
@GetMapping("/{id:\\d+}") //id:正则表达式,"\\d+"正则为正整数
public User addUser(@PathVariable(name = "id") Integer idxxx)
通过对象接收传递的参,需要配置@RequestBody注解
@PostMapping
public User createUser(@Valid @RequestBody User user)
@JsonView控制对象的输出参数
1.使用接口来声明多个视图。
2.在值对象的get方法上指定视图。
3.在controller方法上指定视图。
对象设置如下
public class Animal {
public interface DetailView extends SimpleView{} //DetailView输出包含SimpleView的内容
public interface SimpleView{} //输出除password以外的内容
private String name;
private Integer age;
private String password;
@JsonView(SimpleView.class)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonView(SimpleView.class)
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@JsonView(DetailView.class)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
controller设置如下
@GetMapping("/{id}")
@JsonView(Animal.SimpleView.class) //设置为Animal.DetailView.class则输出password信息
public Animal getAnimal(@PathVariable Integer id){
Animal animal = new Animal();
animal.setAge(33);
animal.setName("cat");
animal.setPassword("sdfd");
return animal;
}