其他
Spring Boot & Restful API 构建实战!
作者:liuxiaopeng
https://www.cnblogs.com/paddix/p/8215245.html
一、非Restful接口的支持
("/article")
public class ArticleController {
private ArticleService articleService;
("/list.json")
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);
}
}
public class ArticleServiceImpl implements ArticleService {
private ArticleMapper articleMapper;
public Long saveArticle(@RequestBody Article article) {
return articleMapper.insertArticle(article);
}
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);
}
public Article getById(Long id) {
return articleMapper.queryById(id);
}
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实现
("/rest")
public class ArticleRestController {
private ArticleService articleService;
(value = "/article", method = POST, produces = "application/json")
public WebResponse<Map<String, Object>> saveArticle( 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;
}
(value = "/article/{id}", method = DELETE, produces = "application/json")
public WebResponse<?> deleteArticle( Long id) {
Article article = articleService.getById(id);
article.setStatus(-1);
articleService.updateArticle(article);
WebResponse<Object> response = WebResponse.getSuccessResponse(null);
return response;
}
(value = "/article/{id}", method = PUT, produces = "application/json")
public WebResponse<Object> updateArticle( Long id, Article article) {
article.setId(id);
articleService.updateArticle(article);
WebResponse<Object> response = WebResponse.getSuccessResponse(null);
return response;
}
(value = "/article/{id}", method = GET, produces = "application/json")
public WebResponse<Article> getArticle( 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提供的,其作用是表示该变量的值是从访问路径中获取。
四、测试
(classes = Application.class)
public class ArticleControllerTest {
private ArticleRestController restController;
private MockMvc mvc;
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(restController).build();
}
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());
}
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();
}
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());
}
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();
}
}
(SpringJUnit4ClassRunner.class)<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
五、总结
- END -
关注Java技术栈微信公众号,在后台回复关键字:Java,可以获取一份栈长整理的 Java 最新技术干货。
最近干货分享
年轻人的第一个自定义 Spring Boot Starter!
点击「阅读原文」加入栈长的战队~