@RequestMapping
?是 Spring 框架中用于映射 HTTP 請求到控制器方法的注解。它支持以下 HTTP 方法訪問類型,通過?method
?屬性指定:
- GET:用于獲取資源
- POST:用于提交數據
- PUT:用于更新資源
- DELETE:用于刪除資源
- PATCH:用于部分更新資源
- HEAD:類似于 GET 請求,但只返回狀態行和頭信息
- OPTIONS:返回服務器支持的 HTTP 方法
現實情況GET方法和POST方法的使用占很大的部分,主要講解GET和POST方法的使用,其他方法舉一反三就可以了
1.所有方法都可以訪問情況
@RequestMapping可以是類注解也可以是方法注解,加在類上或者加在方法上都可以,一般來說都建議在類上面加上,因為方便我們快速的定位問題。
@RestController @RequestMapping("/user") //第一層路徑 public class UserController {@RequestMapping("/u1") //第二層路徑public String u1() {return "hello u1";} }
將程序運行起來后,通過瀏覽器輸入 http://localhost:8080/user/u1 訪問,當然端口有可能不是8080,在運行的時候看一下就可以了
結果:
1.1 類注解可以不寫,但是一般建議寫上
@RestController public class UserController {@RequestMapping("/u1")public String u1() {return "hello u1";} }
1.2 在寫路徑的時候不寫 “/” 也可以,但是最好加上,這算是行業內的規范
@RequestMapping("user") public class UserController {@RequestMapping("u1")public String u1() {return "hello u1";} }
1.3 也可以寫多層路徑
@RestController @RequestMapping("/user") public class UserController {@RequestMapping("/u/u1")public String u1() {return "hello u1";} }
?
2. 限制特定的方法訪問
這里我只舉例get的訪問方式,之后的簡單介紹一下就ok了
在注解中添加method屬性,可以通過這些屬性設置訪問的限定方式:
@RequestMapping添加method屬性
@RestController @RequestMapping("/user") public class UserController {@RequestMapping(value = "/u1", method = RequestMethod.GET)public String u1() {return "hello u1";} }
或者使用
@GetMapping
@RestController @RequestMapping("/user") public class UserController {// @RequestMapping(value = "/u1", method = RequestMethod.GET)@GetMapping("/u1")//就只能被get方法訪問public String u1() {return "hello u1";} }
不同方法測試
這里我們用postman來測試,不同的方法是否可以訪問:
測試get方法:
測試post方法:
?
3.其他方法
?
快捷注解
為簡化開發,Spring 還提供了針對特定 HTTP 方法的快捷注解:
??
@GetMapping
:等同于?@RequestMapping(method = RequestMethod.GET)
@PostMapping
:等同于?@RequestMapping(method = RequestMethod.POST)
@PutMapping
:等同于?@RequestMapping(method = RequestMethod.PUT)
@DeleteMapping
:等同于?@RequestMapping(method = RequestMethod.DELETE)
@PatchMapping
:等同于?@RequestMapping(method = RequestMethod.PATCH)
這些快捷注解使代碼更簡潔易讀,推薦優先使用。