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. ...
随机推荐
- git如何将本地文件关联到远程服务器
很多时候,当我们关联git服务器的时候,本地都有可能会有一些开发的东西需要同步上去.那怎么样设置同步呢!跟我来做,简易配置: git本地关联远程项目: 第一步:选择目录 ...
- LOJ 6192 城市网络(树上倍增)
LOJ #6192. 「美团 CodeM 复赛」城市网络(链接) 一棵以 $ 1 $ 号节点为根的树,每个点有一个权值,有 $ q $ 个询问,每次从 $ x $ 点开始往某个祖先 $ y $ 走,初 ...
- C++ GUI Qt4学习笔记08
C++ GUI Qt4学习笔记08 qtc++signal图形引擎文档 本章介绍Qt的二维图形引擎,Qt的二维图形引擎是基于QPainter类的.<span style="colo ...
- Python---协程---重写多进程
一. # 匹配一行文字中所有开头的字母import re s = 'i love you but you don\'t love me' # \b\m findallcontent = re.find ...
- 微信小程序-tabBar-注意事项
tabBar.list[0].selectedIconPath 文件格式错误,仅支持 .png..jpg..jpeg 格式
- 最全面的H5的背景音效素材(经过实践),分享给你!!!
个人内心独白: 这两天在为一个H5的页面寻找一些相关音效,茫茫的网络,辣么大,真是想法设法翻遍你,不说废话了,看总结吧哦 方法总结(这才是重点,看这里): 1.如果是部分铃声截取的,我们可以来到铃声之 ...
- Shell入门01
Shell入门 1.基于硬件的虚拟化 2.基于平台的虚拟化 3.基于服务的虚拟化 4.基于库的虚拟化 5.基于操作系统的虚拟化 管理员使用Shell程序与操作系统进行交互,之前学习的shell脚本都是 ...
- java浅克隆和深克隆,序列化和反序列化实现深克隆(封装序列化和反序列化操作)
本篇博客内容: 一.浅克隆(ShallowClone)和深克隆(DeepClone) 二.序列化和反序列化实现深克隆 三.封装序列化和反序列化操作 ObjectOutputStream + 内存流By ...
- Windows Server 2003 IIS 使用 Excel.Application
在Server2003服务器系统中,配置ASP调用CreateObject("Excel.Application")对象 1.先在服务器中安装Microsoft Excel 2.打 ...
- [CSP-S模拟测试]:炼金术士的疑惑(模拟+数学+高斯消元)
题目传送门(内部题70) 输入格式 第一行一个正整数$n$,表示炼金术士已知的热化学方程式数量.接下来$n$行,每行一个炼金术士已知的热化学方程式.最后一行一个炼金术士想要求解的热化学方程式,末尾记为 ...