Controller層注解詳解


可根據右邊目錄快速瀏覽

@Controller

處理http請求,在對應的方法上視圖解析器可以解析return中的jsp或html頁面,並且跳轉到相應頁面

@RestController

在默認情況下,使用了 @RestController 注解即可將返回的數據結構轉換成 Json 格式

@RestController注解相當於@ResponseBody + @Controller合在一起的作用(好吧我感覺我自己在講廢話,是本書上都這么寫)

So想理解@RestController我們就要點進去看一下該注解都包含了哪些東西。

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

可以看到 @RestController注解包含了原來的 @Controller@ResponseBody 注解,@ResponseBody注解是將返回的數據結構轉換為 Json 格式。所以在默認情況下,使用了 @RestController 注解即可將返回的數據結構轉換成 Json 格式

@GetMapping

用於將HTTP GET請求映射到特定處理程序方法的注釋。

里面最重要的就是這一句@RequestMapping(method = {RequestMethod.GET})

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
    method = {RequestMethod.GET}
)
public @interface GetMapping {

@PostMapping

用於將HTTP POST請求映射到特定處理程序方法的注釋。

里面最重要的就是這一句@RequestMapping(method = {RequestMethod.POST})可以看出@GetMapping和@PostMapping的區別並不大

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
    method = {RequestMethod.POST}
)
public @interface PostMapping {

@RequestMapping

當你還在猶豫用@GetMapping還是@PostMapping時用他們爸爸(@RequestMapping)就對了

@PathVariable

只支持一個屬性value,類型是為String,代表綁定的屬性名稱。默認不傳遞時,綁定為同名的形參。

@RequestBody

在后端的同一個接收方法里,@RequestBody與@RequestParam()可以同時使用,@RequestBody最多只能有一個,而@RequestParam()可以有多個

用來接收前端傳遞給后端的 JSON 字符串中的數據,但只能使用 POST 的方式提交數據

參考

@PathVariable注解使用

@RequestMapping與@GetMapping和@PostMapping區別


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM