@RestController和@Controller注解
RestController的作用相當于Controller加ResponseBody共同作用的結果,但采用RestController請求方式一般會采用Restful風格的形式,
Controller的作用:宣告該類是Controller層的Bean,將該類宣告進入Spring容器中進行管理
ResponseBody的作用:表明該類的所有方法的回傳值都直接進行提交而不經過視圖決議器,且回傳值的資料自動封裝為json的資料格式
RestController的作用:包含上面兩個的作用,且支持Restful風格的資料提交方式
@RestController原始碼如下,
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented@Controller
@ResponseBodypublic @interface RestController {
/** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any * @since 4.0.1 */
String value() default "";
}
? @RestController的撰寫方式依賴注解組合,@RestController被@Controller和@ResponseBody標注,表示@RestController具有兩者的注解語意,因此在注解處理時@RestController比@Controller多具有一個@ResponseBody語意,這就是@RestController和@Controller的區別,也是@RestController的回傳值為何都是經過轉換的json的原因,
@ResponseBody注解的處理程序
? 既然知道@RestController與@Controller的區別是多了一個@ResponseBody語意,我們不妨了解一下@ResponseBody的處理程序,
首先,可以知道,@ResponseBody是一個針對方法回傳值進行處理的注解,如果熟悉Spring MVC處理程序的話,可以知道在根據requesturl映射獲取到HandlerMethod之后,根據HandlerMethod調度請求方法的物件是HandlerAdapter,方法呼叫結束,回傳值處理的調度物件也是HandlerAdapter,所以,@ResponseBody注解的處理應該也是在HandlerAdapter中完成,
Restful風格:
get:獲取資料時用的請求方式
post:更新資料時的請求方式
put:增加資料時的請求方式
delete:洗掉資料時的請求方式
查考檔案:https://blog.csdn.net/uuqaz/article/details/123919771
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/502284.html
標籤:Java
