學習筆記 大佬繞路,小白多篇文章整合總結篇
簡單背景
網絡程序正朝著移動設備的方向發展,前后端分離、APP,最好的交互交互方式莫過于通過API接口實現。既然要進行數據交互,那么這接口就得有講究了:既要實用,又要優雅好看!
那么,如何寫一套漂亮的API接口呢?
本次我們先了解一下Spring對API接口開發的支持,然后我們采用Spring Boot搭建項目,借用Swagger2列出API接口,便于查閱。
接口返回格式
API接口要求返回的格式是 application/json
,我們知道網頁返回的格式一般是 text/html
,因此,Spring Boot為寫接口,提供了兩種實現方式:類注解 和 方法注解。
- 類注解
@RestController
我們只需要在類上寫上注解 @RestController
,那么此Controller返回格式就都是text/json
。
/*類注解*/
@RestController
@RequestMapping("/sdust/v1/sdcNode")
public class SdcNodeController {
@Autowired
private SdcNodeApp sdcNodeApp;
……
}
- 方法注解
@ResponseBody
我們只需要在某個方法上寫上注解 @ResponseBody
,那么該方法返回格式是text/json
。如下圖
/*類注解*/
@Controller
@RequestMapping("/sdust/v1/sdcNode")
public class SdcLnodeController {
@Autowired
private SdcNodeApp sdcNodeApp;
@RequestMapping("/lef")
@ResponseBody
public String getInfo() {
return "";
}
……
}
值得提醒的是,雖然都是都可以,但更推薦使用類注解,會顯得我們的編碼風格十分統一,代碼更加緊湊,不至于看起來零散。
我們來看下 @RestController
的源碼
@Controller
@ResponseBody
public @interface RestController {
……
}
請求方式源碼
@RequestMapping
在``RequestMapping`的源碼中提到,這種支持任意請求方式,類似于自適應。
@Mapping
public @interface RequestMapping {
……
}
@GetMapping
客戶端只能用 GET
方式請求,適用于查詢數據
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping{
……
}
@PostMapping
客戶端只能用 POST
方式請求,適用于提交數據。
@RequestMapping(method = RequestMethod.POST)
public @interface PostMapping{
……
}
@DeleteMapping
客戶端只能用 DELETE
方式請求,使用于刪除數據。
@RequestMapping(method = RequestMethod.DELETE)
public @interface DeleteMapping{
……
}
@PutMapping
客戶端只能用 PUT
方式請求,使用于修改數據(但在實際使用中,我個人建議還是采用POST方式較為妥當)。
@RequestMapping(method = REquestMethod.PUT)
public @interface PutMapping{
……
}
以上請求我是在接口開發中經常使用的,圖片是注解源碼。當然還有其他一些。關于請求方式及使用范圍,可以參考 RESTful API
接收參數
@RequestParam
我們來寫一個示例并說明:
public String getInfo(@RequestParam(name = "param",
required = false,
defaultValue = "param dafault value") String param)
name
代表提交參數名。
required
意思是這個參數是否必需,默認true,沒有該參數,無法調用此方法;這里設為false,有無該參數都可以調用。
defaultValue
如果該參數值為空,那么就使用默認值。
@PathVariable
@RequestMapping("/get-info/{param}")
public String getInfo(@PathVariable("param") Object param)
我們可以在請求方法后面直接跟值,省去了 ?參數名=
。
這種一般配合 @DeleteMapping
、@PutMapping
使用。
@RequestHeader
這個使用了獲取提交數據的 Headers
的值。我是用來接收 TOKEN
。后面會舉例。
數據格式
下面我們來了解下,Spring Boot 可以支持的數據格式。
我一般常用的基本數據類型有 int
、String
。
而我們在日常中,還可能有 Array
、List
、Map
……
那么,Spring Boot支持嗎?我們如何解決?并且統一化呢?
JSON!
毫無疑問JSON可以幫助我們解決這個問題,當然XML也是可以的。
在Controller層當中使用一些封裝的方法,講實現的內容封裝到自己定義的數據結構中返回給前端就可以實現通過JSON傳遞數據
至于前端方面,先看 Ajax
代碼:
$.ajax({
headers : {
Accept: "application/json; charset=utf-8",
'token' : '9B4BF951093F1F1A40BB2DAAA30B3838'
},
url: URI + '/admin/blog/add',
type: 'POST',
async: true,
data: {
...
},
timeout: 3000,
dataType: 'json',
beforeSend: function(xhr){},
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(xhr, textStatus){
console.log(xhr);
},
complete: function(){}
})
現在的問題是如何獲取 token
的值?沒錯,就是 @RequestHeader("token")
!
如果我們沒在Controller,那怎么辦
答案是
String token = request.getHeader("token");
System.out.println(token);