Spring Boot学习(RESTful API)
来源:互联网 发布:网络社交的利弊二辩 编辑:程序博客网 时间:2024/05/18 02:30
马上要离开青岛了,刚辞职事多得很,今天就介绍一下RESTful API吧
1. RESTful API简介
3个月前公司开始使用RESTful API来开发项目了,前后分离,单纯的我以为我只用做java了,安安静静的写java代码才是正儿八经的java软件工程师啊,哎,结果前端不了解业务,也不了解RESTful API开发模式,更可怕的是我们选用的前端是Angular1.x,这B基本不会。。。然后工作就变成了,我开发着后端代码,他写着前端代码,我写完了再帮他把前端bug改了,帮他做代码审核。。。扯远了,现在辞职了,仍然觉那段开发经历是个噩梦。吐槽结束,开始干货。这方面我也是才开始学,看了许多前辈的资料,我会在文后附上。
1.1 什么是 REST?
REST 是属于 WEB 自身的一种架构风格,是在 HTTP 1.1 规范下实现的。Representational State Transfer 全称翻译为表现层状态转化。Resource:资源。比如 newsfeed;Representational:表现形式,比如用JSON,富文本等;State Transfer:状态变化。通过HTTP 动作实现。
1.2REST的五个要素和六个特性
五要素
- 资源(Resource)
- 资源的表述(Representation)
- 状态转移(State Transfer)
- 统一接口(Uniform Interface)
- 超文本驱动(Hypertext Driven)
六特性
- 面向资源(Resource Oriented)
- 可寻址(Addressability)
- 连通性(Connectedness)
- 无状态(Statelessness)
- 统一接口(Uniform Interface)
- 超文本驱动(Hypertext Driven)
1.3 Http请求方式
如之前的介绍,REST是给予Http协议的,所以有必要介绍一下Http请求的类型和规范。
- GET 请求获取Request-URI所标识的资源
- POST 在Request-URI所标识的资源后附加新的数据
- HEAD 请求获取由Request-URI所标识的资源的响应消息报头
- PUT 请求服务器存储一个资源,并用Request-URI作为其标识
- DELETE 请求服务器删除Request-URI所标识的资源
- TRACE 请求服务器回送收到的请求信息,主要用于测试或诊断
- CONNECT 保留将来使用
- OPTIONS 请求查询服务器的性能,或者查询与资源相关的选项和需求
2.RESTFul API的简单应用
之前有做过了Spring Boot + Mybatis的项目,就拿这个项目做介绍吧。
在之前的unit2-1项目中,我只写了两个get方法,用来获得所有学生信息集合和单个学生信息,现在我们来增加一些。新增、更新和删除。
@RestController@RequestMapping(value = "/student")public class StudentController { @Autowired private StudentService studentService; @GetMapping(value = "/list") public List<Student> findList(){ return studentService.findList(); } @GetMapping(value = "/getById/{id}") public Student getById(@PathVariable int id){ return studentService.getById(id); } @PostMapping(value = "/insert") public String insert(Student student){ studentService.insert(student); return "success"; } @PostMapping(value = "/updateById/{id}") public String updateById(@PathVariable int id , Student student){ student.setId(id); studentService.updateById(student); return "success"; } @DeleteMapping(value = "/deleteById/{id}") public String deleteById(@PathVariable int id ){ studentService.deleteById(id); return "success"; }}
这里只放了controller的代码,别的就去我的git上看吧,就是个增删改查。
3. RESTFul API的测试方法
3.1 JUnit测试环境
直接上测试代码吧
@RunWith(SpringRunner.class)@SpringBootTest@AutoConfigureMockMvcpublic class Unit21ApplicationTests { @Autowired private MockMvc mockMvc; @Test public void contextLoads() throws Exception { String baseUrl = "/student"; RequestBuilder requestBuilder = null; MvcResult mvcResult = null; // 先查询学生列表 requestBuilder = get(baseUrl + "/list"); mvcResult = mockMvc.perform(requestBuilder).andReturn(); System.out.printf(mvcResult.getResponse().getContentAsString()); // 新增一条 requestBuilder = post(baseUrl + "/insert") .param("name", "test") .param("idCard", "test001") .param("age", "1"); mvcResult = mockMvc.perform(requestBuilder).andReturn(); System.out.printf(mvcResult.getResponse().getContentAsString()); // 查询id为1的学生 requestBuilder = get(baseUrl+"/getById/1"); mvcResult = mockMvc.perform(requestBuilder).andReturn(); System.out.printf(mvcResult.getResponse().getContentAsString()); // 更新id为1的学生 requestBuilder = post(baseUrl + "/updateById/1") .param("name", "test002") .param("idCard", "test002") .param("age", "1"); mvcResult = mockMvc.perform(requestBuilder).andReturn(); System.out.printf(mvcResult.getResponse().getContentAsString()); // 再查询id为1的学生 requestBuilder = get(baseUrl+"/getById/1"); mvcResult = mockMvc.perform(requestBuilder).andReturn(); System.out.printf(mvcResult.getResponse().getContentAsString()); // 删除id为1的学生 requestBuilder = delete(baseUrl+"/deleteById/1"); mvcResult = mockMvc.perform(requestBuilder).andReturn(); System.out.printf(mvcResult.getResponse().getContentAsString()); }}
使用的Mock来模拟请求,因为用浏览器访问的都是GET请求,所以需要测试类来测试,但是在测试类的使用过程中感觉效率还是不高,需要敲很多的代码(尽管可以复制粘贴),像这种基础的增删改查我们可以直接使用这个测试类,只需要修改参数就行,但这测试方法有个弊端,就是有点慢,你每次测试一个方法他都有重启Spring Boot,不知道Junit有没有类似热部署的方法
3.2 火狐+RESTClient 测试环境
我建议使用工具来发起Http请求,我这里使用的是RESTClient,大家可以到Git上下载它们的源码,有java写的也有Python写的,都有GUI界面
我使用的是火狐浏览器插件,感觉这样更方便,更形象,谷歌浏览器也有类似的插件,这里我附上火狐浏览器插件的地址 https://addons.mozilla.org/zh-CN/firefox/addon/restclient/
下面是插件截图
可以设置请求头,请求参数,请求方法,请求地址,特别好用,需要注意的是带参请求需要设置请求头Content-type为application/x-www-form-urlencoded;charset=UTF-8,使用这个工具的好处是你把项目启起来,不断的发起请求就能知道这些接口返回的信息完整度,减少了重启项目消耗的时间
说这么多就是好用啊~~~来一个新增请求的完整界面
4. 基于Swagger2的API文档
前后端分离,特别是不单单是代码分离,开发人员也分离的时候,前端人员不一定有后台代码,或者它们看不懂java代码,或者让它们通过controller来查找Api不方便,等等原因推动了接口文档的编写。
Swagger是为代码注释等同接口文档而出现的,说的通俗点,编写代码是需要有注释的,代码逻辑需要注释,方法的作用,注意事项都需要代码注释,而请求地址就是一个方法,我们将方法的注释用Swagger的@ApiOperation注解来扩充,那么,后端将会提供一个类似接口文档的请求地址。下面上代码。
4.1 pom.xml中引入Swagger依赖
<!-- swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
增加一个配置类
@Configuration@EnableSwagger2public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("cn.yuan.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中的Swagger2") .description("简介") .termsOfServiceUrl("https://git.oschina.net/heyuan1515/spring-boot-study") .contact("H") .version("1.0") .build(); }}
在controller的请求方法上添加注解
@DeleteMapping(value = "/deleteById/{id}") @ApiOperation("删除学生信息") public String deleteById(@PathVariable int id ){ studentService.deleteById(id); return "success"; }
启动项目,访问 http://localhost:8080/swagger-ui.html 可以看到接口信息
5. 参考文章
理解真正的REST风格 http://www.infoq.com/cn/articles/understanding-restful-style
Spring Boot实现RESTFul http://www.bysocket.com/?p=1627
RESTClient 测试工具 http://www.oschina.net/news/61889/restclient-3-5
火狐浏览器(开发者版) https://www.mozilla.org/zh-CN/firefox/developer/?utm_campaign=mdn-front-pg-promo&utm_medium=referral&utm_source=developer.mozilla.org
Swagger2的使用 http://blog.didispace.com/springbootswagger2/
- Spring Boot学习(RESTful API)
- spring boot 实现Restful API
- Spring boot restful api demo
- spring boot restful API风格
- Spring Boot学习(三)之构建RESTful API与单元测试
- spring-boot restful接口学习(1)
- Spring Boot构建RESTful API与单元测试
- spring-boot 集成 Swagger 搭建RESTful API
- Spring Boot构建RESTful API与单元测试
- 三、Spring Boot构建RESTful API
- Spring Boot 构建 Restful API 和测试
- 使用 JSONDoc 记录 Spring Boot RESTful API
- Spring Boot构建RESTful API与单元测试
- Spring Boot构建RESTful API与单元测试
- Spring Boot注解完成Restful API
- Spring Boot构建RESTful API与单元测试
- Spring Boot构建RESTful API与单元测试
- Spring Boot系列 - 6. spring boot 实现Restful API
- ugui的优化
- Linux下修改MySQL初始密码、开启远程登录、授权远程登录用户
- Markdown转PPT的方法
- kubeadm安装kubernetes(weave)
- Leetcode(19)
- Spring Boot学习(RESTful API)
- 闪讯无线助手-Android端闪讯破解路由器拨号实现原理
- php 的 cli 运行模式
- 安卓开发,与后台服务器对接中,JSON解析入门学习
- 【旧资料整理】MFC--自己优化的双缓冲绘图方法
- MVC权限设计
- Python 读取csv的某行——两种方法
- ora-01480 str 绑定值的结尾null字符缺失
- 【旧资料整理】MFC--尝试得出<<修改浮动边栏标题使立即生效>>方法