SpringBoot_restful

本文介绍了HTTP的基本概念,包括常见的请求方法如GET、POST等,并深入探讨了RESTful风格的API设计原则及其应用场景。提供了具体的Spring框架下RESTful API的实现案例。

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

1. HTTP知识

名词解释
GET请求获取Request-URI所标识的资源
POST在Request-URI所标识的资源后附加新的数据
HEAD请求获取由Request-URI所标识的资源的响应消息报头
PUT请求服务器存储一个资源,并用Request-URI作为其标识
DELETE请求服务器删除Request-URI所标识的资源
TRACE请求服务器回送收到的请求信息,主要用于测试或诊断
CONNECT保留将来使用
OPTIONS请求查询服务器的性能,或者查询与资源相关的选项和需求

HTTP具体介绍


2. restful ?

最近学习了一下restful风格,简而言之,就是一种接口访问方式+命名的规范。

具体一点, GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源。

牛人总结restful :
(1)每一个URI代表一种资源;
(2)客户端和服务器之间,传递这种资源的某种表现层;
(3)客户端通过四个HTTP动词,对服务器端资源进行操作,实现”表现层状态转化”。
原文


3.代码demo

  • 查询单个对象(GET + 路径传参)
 @RequestMapping(value = "/city/{id}",method = RequestMethod.GET)
    public BaseResp<City> getCity(@PathVariable Long id){
        return new BaseResp(ResultStatus.SUCCESS,restfulService.getCity(id));
    }
  • 查询列表(GET)
    @RequestMapping(value = "/city",method = RequestMethod.GET)
    public BaseResp<List<City>> getCity(){
        return new BaseResp(ResultStatus.SUCCESS,restfulService.listCity());
    }
  • 查询分页(GET)
 @RequestMapping(value = "/city/{pages}/{size}",method = RequestMethod.GET)
    public BaseResp<Page<City>> getCity(@PathVariable Integer pages,
                                        @PathVariable Integer size){
        return new BaseResp(ResultStatus.SUCCESS,restfulService.listCity(pages, size));
    }
  • 保存对象(POST)
 @RequestMapping(value = "/city",method = RequestMethod.POST)
    public BaseResp<City> saveCity(@RequestBody City city){
        return new BaseResp(ResultStatus.SUCCESS,restfulService.saveCity(city));
    }
  • 修改对象(PUT)
 @RequestMapping(value = "/city/{id}",method = RequestMethod.PUT)
    public BaseResp<Integer> saveCity(@PathVariable Long id,
                                      @RequestBody City city){
        return new BaseResp(ResultStatus.SUCCESS,restfulService.updateCity(id,city));
    }
  • 删除(DELETE)
    @RequestMapping(value = "/city/{id}",method = RequestMethod.DELETE)
    public BaseResp<String> deleteCity(@PathVariable Long id){
        restfulService.deleteCity(id);
        return new BaseResp(ResultStatus.SUCCESS);
    }
  • 上传文件demo
 @RequestMapping(value = "/upload/{typeId}")
    public BaseResp<String> uploadFile(@PathVariable Integer typeId,
                                       @RequestParam("file") MultipartFile file){
        if (null != file){
            System.out.println(typeId);
            System.out.println(file.getOriginalFilename());
        }
        return new BaseResp(ResultStatus.SUCCESS);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值