【SpringBoot註解-5】web項目相關注解


本文將對前文出現的一系列MVC註解,包括 @RestController、 @RequestMapping、@PathVariable、@RequestParam 以及 @RequestBody,進行更詳細地解析與總結。

@RestController

@RestController 是MVC中應用非常頻繁的一個註解,也是 SpringBoot 新增的一個註解,包括:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    String value() default "";
}

@RestController作用是,返回JSON格式的數據,可以看作是 @Controller 和 @ResponseBody 的結合體。

@RequestMapping

@RequestMapping 是一個用來處理請求地址映射的註解,它可以用於類上,也可以用於方法上。用於類上的註解會將一個特定請求或者請求模式映射到一個控制器之上,表示類中的所有響應請求的方法都是以該地址作爲父路徑;方法的級別上註解表示進一步指定到處理方法的映射關係。
該註解有 6 個屬性,一般在項目中比較常用的有 3 個屬性:value、method 和 produces。

  1. value 屬性:指定請求的實際地址,value 可以省略不寫。
  2. method 屬性:指定請求的類型,主要有GET、PUT、POST、DELETE,默認爲 GET。
  3. produces 屬性:指定返回內容類型。

@RequestMapping 使用示例:

@RestController
@RequestMapping(value = "/test", produces = "application/json; charset=UTF-8")
public class TestController {

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public String testGet() {
        return "SUCCESS";
    }
}

啓動項目在瀏覽器中輸入:localhost:8080/test/get 即可。(8080由配置文件配置)。

爲了簡化使用,四種請求方法都有相應的註解,無需在 @RequestMapping 註解中加 method 屬性來指定,上面的 GET方式請求可以直接使用 @GetMapping("/get") 註解,效果一樣。相應地,PUT 方式、POST 方式和 DELETE方式對應的註解分別爲 @PutMapping、@PostMapping 和 DeleteMapping。

@PathVariable

@PathVariable 註解主要用來獲取 URL 參數,Spring Boot 支持 Restfull 風格的 URL,比如一個 GET 請求攜帶一個參數 id,我們將 id 作爲參數接收,可以使用 @PathVariable 註解。如下:

@GetMapping("/student/{id}")
public String testPathVariable(@PathVariable Integer id) {
    System.out.println("獲取到的id爲:" + id);
    return "success";
}

對於URL,佔位符可以在任何位置,不一定非要在最後,比如這樣:/xxx/{id}/student。此外,URL 還支持多佔位符,方法參數使用同樣數量的參數來接收,例如:

@GetMapping("/student/{idd}/{name}")
public String testPathVariable(@PathVariable(value = "idd") Integer id, @PathVariable String name) {
    System.out.println("獲取到的id爲:" + id);
    System.out.println("獲取到的name爲:" + name);
    return "success";
}

運行項目,在瀏覽器中請求:localhost:8080/test/student/2/xiaohong, 可以看到控制檯輸出如下信息:

獲取到的id爲:2
獲取到的name爲:xiaohong

所以它支持多個參數的接收。同樣地,如果 URL 中的參數和方法中的參數名稱不同的話,也需要使用 value 屬性來綁定兩個參數。

@RequestParam

@RequestParam 也是獲取請求參數的,@RequestParam 和 @PathVariable 有什麼不同呢?
主要區別在於: @PathValiable 是從 URL 模板中獲取參數值:
http://localhost:8080/student/{id};
而 @RequestParam 是從 Request 裏獲取參數值:
http://localhost:8080/student?id=1。
我們使用該 URL 帶上參數 id 來測試下如下代碼:

@GetMapping("/student")
public String testRequestParam(@RequestParam Integer id) {
    System.out.println("前端傳入的id爲:" + id);
    return "success";
}

可以正常從控制檯打印出 id 信息。同樣地,URL 上面的參數和方法的參數需要一致,如果不一致,也需要使用 value 屬性來說明,比如 URL 爲:http://localhost:8080/student?idd=1。

@RequestMapping("/user")
public String testRequestParam(@RequestParam(value = "idd", required = false) Integer id) {
    System.out.println("前端傳入的id爲:" + id);
    return "success";
}

除了 value 屬性外,還有兩個屬性比較常用。

  1. required 屬性:true 表示該參數必傳,否則就會報 404 錯誤,false 表示傳不傳皆可。
  2. defaultValue屬性:默認值,表示請求中沒有同名參數時的默認值。

從 URL 中可以看出,@RequestParam 註解用於 GET 請求上時,接收拼接在 URL 中的參數。除此之外,該註解還可以用於 POST 請求,接收前端表單提交的參數,假如前端通過表單提交 username 和 password 兩個參數,那我們可以使用 @RequestParam 來接收,用法和上面一樣。

@PostMapping("/form")
public String testForm(@RequestParam String username, @RequestParam String password) {
    System.out.println("前端傳入的username爲:" + username);
    System.out.println("前端傳入的password爲:" + password);
    return "SUCCESS";
}

我們使用 Postman 來模擬一下表單提交,測試一下接口:
在這裏插入圖片描述如果表單數據很多,我們不可能在後臺方法中寫上很多參數,每個參數還要 @RequestParam 註解。針對這種情況,我們需要封裝一個實體類來接收這些參數,實體中的屬性名和表單中的參數名一致即可。

public class Student{
    private String username;
    private String password;
    // set get
}

使用實體接收的話,我們不必在前面加 @RequestParam 註解,直接使用即可。

@PostMapping("/form2")
public String testForm(Student student) {
    System.out.println("前端傳入的username爲:" + username);
    System.out.println("前端傳入的password爲:" + password);
    return "SUCCESS";
}

實際項目中,表單數據一般都有很多,這時需要封裝一個實體類來接收表單數據。

@RequestBody

@RequestBody 註解用於接收前端傳來的實體,接收參數也是對應的實體,比如前端通過 JSON 提交傳來兩個參數 username 和 password,此時我們需要在後端封裝一個實體來接收。在傳遞的參數比較多的情況下,使用 @RequestBody 接收會非常方便。例如:

public class Student {
    private String username;
    private String password;
    // set get
}
@PostMapping("/user")
public String testRequestBody(@RequestBody Student student) {
    System.out.println("前端傳入的username爲:" + username);
    System.out.println("前端傳入的password爲:" + password);
    return "SUCCESS";
}

我們使用 Postman 工具來測試一下效果,打開 Postman,輸入請求地址和參數,參數我們用 JSON 來模擬,如下圖所有,調用之後返回 success。
在這裏插入圖片描述
同時看一下後臺控制檯輸出的日誌:

獲取到的username爲:xiaohong
獲取到的password爲:12345678

可以看出,@RequestBody 註解用於 POST 請求上,接收 JSON 實體參數。它和上面我們介紹的表單提交有點類似,只不過參數的格式不同,一個是 JSON 實體,一個是表單提交。在實際項目中根據具體場景和需要使用對應的註解即可。

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