SpringBoot Web开发——构建Restful风格接口

SpringBoot Web开发——构建Restful风格接口

0.REST简介

REST:Representational State Transfer,就是表现层状态转换。

可从三个方面去理解REST:

  • 资源:每个资源就是一个具体存在的对象(系统用户,媒体文件等),以为唯一URI(统一资源定位符)存在。
  • 表现层:资源表现形式,一般以JSON形式表现。
  • 状态转换:资源的变化过程,创建/访问/修改/删除(CRUD)

HTTP虽然是无状态协议,但是存在多种动作(请求方式),可用HTTP的多种动作对应资源的状态转换。

HTTP的多种动作(请求方式):GET、POST、PUT、DELETE。

  • GET 用来访问(获取)资源
  • POST 用来新建(添加)资源
  • PUT 用来更新(修改)资源
  • DELETE 用来删除资源

其实HTTP动作(请求方式)还有以下不常用的动作:

  • PATCH:也是修改资源,但是有些Java类不支持,慎用
  • HEAD:获取资源的Content-type
  • OPTIONS:

1.Restful风格URI示例

假设存在实体类Word(单词类),有三个字段:id,english,chinese。

那么使用Restful风格URL对word数据进行增删改查:

GET     /word          # 访问(获取)word列表
GET     /word/5        # 访问(获取)id为5的word数据
POST    /word          # 新建(添加)一个word
PUT     /word            # 更新(修改)一个word
DELETE  /word/12       # 删除id为12的word数据

可看出Restful风格URL的一个特性:使用请求方式区分CRUD,使得URL中避免出现动词,便于统一与拓展。

  • 当参数比较少时(1到3个),考虑采用URI传参。

  • 当参数比较多时,考虑采用JSON格式传参。

其中URI传参的建议:

不建议这样: PUT /word?english=water&chinese=水

而建议这样: PUT /word/{english}/{chinese}

2.Springboot构建Restful风格接口

2.1 四个用于构建Restful风格的注解

Springboot中在控制层使用以下注解可实现REST风格:

  • @RestController :标注于控制器类上,Rest控制器注解,相当于@Controller+@ResponseBoby,使其为返回结果均为JSON格式的控制器
  • @RequestMapping(value = “请求路径”, method = RequestMethod.GET/POST/PUT/DELETE):标注于请求的方法上,请求映射注解,在其括号内添加请求路径和请求方法GET/POST/PUT/DELETE
  • @RequestBody标注于请求参数为JSON的对应的实体类上,请求体注解,将前端发送的JSON参数映射成实体类
  • @PathVariable注解于在URI当中的参数对应的变量,路径参数注解,将前端发送在URI当中的参数取出来。

后面截取的部分代码和完整的控制器代码中都会用到这些注解。

2.2 添加单词信息(JSON参数):POST请求

  • @RequestMapping(value = “/Word”, method = RequestMethod.POST)

请求路径 :/Word,请求方法:POST

  • @RequestBody Word word

前端以JSON格式提交参数,@RequestBody注解将其解析为Word类的对象,后面再去操作word即可。

 //1. 添加单词信息
    @RequestMapping(value = "/Word", method = RequestMethod.POST)
    public Map<String, Object> insert(@RequestBody Word word) {
        result = new HashMap<>();
        //省略
        //省略 后面控制器中有完整代码....这里先贴出和REST有关的代码
        //省略
        return result;
    }

2.3 根据id删除单词信息(URI参数):DELETE请求

  • @RequestMapping(value = “/Word/{id}”, method = RequestMethod.DELETE)

请求路径 :/Word/{id},在URI里传递参数id,请求方法:DELETE

  • @PathVariable Integer id

将URI中的id参数取出

//2. 根据id删除单词信息
    @RequestMapping(value = "/Word/{id}", method = RequestMethod.DELETE)
    public Map<String, Object> delete(@PathVariable Integer id) {
        result = new HashMap<>();
       //省略
        //省略 后面控制器中有完整代码....这里先贴出和REST有关的代码
        //省略
        return result;
    }

2.4 根据id更新单词信息(JSON参数):PUT请求

  • @RequestMapping(value = “/Word”, method = RequestMethod.PUT)

请求路径 :/Word,请求方法:PUT

  • @RequestBody Word word

前端以JSON格式提交参数,@RequestBody注解将其解析为Word类的对象,后面再去操作word即可。

 //3. 更新单词信息
    @RequestMapping(value = "/Word", method = RequestMethod.PUT)
    public Map<String, Object> update(@RequestBody Word word) {
        result = new HashMap<>();
        //省略
        //省略 后面控制器中有完整代码....这里先贴出和REST有关的代码
        //省略
        return result;
    }

2.5 根据id查询单词信息(URI参数)/查询所有单词 :GET请求

根据id查询单词信息:

  • @RequestMapping(value = “/Word/{id}”, method = RequestMethod.GET)

请求路径 :/Word/{id},在URI里传递参数id,请求方法:PUT

  • @PathVariable Integer id

