Spring Boot & Restful API 构建实战!
作者:liuxiaopeng
https://www.cnblogs.com/paddix/p/8215245.html
一、非Restful接口的支持
@Controller
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
@RequestMapping("/list.json")
@ResponseBody
public 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 {
@Autowired
private ArticleMapper articleMapper;
@Override
public Long saveArticle(@RequestBody Article article) {
return articleMapper.insertArticle(article);
}
@Override
public 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);
}
@Override
public Article getById(Long id) {
return articleMapper.queryById(id);
}
@Override
public void updateArticle(Article article) {
article.setUpdateTime(new Date());
articleMapper.updateArticleById(article);
}
}
- @Controller 标识一个类为控制器。
- @RequestMapping URL的映射。
- @ResponseBody 返回结果转换为JSON字符串。
- @RequestBody 表示接收JSON格式字符串参数。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
二、Restful API设计
三、Restful API实现
@RestController
@RequestMapping("/rest")
public class ArticleRestController {
@Autowired
private 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提供的,其作用是表示该变量的值是从访问路径中获取。
四、测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class ArticleControllerTest {
@Autowired
private ArticleRestController restController;
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(restController).build();
}
@Test
public 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());
}
@Test
public 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();
}
@Test
public 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());
}
@Test
public 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();
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
五、总结
- END -
关注Java技术栈微信公众号,在后台回复关键字:Java,可以获取一份栈长整理的 Java 最新技术干货。
最近干货分享
点击「阅读原文」加入栈长的战队~
Spring Boot & Restful API 构建实战!的更多相关文章
- 使用 JSONDoc 记录 Spring Boot RESTful API
这个博文可以分为两部分:第一部分我将编写一个Spring Boot RESTful API,第二部分将介绍如何使用JSONDoc来记录创建的API.做这两个部分最多需要15分钟,因为使用Spring ...
- spring boot RESTFul API拦截 以及Filter和interceptor 、Aspect区别
今天学习一下RESTFul api拦截 大概有三种方式 一.通过Filter这个大家很熟悉了吧,这是java规范的一个过滤器,他会拦截请求.在springboot中一般有两种配置方式. 这种过滤器拦截 ...
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】03、创建RESTful API,并统一处理返回值
本节应用Spring对RESTful的支持,使用了如@RestController等注解实现RESTful控制器. 如果对Spring中的RESTful不太明白,请查看相关书籍 1.创建一个数据对象, ...
- Spring Boot - Restful API
基本用法 @GetMapping与@PostMapping不指定参数时就是指直接使用到controller一级的url就行 @GetMapping与@PathVariable对应,前者{}中的字符串和 ...
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】06、Mybatis+SQLServer集成
1.增加POM依赖 注意pagehelper插件,我重写过,可以到我的这篇文章了解https://www.cnblogs.com/LiveYourLife/p/9176934.html <dep ...
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】05、Shiro集成
1.POM文件中加入Shiro和fastJSON依赖 <dependency> <groupId>org.apache.shiro</groupId> <ar ...
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】04、统一处理异常
本节讨论如何使用Spring的异常处理机制,当我们程序出现错误时,以相同的一种格式,把错误信息返回给客户端 1.创建一些自定义异常 public class TipsException extends ...
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】02、创建新的SpringBoot项目
1.创建项目 得到项目架构 2.测试项目Web功能 默认端口为8080,运行后,输入localhost:8080/index即可访问到网页 到这里,项目构建成功!
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】01、环境准备
开发环境 windows+STS(一个针对Spring优化的Eclipse版本)+Maven+SQLServer 环境部署 1.安装SQLServer(使用版本2008R2) 自行安装,此处略过 2. ...
随机推荐
- vue2.0 之 过渡动画transtion
过渡的类名: 在进入/离开的过渡中,会有 6 个 class 切换 (v 是前缀,name = v) v-enter:定义进入过渡的开始状态.在元素被插入时生效,在下一个帧移除. v-enter-ac ...
- element隐藏组件滚动条scrollbar使用
可使用 组件 <el-scrollbar></el-scrollbar> 设置 组件的样式 为 高度100% <el-scrollbar style="heig ...
- React 应用设计之道 - curry 化妙用
使用 React 开发应用,给予了前端工程师无限"组合拼装"快感.但在此基础上,组件如何划分,数据如何流转等应用设计都决定了代码层面的美感和强健性. 同时,在 React 世界里提 ...
- pyqt5-QAbstractScrollArea滚动条
继承 QObject-->QWidget-->QFrame-->QAbstractScrollArea 是抽象类 import sys from PyQt5.QtWidgets i ...
- R语言 eval(quote(x)) 和 eval(x)
eval() 's first argument is an expression. So if you only provide one argument, it will evaluate the ...
- 【GDOI 2016 Day1】疯狂动物城
题目 分析 注意注意:码农题一道,打之前做好心理准备. 对于操作1.2,修改或查询x到y的路径,显然树链剖分. 对于操作2,我们将x到y的路径分为x到lca(x,y)和lca(x,y)到y两部分. 对 ...
- vue安装 js-cookie
首先在命令行工具输入:npm install vue-js-cookie 安装完成之后在需要使用的页面导入:import Cookies from 'js-cookie' 这样就可以使用了,如下图,先 ...
- 51nod1820 长城之旅
题目描述 BB 痛失一血(打了场Comet OJ回来就没了) 不过后来又刷了一道水题 题解 LCM+取模=结论题 结论1 \(gcd(k^{2^i}+1,k^{2^j}+1)=1 (i\neq j 且 ...
- 【java工具类】AES加密解密
百度百科一下,AES:高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准.这个标准 ...
- Java——类的继承、访问控制
[继承] <1>Java只支持单继承,不支持多继承. <2>继承父类的私有成员变量,只有所有权,没有使用权. [继承中的构造方法]