java
主页 > 软件编程 > java >

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

2022-03-17 | 秩名 | 点击:

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

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接口

下面代码中并未真正的进行数据库操作,本专栏后面会讲解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;

  }

}

原文链接:https://www.kancloud.cn/hanxt/springboot2/1384776
相关文章
最新更新