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. ...
随机推荐
- 用Java写一个递归遍历目录下面的所有文件
java获取文件的属性如文件大小和修改时间: long mysize = file.length();long lastModified = file.lastModified();System.ou ...
- vue项目中 指令 v-html 中使用过滤器filters功能
转载于简书 链接:http://www.jianshu.com/p/29b7eaabd1ba 问题 2.0 filters only work in mustache tags and v-bind. ...
- [REPRINT]Properties vs. Getters and Setters
http://www.python-course.eu/python3_properties.php Our new class means breaking the interface. The a ...
- Linux相关TCP参数优化: proc/sys/net/ipv4/ 提高web质量
tcp_wmem(3个INTEGER变量): min, default, max min:为TCP socket预留用于发送缓冲的内存最小值.每个tcp socket都可以在建议以后都可以使用它.默认 ...
- 洛谷P2258 子矩阵——题解
题目传送 表示一开始也是一脸懵逼,虽然想到了DP,但面对多变的状态不知从何转移及怎么合理记录状态.之(借鉴大佬思路)后,豁然开朗,于是在AC后分享一下题解. 发现数据范围出奇地小,不过越是小的数据范围 ...
- 解决:未能加载文件或程序集“MiniProfiler”或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配
参考:https://www.lanhusoft.com/Article/120.html 产生的原因: 公司原来的项目用的是MiniProfiler 3.0.11新项目本来想使用4.0,但是无奈网上 ...
- 几种Android混淆和逆向工具介绍
针对Android面临的安全风险,一些防止逆向的方法应运而生.代码混淆在X86架构上曾经被广泛研究,他被用于保护软件的只是产权,但是恶意软件也常常使用他来对抗杀毒软件或者对抗逆向分析者,代码混淆可以给 ...
- 网页分页page
public class PageBean { private int page; // 第几页 private int pageSize; // 每页记录数 private int start; / ...
- 模拟vue实现简单的webpack打包
一.安装nodejs,查看是否安装成功 二.package.json项目初始化 npm init 电脑有node环境,在根目录下运行命令npm init初始化项目,根据提示输入项目相关信息,然后运行. ...
- JavaVM & JNIEnv
JNIEnv提供了大多数的JNI函数.你的本地方法都会接收JNIEnv作为第一个参数.JNIEnv用于本地线程存储.因此,你不能在线程间共享同一个JNIEnv.如果一个代码段没有其他方式获取它自身线程 ...