一 代码位置
https://gitee.com/cakin24/code/tree/master/09/RESTful
二 关键代码
package com.example.demo.controller;
import com.example.demo.entity.Article;
import com.example.demo.repository.ArticleRepository;
import com.example.demo.result.ExceptionMsg;
import com.example.demo.result.Response;
import com.example.demo.result.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("article")
public class ArticleController {
protected Response result(ExceptionMsg msg){
return new Response(msg);
}
protected Response result(){
return new Response();
}
@Autowired
private ArticleRepository articleRepository;
@Autowired
RestTemplateBuilder restTemplateBuilder;
//查 Test1
@RequestMapping(value = "/", method = RequestMethod.GET)
public ResponseData getArticleList() {
List<Article> list = new ArrayList<Article>(articleRepository.findAll());
return new ResponseData(ExceptionMsg.SUCCESS,list);
}
//增 Test2
@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseData add(Article article) {
articleRepository.save(article);
// return "{success:true,message: \"添加成功\" }";
return new ResponseData(ExceptionMsg.SUCCESS,article);
}
//删 Test3
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Response delete(@PathVariable("id") long id) {
articleRepository.deleteById(id);
return result(ExceptionMsg.SUCCESS);
}
//改 Test4
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseData update(Article model) {
articleRepository.save(model);
return new ResponseData(ExceptionMsg.SUCCESS,model);
}
//查 Test5
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseData findArticle(@PathVariable("id") Integer id) throws IOException {
Article article = articleRepository.findById(id);
if (article != null) {
return new ResponseData(ExceptionMsg.SUCCESS,article);
}
return new ResponseData(ExceptionMsg.FAILED,article);
}
}
三 测试
1 Test2测试
2 Test1测试
3 Test5测试
4 Test4测试
5 Test3测试