Spring MVC 常用以下幾個注解
-
@Controller
@Controller
注解在類上,表明這個類是Spring MVC里的Controller,將其聲明為Spring的一個Bean,Dispatcher Servlet 會自動 掃描注解了此注解的類坑鱼,并將Web請求映射到了注解了@RequestMapping
的方法上持灰。這里特別指出,在聲明普通Bean時怎燥,使用@Component
瘫筐、@Service
、@Repository
和@Controller
是等同的铐姚,因為@Service
策肝、@Repository
、@Controller
都組合了@Component
元注解隐绵;但在Spring MVC 聲明控制器Bean的時候之众,只能使用@Controller
。
-
@RequestMapping
@RequestMapping
注解是用來映射web請求(訪問路徑和參數(shù))依许、處理類和方法的酝枢。
@RequestMapping
可注解在類或方法上。注解在方法上的@RequestMapping
路徑會繼承注解在類上的路徑悍手,@RequestMapping
支持Servlet
的request
和 response
作為參數(shù)帘睦,也支持對request
和 response
的媒體類型進(jìn)行配置。
-
@ResponseBody
@ResponseBody
支持將返回值放在 response 體內(nèi)坦康,而不是返回一個頁面竣付。我們在很多基于Ajax
的程序時,可以以此注解返回數(shù)據(jù) 而不是頁面滞欠;此注解可放置在返回值前或者方法上古胆。
-
@RequestBody
@RequestBody
允許request
的參數(shù)在request
體中,而不是直接鏈接在地址后面。此注解放置在參數(shù)前逸绎。
-
@PathVariable
@PathVariable
用來接收路徑參數(shù)惹恃,如 /news/2016-11-11
,可接收2016-11-11
作為參數(shù)棺牧,此注解放置在參數(shù)前巫糙。
-
@RestController
@RestController
是一個組合 注解,組合了@Controller
和 @ ResponseBody
颊乘,這就意味著當(dāng)你只開發(fā)一個和頁面交互數(shù)據(jù)的控制的時候参淹,需要使用此注解。若沒有此注解乏悄,要想實現(xiàn)上述功能浙值,則需要自己在代碼中加@Controller
和 @ResponseBody
兩個注解。