将URI中的id参数取出

查询所有单词:

  • @RequestMapping(value = “/Word”, method = RequestMethod.GET)

请求路径 :/Word,无参数,请求方法:PUT

   //4. 根据id查询单词信息
    @RequestMapping(value = "/Word/{id}", method = RequestMethod.GET)
    public Map<String, Object> getOne(@PathVariable Integer id) {
        result = new HashMap<>();
       //省略
        //省略 后面控制器中有完整代码....这里先贴出和REST有关的代码
        //省略
        return result;
    }

    //5. 查询所有单词
    @RequestMapping(value = "/Word", method = RequestMethod.GET)
    public Map<String, Object> getAll() {
        result = new HashMap<>();
        //省略
        //省略 后面控制器中有完整代码....这里先贴出和REST有关的代码
        //省略
        return result;
    }

2.6 完整控制器类代码

在类上使用注解

package com.piao.springboot_rest.controller;

import com.piao.springboot_rest.entity.Word;
import com.piao.springboot_rest.mapper.WordMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

//RestController=@Controller+@ResponseBoby
@RestController
public class MyRestController {
    //存储预返回页面的结果对象
    private Map<String, Object> result;
    //注入业务对象
    @Resource
    private WordMapper wordMapper;

    //1. 添加单词信息
    @RequestMapping(value = "/Word", method = RequestMethod.POST)
    public Map<String, Object> insert(@RequestBody Word word) {
        result = new HashMap<>();
        //数据校验 判空!
        if (null == word) {
            result.put("message", "插入的单词为空");
            return result;
        }
        if (null == word.getChinese() || "".equals(word.getEnglish())) {
            result.put("message", "插入的单词中文为空或者为空字符串");
            return result;
        }
        if (null == word.getChinese() || "".equals(word.getChinese())) {
            result.put("message", "插入的单词中文为空或者为空字符串");
            return result;
        }
        wordMapper.insert(word);
        result.put("message", "插入单词成功");
        return result;
    }

    //2. 根据id删除单词信息
    @RequestMapping(value = "/Word/{id}", method = RequestMethod.DELETE)
    public Map<String, Object> delete(@PathVariable Integer id) {
        result = new HashMap<>();
        //数据校验 判空!
        if (null == id) {
            result.put("message", "输入的单词id为空");
            return result;
        }
        wordMapper.deleteById(id);
        result.put("message", "删除单词成功");
        return result;
    }

    //3. 更新单词信息
    @RequestMapping(value = "/Word", method = RequestMethod.PUT)
    public Map<String, Object> update(@RequestBody Word word) {
        result = new HashMap<>();
        //数据校验 判空!
        if (null == word.getId()) {
            result.put("message", "更新的单词id为空");
            return result;
        }
        if (null == word.getEnglish() || "".equals(word.getEnglish())) {
            result.put("message", "更新的单词中文为空或者为空字符串");
            return result;
        }
        if (null == word.getChinese() || "".equals(word.getChinese())) {
            result.put("message", "更新的单词中文为空或者为空字符串");
            return result;
        }
        wordMapper.updateById(word);
        result.put("message", "更新单词成功");
        return result;
    }

    //4. 根据id查询单词信息
    @RequestMapping(value = "/Word/{id}", method = RequestMethod.GET)
    public Map<String, Object> getOne(@PathVariable Integer id) {
        result = new HashMap<>();
        //数据校验 判空!
        if (null == id) {
            result.put("message", "传入id为空");
            return result;
        }
        result.put("word", wordMapper.selectById(id));
        result.put("message", "查询单词成功");
        return result;
    }

    //5. 查询所有单词
    @RequestMapping(value = "/Word", method = RequestMethod.GET)
    public Map<String, Object> getAll() {
        result = new HashMap<>();
        //selectList(null)设置过滤条件为空,就是查询所有,并以list形式返回
        result.put("word", wordMapper.selectList(null));
        result.put("message", "查询所有单词成功");
        return result;
    }

}

3.测试REST风格接口

均使用postman软件测试:

3.1 测试添加单词信息 POST请求 JSON参数

记得选择POST请求方式,参数为JSON格式

REST POST请求 JSON参数

3.2 测试根据id更新单词信息 DELETE请求 URI参数

id参数在URI中,DELETE请求,下面的截图中为删除id为5566的单词信息:

REST DELETE请求 URI参数

3.3 测试根据id更新单词信息 PUT请求 JSON参数

参数为JSON格式,请求方式PUT

REST PUT请求 JSON参数

3.4 根据id查询单词信息(URI参数)/查询所有单词 :GET请求

根据id查询单词信息:参数id在URI中,GET请求:下面截图例子为查询id为8的单词数据

RESt GET请求 URI参数

查询所有单词:无参数,GET请求

REST 无参数,GET请求
整个REST的demo代码使用SpringBoot+MyBatisPlus+MySQL构成链接:springboot_rest demo

发布了83 篇原创文章 · 获赞 40 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_42391904/article/details/104365503