Spring Boot Restful API 构建实战!
作者:liuxiaopeng
https://www.cnblogs.com/paddix/p/8215245.html
在现在的开发流程中,为了最大程度实现前后端的分离,通常后端接口只提供数据接口,由前端通过Ajax请求从后端获取数据并进行渲染再展示给用户。
我们用的最多的方式就是后端会返回给前端一个JSON字符串,前端解析JSON字符串生成JavaScript的对象,然后再做处理。
本文就来演示一下Spring boot如何实现这种模式,本文重点会讲解如何设计一个Restful的API,并通过Spring boot来实现相关的API。
不过,为了大家更好的了解Restful风格的API,我们先设计一个传统的数据返回接口,这样大家可以对比着来理解。
一、非Restful接口的支持
我们这里以文章列表为例,实现一个返回文章列表的接口,代码如下:
@Controller
@RequestMapping("/article")
public class ArticleController {@Autowiredprivate ArticleService articleService;@RequestMapping("/list.json")@ResponseBodypublic List<Article> listArticles(String title, Integer pageSize, Integer pageNum) {if (pageSize == null) {pageSize = 10;}if (pageNum == null) {pageNum = 1;}int offset = (pageNum - 1) * pageSize;return articleService.getArticles(title, 1L, offset, pageSize);}}
@Service
public class ArticleServiceImpl implements ArticleService {@Autowiredprivate ArticleMapper articleMapper;@Overridepublic Long saveArticle(@RequestBody Article article) {return articleMapper.insertArticle(article);}@Overridepublic List<Article> getArticles(String title,Long userId,int offset,int pageSize) {Article article = new Article();article.setTitle(title);article.setUserId(userId);return articleMapper.queryArticlesByPage(article,offset,pageSize);}@Overridepublic Article getById(Long id) {return articleMapper.queryById(id);}@Overridepublic void updateArticle(Article article) {article.setUpdateTime(new Date());articleMapper.updateArticleById(article);}}
运行Application.java这个类,然后访问:http://locahost:8080/article/list.json,就可以看到如下的结果:
- @Controller 标识一个类为控制器。
- @RequestMapping URL的映射。
- @ResponseBody 返回结果转换为JSON字符串。
- @RequestBody 表示接收JSON格式字符串参数。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
二、Restful API设计
![](/assets/blank.gif)
三、Restful API实现
@RestController
@RequestMapping("/rest")
public class ArticleRestController {@Autowiredprivate ArticleService articleService;@RequestMapping(value = "/article", method = POST, produces = "application/json")public WebResponse<Map<String, Object>> saveArticle(@RequestBody Article article) {article.setUserId(1L);articleService.saveArticle(article);Map<String, Object> ret = new HashMap<>();ret.put("id", article.getId());WebResponse<Map<String, Object>> response = WebResponse.getSuccessResponse(ret);return response;}@RequestMapping(value = "/article/{id}", method = DELETE, produces = "application/json")public WebResponse<?> deleteArticle(@PathVariable Long id) {Article article = articleService.getById(id);article.setStatus(-1);articleService.updateArticle(article);WebResponse<Object> response = WebResponse.getSuccessResponse(null);return response;}@RequestMapping(value = "/article/{id}", method = PUT, produces = "application/json")public WebResponse<Object> updateArticle(@PathVariable Long id, @RequestBody Article article) {article.setId(id);articleService.updateArticle(article);WebResponse<Object> response = WebResponse.getSuccessResponse(null);return response;}@RequestMapping(value = "/article/{id}", method = GET, produces = "application/json")public WebResponse<Article> getArticle(@PathVariable Long id) {Article article = articleService.getById(id);WebResponse<Article> response = WebResponse.getSuccessResponse(article);return response;}}
我们使用的是@RestController这个注解,而不是@Controller,不过这个注解同样不是Spring boot提供的,而是Spring MVC4中的提供的注解,表示一个支持Restful的控制器。
这个类中有三个URL映射是相同的,即都是/article/{id},这在@Controller标识的类中是不允许出现的。这里的可以通过method来进行区分,produces的作用是表示返回结果的类型是JSON。
@PathVariable这个注解,也是Spring MVC提供的,其作用是表示该变量的值是从访问路径中获取。
所以看来看去,这个代码还是跟Spring boot没太多的关系,Spring boot也仅仅是提供自动配置的功能,这也是Spring boot用起来很舒服的一个很重要的原因,因为它的侵入性非常非常小,你基本感觉不到它的存在。
四、测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class ArticleControllerTest {@Autowiredprivate ArticleRestController restController;private MockMvc mvc;@Beforepublic void setUp() throws Exception {mvc = MockMvcBuilders.standaloneSetup(restController).build();}@Testpublic void testAddArticle() throws Exception {Article article = new Article();article.setTitle("测试文章000000");article.setType(1);article.setStatus(2);article.setSummary("这是一篇测试文章");Gson gosn = new Gson();RequestBuilder builder = MockMvcRequestBuilders.post("/rest/article").accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON_UTF8).content(gosn.toJson(article));MvcResult result = mvc.perform(builder).andReturn(); System.out.println(result.getResponse().getContentAsString());}@Testpublic void testUpdateArticle() throws Exception {Article article = new Article();article.setTitle("更新测试文章");article.setType(1);article.setStatus(2);article.setSummary("这是一篇更新测试文章");Gson gosn = new Gson();RequestBuilder builder = MockMvcRequestBuilders.put("/rest/article/1").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON_UTF8).content(gosn.toJson(article));MvcResult result = mvc.perform(builder).andReturn();}@Testpublic void testQueryArticle() throws Exception {RequestBuilder builder = MockMvcRequestBuilders.get("/rest/article/1").accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON_UTF8);MvcResult result = mvc.perform(builder).andReturn(); System.out.println(result.getResponse().getContentAsString());}@Testpublic void testDeleteArticle() throws Exception {RequestBuilder builder = MockMvcRequestBuilders.delete("/rest/article/1").accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON_UTF8);MvcResult result = mvc.perform(builder).andReturn();}}
执行结果这里就不给大家贴了,大家有兴趣的话可以自己实验一下。整个类要说明的点还是很少,主要这些东西都与Spring boot没关系,支持这些操作的原因还是上一篇文章中提到的引入对应的starter:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
因为要执行HTTP请求,所以这里使用了MockMvc,ArticleRestController通过注入的方式实例化,不能直接new,否则ArticleRestController就不能通过Spring IoC容器来管理,因而其依赖的其他类也无法正常注入。通过MockMvc我们就可以轻松的实现HTTP的DELETE/PUT/POST等方法了。
五、总结
本文讲解了如果通过Spring boot来实现Restful的API,其实大部分东西都是Spring和Spring MVC提供的,Spring boot只是提供自动配置的功能。
但是,正是这种自动配置,为我们减少了很多的开发和维护工作,使我们能更加简单、高效的实现一个web工程,从而让我们能够更加专注于业务本身的开发,而不需要去关心框架的东西。
正文结束
1.
2.
3.
4.
5.
6.
7.
8.
一个人学习、工作很迷茫?
点击「阅读原文」加入我们的小圈子!
Spring Boot Restful API 构建实战!相关推荐
- api分层内部外部 spring_java - Spring boot restful API分层架构验证 - SO中文参考 - www.soinside.com...
[今天,我与我们的一位团队成员就Controller和Service层中的RESTful API输入的验证进行了大讨论,我觉得这是提出更大论点的糟糕日子.因此,我们有一个具有分层体系结构的spring ...
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】05、Shiro集成
1.POM文件中加入Shiro和fastJSON依赖 <dependency><groupId>org.apache.shiro</groupId><arti ...
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】04、统一处理异常...
本节讨论如何使用Spring的异常处理机制,当我们程序出现错误时,以相同的一种格式,把错误信息返回给客户端 1.创建一些自定义异常 public class TipsException extends ...
- Spring boot restful api 方法参数 BindException 异常处理
BindException位于org.springframework.validation中 客户端 发起接口请求,Controller在接收的参数在进行绑定注解校验规则时出现异常,会抛出 Bind ...
- php slim 教程,Slim - 超轻量级PHP Restful API构建框架
下载源码包: http://www.slimframework.com/ 基于Slim的Restful API Sample: require '/darjuan/Slim/Slim.php'; us ...
- 构建Spring Boot RESTful服务+ Spring Boot执行器
总览 什么是REST? REST(代表状态转移)是Web构建的体系结构样式,已成为用于Web应用程序的标准软件设计模式 . 代表性国家转移一词最早由REST的发起人,HTTP规范的主要作者之一Roy ...
- 使用Spring Boot和GraphQL构建安全的API
"我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. Grap ...
- Spring Boot Vue Element入门实战(完结)
最近给朋友做一个大学运动会管理系统,用作教学案例,正好自己也在自学VUE,决定用spring boot vue做一个简单的系统.vue这个前端框架很火,他和传统的Jquery 编程思路完全不一样,Jq ...
- 使用Spring Boot和Kubernetes构建微服务架构
"我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. 在本教程 ...
- 使用PostgreSQL使用Spring Boot和JPA构建基本应用
"我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. 每个不平 ...
最新文章
- matlab.10折交叉验证
- windows下使用GIT下载ANDROID源码
- Literal的使用和作用
- 【Python】Pycharm
- 简单分析几个常见的排序算法(C语言)
- 【QGIS入门实战精品教程】4.6:QGIS实现栅格(影像、DEM)的拼接与掩膜提取
- sigal mq_notify
- idea更换源_在Intelij IDEA中修改阿里Maven源
- PuTTY/PuttyGen介绍
- 图像分类网络总结回顾(上)
- 关于DOS/DDOS攻击和防御
- 电脑中的B、K、M、G单位换算你能分清吗?
- mysql合并两个表_MYSQL如何合并两个表
- 微信小程序开发-view视图组件
- 【微信机器人】实现保存微信表情包到相册
- 手机nfc的简单使用
- sitecore系统教程之内容编辑器
- 计算机组成原理测试题——第5章 输入输出系统(上)(2)
- 上古卷轴5mo初始化python失败_《上古卷轴5》MO管理器设置方法初级教程 MO管理器怎么设置...
- 2021观澜二中高考成绩查询,最新深中高考地段生源数据揭秘:站上时代风口,踊追新中心二梯队学区房!...
热门文章
- the database profile could not loaded. Check log for details
- 高并发红包整体设计方案
- IDEA 2017.3.3 Mybatis Plugin 3.154 安装和破解方法(Windows系统)
- Streams AQ: qmn coordinator waiting for slave to start等待事件
- 我的Android进阶之旅------Android实现音乐示波器、均衡器、重低音和音场功能
- 《Linux命令行与shell脚本编程大全》 第一、二章 学习笔记
- 群集之 COROSYNC OPENAIS +PACEMAKER +REBD+WEB
- 鄂尔多斯打造西部云计算基地
- 51cto案例精解第一章PPT
- indesign软件教程,如何更改内容颜色?