其他
实战:SpringBoot & Restful API 构建示例
点击上方 Java后端,选择 设为星标
优质文章,及时送达作者 | liuxiaopeng
链接 | 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 {
@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);
}
}
这个ArticleService的实现很简单,就是简单的封装了ArticleMapper的操作,ArticleService的实现类如下:
@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);
}
}
运行Application.java这个类,然后访问:http://locahost:8080/article/list.json,就可以看到如下的结果:
ArticleServiceImpl这个类是一个很普通的类,只有一个Spring的注解@Service,标识为一个bean以便于通过Spring IoC容器来管理。我们再来看看ArticleController这个类,其实用过Spring MVC的人应该都熟悉这几个注解,这里简单解释一下:
@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;
}
}
四、测试
@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>