【IDEA開發SpringBoot2.0】開發RESTFul類型的對外接口#03


大致解釋一下什麼是RESTFul

Restful是一種軟件架構風格,而不是標準,只是提供了一組設計原則和約束條件。它主要用於客戶端和服務器交互類的軟件。基於這個風格設計的軟件可以更簡潔,更有層次,更易於實現緩存等機制。如果一個架構符合REST原則,就稱它爲RESTful架構


接下來進入正題,創建三個Model類,詳細代碼如下

Reader

package com.zimug.bootlaunch.model;
import lombok.Data;

@Data
public class Reader {
    private String name;
    private int age;
}

Article

package com.moli.zy.springboot2ml.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Article {
    private Long id;
    private String author;
    private String title;
    private String content;
    private Date createTime;
    private List<Reader> reader;
}

AjaxResponse

package com.moli.zy.springboot2ml.model;

import lombok.Data;

@Data
public class AjaxResponse {
    private boolean isok;
    private int code;   
    private String message;
    private Object data;
    
    private AjaxResponse() {

    }

    public static AjaxResponse success() {
        AjaxResponse resultBean = new AjaxResponse();
        resultBean.setIsok(true);
        resultBean.setCode(200);
        resultBean.setMessage("success");
        return resultBean;
    }

    public static AjaxResponse success(Object data) {
        AjaxResponse resultBean = new AjaxResponse();
        resultBean.setIsok(true);
        resultBean.setCode(200);
        resultBean.setMessage("success");
        resultBean.setData(data);
        return resultBean;
    }
}

當前結構如圖所示
在這裏插入圖片描述

創建一個Controller類

ArticleRestController

package com.moli.zy.springboot2ml.controller;

import com.moli.zy.springboot2ml.model.AjaxResponse;
import com.moli.zy.springboot2ml.model.Article;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import static org.springframework.web.bind.annotation.RequestMethod.*;

@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleRestController {

    @RequestMapping(value = "/article", method = POST, produces = "application/json")
    public AjaxResponse saveArticle(@RequestBody Article article) {

        log.info("saveArticle:{}", article);

        return AjaxResponse.success(article);
    }

    @RequestMapping(value = "/article/{id}", method = DELETE, produces = "application/json")
    public AjaxResponse deleteArticle(@PathVariable Long id) {

        log.info("deleteArticle:{}", id);

        return AjaxResponse.success(id);
    }

    @RequestMapping(value = "/article/{id}", method = PUT, produces = "application/json")
    public AjaxResponse updateArticle(@PathVariable Long id, @RequestBody Article article) {
        article.setId(id);

        log.info("updateArticle:{}", article);

        return AjaxResponse.success(article);
    }

    @RequestMapping(value = "/article/{id}", method = GET, produces = "application/json")
    public AjaxResponse getArticle(@PathVariable Long id) {

        Article article1 = Article.builder().id(28L).author("ml").content("spring boot 2").title("aaa").build();
        return AjaxResponse.success(article1);
    }
}

這個Controller就是本篇的重點,接下來詳細講解一下這個類


類上有三個註解
@Slf4j
@RestController
@RequestMapping("/rest")
【@Slf4j】:

這個註解可以省去手動new一個用於打印日誌的對象

【@RestController】:

這個註解相當於@ResponseBody、@Controller的結合體,意思就是如果使用@RestController註解,那麼方法不能再返回頁面,而是返回JSON,XML或自定義mediaType內容。我們這裏需要類的所有方法返回JSON格式的數據,所以加上這個註解即可。如果你不想整個類的方法都被影響,那你可以這樣做

@Controller
public class ArticleRestController {

    public @ResponseBody AjaxResponse saveArticle() {
    
    }
}

如上代碼所示,類上用@Controller註解,然後給你需要返回JSON、XML數據的方法加上@ResponseBody註解即可

【@RequestMapping("/test")】:

這個註解就是映射一個路徑,讓我們可以訪問到對應的方法,最終獲得我們想要的東西。例如你本地跑了一個項目,想訪問被這個註解修飾的類下的某一個方法,那麼你瀏覽器的地址就應該填【127.0.0.1:8080/test/xxxxx】


