1,前置知識點
1.1 @GetMapping,@PostMapping,@PutMapping,@DeleteMapping
平時我們都是使用@RequestMapping,然后通過它的method屬性來指定請求的方式,這樣是有些麻煩的,然后這四個標簽就是來簡化這一點的,具體如下,
@GetMapping = @RequestMapping(method = RequestMethod.GET)
@PostMapping = @RequestMapping(method = RequestMethod.POST)
@PutMapping = @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)
1.2 @PathVariable
@PathVariable是Spring MVC中的注解,用于從URL路徑中提取變量值并將其綁定到方法參數(shù)上。它通常與@RequestMapping一起使用。
使用@PathVariable注解可以方便地獲取REST風格URL路徑中的變量值,并將其作為方法參數(shù)使用。
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("book query ..." + id );
return "{'module':'book query'}";
}
在getUserById方法上,我們使用@GetMapping(“/{id}”)將方法與URL路徑/books/{id}進行映射。{id}表示一個占位符,它對應URL路徑中的實際值。
然后,我們在方法參數(shù)上使用@PathVariable注解,將id參數(shù)與URL路徑中的實際值進行綁定。Spring MVC會自動提取URL路徑中的相應部分,并將其作為參數(shù)傳遞給getUserById方法。
例如,當客戶端發(fā)送GET請求到/books/1時,Spring MVC將提取URL中的1作為id參數(shù)的值,并將其傳遞給getById方法。在方法內(nèi)部,我們可以使用id來執(zhí)行相應的邏輯操作,比如根據(jù)用戶ID查詢用戶信息。
1.3 按照REST風格訪問資源時,使用行為動作區(qū)分對資源進行了何種操作
http://localhost:8080/books 查詢所有圖書信息 GET(查詢)
http://localhost:8080/books/1 查詢指定圖書信息 GET(查詢)
http://localhost:8080/books 添加圖書信息 POST(新增/保存)
http://127.0.0.1:8080/books 修改用戶信息 PUT(修改/更新)
http://localhost:8080/books/1 刪除用戶信息 DELETE(刪除)
2,代碼演示
controller類
package com.hkd.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping
public String query(){
System.out.println("book query..." );
return "{'module':'book query'}";
}
@PostMapping
public String save(){
System.out.println("book save..." );
return "{'module':'book save'}";
}
@PutMapping
public String update(){
System.out.println("book update..." );
return "{'module':'book update'}";
}
@DeleteMapping("/{id}")
public String update(@PathVariable Integer id){
System.out.println("book delete ..." + id );
return "{'module':'book delete'}";
}
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("book query ..." + id );
return "{'module':'book query'}";
}
}
使用postman測試
以查詢所有和刪除為例演示
查詢所有
刪除圖書
文章來源:http://www.zghlxwxcb.cn/news/detail-722334.html
…文章來源地址http://www.zghlxwxcb.cn/news/detail-722334.html
到了這里,關(guān)于Rest風格基本語法與實戰(zhàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!