服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - spring常用注解开发一个RESTful接口示例

spring常用注解开发一个RESTful接口示例

2022-10-08 15:19字母哥 Java教程

这篇文章主要为大家介绍了使用spring常用注解开发一个RESTful接口示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步

一、开发REST接口

在本专栏之前的章节中已经给大家介绍了

Spring常用注解及http数据转换教程

Spring Boot提高开发效率必备工具lombok使用

Spring Boot开发RESTful接口与http协议状态表述

本节内容就是将之前学到的内容以代码的方式体现出来。

第一步:定义资源(对象)

?
1
2
3
4
5
6
7
8
9
10
@Data
@Builder
public class Article {
    private Long  id;
    private String author;
    private String title;
    private String content;
    private Date createTime;
    private List<Reader> reader;
}
?
1
2
3
4
5
@Data
public class Reader {
  private String name;
  private Integer age;
}

Data、Builder都是lombok提供给我们的注解,有利于我们简化代码。可以参考本专栏之前章节对lombok进行学习。

@Builder为我们提供了通过对象属性的链式赋值构建对象的方法,下文中代码会有详细介绍。

@Data注解帮我们定义了一系列常用方法,如:getters、setters、hashcode、equals等

第二步:HTTP方法与Controller(动作)

我们实现一个简单的RESTful接口

  • 增加一篇Article ,使用POST方法
  • 删除一篇Article,使用DELETE方法,参数是id
  • 更新一篇Article,使用PUT方法,以id为主键进行更新
  • 获取一篇Article,使用GET方法

下面代码中并未真正的进行数据库操作,本专栏后面会讲解mybatis和JPA,届时会做补充。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleController {
  //获取一篇Article,使用GET方法,根据id查询一篇文章
  //@RequestMapping(value = "/articles/{id}",method = RequestMethod.GET)
  @GetMapping("/articles/{id}")
  public AjaxResponse getArticle(@PathVariable("id") Long id){
    //使用lombok提供的builder构建对象
    Article article = Article.builder()
            .id(id)
            .author("zimug")
            .content("spring boot 从青铜到王者")
            .createTime(new Date())
            .title("t1").build();
    log.info("article:" + article);
    return AjaxResponse.success(article);
  }
  //增加一篇Article ,使用POST方法(RequestBody方式接收参数)
  //@RequestMapping(value = "/articles",method = RequestMethod.POST)
  @PostMapping("/articles")
  public AjaxResponse saveArticle(@RequestBody Article article,
                                  @RequestHeader String aaa){
    //因为使用了lombok的Slf4j注解,这里可以直接使用log变量打印日志
    log.info("saveArticle:" + article);
    return AjaxResponse.success();
  }
  //增加一篇Article ,使用POST方法(RequestParam方式接收参数)
  /*@PostMapping("/articles")
  public AjaxResponse saveArticle(@RequestParam  String author,
                                  @RequestParam  String title,
                                  @RequestParam  String content,
                                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                  @RequestParam  Date createTime){
    log.info("saveArticle:" + createTime);
    return AjaxResponse.success();
  }*/
  //更新一篇Article,使用PUT方法,以id为主键进行更新
  //@RequestMapping(value = "/articles",method = RequestMethod.PUT)
  @PutMapping("/articles")
  public AjaxResponse updateArticle(@RequestBody Article article){
    if(article.getId() == null){
      //article.id是必传参数,因为通常根据id去修改数据
      //TODO 抛出一个自定义的异常
    }
    log.info("updateArticle:" + article);
    return AjaxResponse.success();
  }
  //删除一篇Article,使用DELETE方法,参数是id
  //@RequestMapping(value = "/articles/{id}",method = RequestMethod.DELETE)
  @DeleteMapping("/articles/{id}")
  public AjaxResponse deleteArticle(@PathVariable("id") Long id){
    log.info("deleteArticle:" + id);
    return AjaxResponse.success();
  }
}

因为使用了lombok的@Slf4j注解(类的定义处),就可以直接使用log变量打印日志。不需要写下面的这行代码。

?
1
private static final Logger log = LoggerFactory.getLogger(HelloController.class);

二、统一规范接口响应的数据格式

下面这个类是用于统一数据响应接口标准的。它的作用是:统一所有开发人员响应前端请求的返回结果格式,减少前后端开发人员沟通成本,是一种RESTful接口标准化的开发约定。下面代码只对请求成功的情况进行封装,在后续的异常处理相关的章节会做更加详细的说明。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Data
public class AjaxResponse {
  private boolean isok;  //请求是否处理成功
  private int code; //请求响应状态码(200、400、500)
  private String message;  //请求结果描述信息
  private Object data; //请求结果数据(通常用于查询操作)
  private AjaxResponse(){}
  //请求成功的响应,不带查询数据(用于删除、修改、新增接口)
  public static AjaxResponse success(){
    AjaxResponse ajaxResponse = new AjaxResponse();
    ajaxResponse.setIsok(true);
    ajaxResponse.setCode(200);
    ajaxResponse.setMessage("请求响应成功!");
    return ajaxResponse;
  }
  //请求成功的响应,带有查询数据(用于数据查询接口)
  public static AjaxResponse success(Object obj){
    AjaxResponse ajaxResponse = new AjaxResponse();
    ajaxResponse.setIsok(true);
    ajaxResponse.setCode(200);
    ajaxResponse.setMessage("请求响应成功!");
    ajaxResponse.setData(obj);
    return ajaxResponse;
  }
  //请求成功的响应,带有查询数据(用于数据查询接口)
  public static AjaxResponse success(Object obj,String message){
    AjaxResponse ajaxResponse = new AjaxResponse();
    ajaxResponse.setIsok(true);
    ajaxResponse.setCode(200);
    ajaxResponse.setMessage(message);
    ajaxResponse.setData(obj);
    return ajaxResponse;
  }
}

以上就是springboot常用注解开发一个RESTful接口示例的详细内容,更多关于springboot注解开发RESTful接口的资料请关注服务器之家其它相关文章!

原文链接:https://www.kancloud.cn/hanxt/springboot2/1384776

延伸 · 阅读

精彩推荐