接下來我們觀察一下類中這四個方法上的@RequestMapping註解

 @RequestMapping(value = "/article",      method = POST,   produces = "application/json")
 @RequestMapping(value = "/article/{id}", method = DELETE, produces = "application/json")
 @RequestMapping(value = "/article/{id}", method = PUT,    produces = "application/json")
 @RequestMapping(value = "/article/{id}", method = GET,    produces = "application/json")

可以看到,這四條的映射路徑“article”都一樣,區別是method請求方式不同,這就是RESTFul風格,POST就代表"添加"這個操作,DELETE就代表"刪除",PUT代表"修改",GET代表"獲取"

RESTFul風格的好處:

1.看地址就知道要什麼資源
2.看請求類型就知道針對資源幹什麼
3.看返回狀態碼就知道結果如何


方法上的註解 除了這種寫法,還有更簡便的寫法
@RequestMapping(value = "/article", method = POST, produces = "application/json")
public @ResponseBody AjaxResponse saveArticle(@RequestBody Article article) {
	return AjaxResponse.success(article);
}
還可以這樣寫,效果是一樣的,更簡潔
@PostMapping("/article")
public @ResponseBody  AjaxResponse saveArticle(@RequestBody Article article) {
	return  AjaxResponse.success(article);
}

下面講解一下方法形參的註解含義

觀察下面這三個方法的形參

@PostMapping("/article")
public @ResponseBody AjaxResponse saveArticle(@RequestBody Article article) {
}

@PostMapping("/article")
public @ResponseBody  AjaxResponse saveArticle(@RequestParam String  id, @RequestParam String  author) {
}

@DeleteMapping("/article/{id}")
public @ResponseBody AjaxResponse deleteArticle(@PathVariable Long id) {
}
@RequestBody

該註解常用來處理Content-Type: 不是application/x-www-form-urlencoded編碼的內容,例如application/json, application/xml等;
它是通過使用HandlerAdapter 配置的HttpMessageConverters來解析post data body,然後綁定到相應的bean上的。

提交JSON、XML數據格式的數據時用這個註解

@RequestParam

1.常用來處理簡單類型的綁定,通過Request.getParameter() 獲取的String可直接轉換爲簡單類型的情況( String–> 簡單類型的轉換操作由ConversionService配置的轉換器來完成);因爲使用request.getParameter()方式獲取參數,所以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值;
2.用來處理Content-Type: 爲 application/x-www-form-urlencoded編碼的內容,提交方式GET、POST;
3.該註解有兩個屬性: value、required; value用來指定要傳入值的id名稱,required用來指示參數是否必須綁定;

比如表單方式提交就用這個註解

@PathVariable

當使用@RequestMapping URI template 樣式映射時, 即 someUrl/{paramId}, 這時的paramId可通過 @Pathvariable註解綁定它傳過來的值到方法的參數上

該註解可以接收請求路徑中佔位符的值


最終的ArticleRestController代碼

package com.moli.zy.springboot2ml.controller;

import com.moli.zy.springboot2ml.model.AjaxResponse;
import com.moli.zy.springboot2ml.model.Article;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


@Slf4j
@Controller
@RequestMapping("/rest")
public class ArticleRestController {

    @PostMapping("/article")
    public @ResponseBody  AjaxResponse saveArticle(@RequestBody Article article) {

        log.info("saveArticle:{}",article);

        return  AjaxResponse.success(article);
    }

    @DeleteMapping("/article/{id}")
    public @ResponseBody AjaxResponse deleteArticle(@PathVariable Long id) {

        log.info("deleteArticle:{}",id);

        return AjaxResponse.success(id);
    }

    @PutMapping("/article/{id}")
    public @ResponseBody AjaxResponse updateArticle(@PathVariable Long id, @RequestBody Article article) {
        article.setId(id);

        log.info("updateArticle:{}",article);

        return AjaxResponse.success(article);
    }

    @GetMapping( "/article/{id}")
    public @ResponseBody  AjaxResponse getArticle(@PathVariable Long id) {

        Article article1 = Article.builder().id(28L).author("ml").content("spring boot 2").title("aaa").build();
        return AjaxResponse.success(article1);
    }
}

到此本節教程結束,項目跑起來之後接口就可以正常訪問了


這是我通過學習對知識的整理及備忘,本博客的所有內容,僅是自己的一些學習筆記,如有錯誤,歡迎指正。如有侵權,請告知修改。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章