RESTful请求

本文详细介绍了RESTful API的设计原则与实现方法,对比了RESTful与普通API请求的区别,包括如何使用HTTP动词来定义操作、如何利用URL描述资源、如何通过JSON进行数据交互等。此外还介绍了Spring框架中处理RESTful请求的具体实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


1.RESTful 用url描述资源,参数从url中获取。
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;
 }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值