Spring從2.5版本開始在編程中引入注解,用戶可以使用@RequestMapping, @RequestParam, @ModelAttribute等等這樣類似的注解。到目前為止,Spring的版本雖然發生了很大的變化,但注解的特性卻是一直延續下來,并不斷擴展,讓廣大的開發人員的雙手變的更輕松起來,這都離不開Annotation的強大作用,今天我們就一起來看看Spring MVC 4中常用的那些注解吧。
1. @Controller
Controller控制器是通過服務接口定義的提供訪問應用程序的一種行為,它解釋用戶的輸入,將其轉換成一個模型然后將試圖呈獻給用戶。Spring MVC 使用 @Controller 定義控制器,它還允許自動檢測定義在類路徑下的組件并自動注冊。如想自動檢測生效,需在XML頭文件下引入 spring-context:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<? xml version = "1.0" encoding = "UTF-8" ?>< beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:p = "http://www.springframework.org/schema/p" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> < context:component-scan base-package = "org.springframework.samples.petclinic.web" /> <!-- ... --> </ beans > |
2. @RequestMapping
我們可以 @RequestMapping 注解將類似 “/favsoft”這樣的URL映射到整個類或特定的處理方法上。一般來說,類級別的注解映射特定的請求路徑到表單控制器上,而方法級別的注解只是映射為一個特定的HTTP方法請求(“GET”,“POST”等)或HTTP請求參數。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
@Controller @RequestMapping ( "/favsoft" ) public class AnnotationController { @RequestMapping (method=RequestMethod.GET) public String get(){ return "" ; } @RequestMapping (value= "/getName" , method = RequestMethod.GET) public String getName(String userName) { return userName; } @RequestMapping (value= "/{day}" , method=RequestMethod.GET) public String getDay(Date day){ DateFormat df = new SimpleDateFormat( "yyyy-MM-dd" ); return df.format(day); } @RequestMapping (value= "/addUser" , method=RequestMethod.GET) public String addFavUser( @Validated FavUser favUser,BindingResult result){ if (result.hasErrors()){ return "favUser" ; } //favUserService.addFavUser(favUser); return "redirect:/favlist" ; } @RequestMapping ( "/test" ) @ResponseBody public String test(){ return "aa" ; } } |
@RequestMapping 既可以作用在類級別,也可以作用在方法級別。當它定義在類級別時,標明該控制器處理所有的請求都被映射到 /favsoft 路徑下。@RequestMapping中可以使用 method 屬性標記其所接受的方法類型,如果不指定方法類型的話,可以使用 HTTP GET/POST 方法請求數據,但是一旦指定方法類型,就只能使用該類型獲取數據。
@RequestMapping 可以使用 @Validated與BindingResult聯合驗證輸入的參數,在驗證通過和失敗的情況下,分別返回不同的視圖。
@RequestMapping支持使用URI模板訪問URL。URI模板像是URL模樣的字符串,由一個或多個變量名字組成,當這些變量有值的時候,它就變成了URI。
3. @PathVariable
在Spring MVC中,可以使用 @PathVariable 注解方法參數并將其綁定到URI模板變量的值上。如下代碼所示:
1
2
3
4
5
|
String findOwner( String , Model model) { FavUser favUser = favUserService.findFavUser(); model.addAttribute( ; } |
URI模板 “favusers/{favUserId}"指定變量的名字 favUserId ,當控制器處理這個請求的時候, favUserId的值會被設定到URI中。比如,當有一個像“favusers/favccxx”這樣的請求時,favUserId的值就是 favccxx。
@PathVariable 可以有多個注解,像下面這樣:
1
2
3
4
5
|
@RequestMapping (value= "/owners/{ownerId}/pets/{petId}" , method=RequestMethod.GET) public String findPet( @PathVariable String ownerId, @PathVariable String petId, Model model) { Owner owner = ownerService.findOwner(ownerId); Pet pet = owner.getPet(petId); model.addAttribute( "pet" , pet); return "displayPet" ; } |
@PathVariable中的參數可以是任意的簡單類型,如int, long, Date等等。Spring會自動將其轉換成合適的類型或者拋出 TypeMismatchException異常。當然,我們也可以注冊支持額外的數據類型。
如果@PathVariable使用Map<String, String>類型的參數時, Map會填充到所有的URI模板變量中。
@PathVariable支持使用正則表達式,這就決定了它的超強大屬性,它能在路徑模板中使用占位符,可以設定特定的前綴匹配,后綴匹配等自定義格式。
@PathVariable還支持矩陣變量,因為現實場景中用的不多,這就不詳細介紹了,有需要的童鞋請查看官網的文檔。
4. @RequestParam
@RequestParam將請求的參數綁定到方法中的參數上,如下面的代碼所示。其實,即使不配置該參數,注解也會默認使用該參數。如果想自定義指定參數的話,如果將@RequestParam的 required 屬性設置為false(如@RequestParam(value="id",required=false))。
5. @RequestBody
@RequestBody是指方法參數應該被綁定到HTTP請求Body上。
1
2
3
|
@RequestMapping (value = "/something" , method = RequestMethod.PUT) public void handle( @RequestBody String body, Writer writer) throws IOException { writer.write(body); } |
如果覺得@RequestBody不如@RequestParam趁手,我們可以使用 HttpMessageConverter將request的body轉移到方法參數上, HttMessageConverser將 HTTP請求消息在Object對象之間互相轉換,但一般情況下不會這么做。事實證明,@RequestBody在構建REST架構時,比@RequestParam有著更大的優勢。
6. @ResponseBody
@ResponseBody與@RequestBody類似,它的作用是將返回類型直接輸入到HTTP response body中。@ResponseBody在輸出JSON格式的數據時,會經常用到,代碼見下圖:
1
2
|
@RequestMapping (value = "/something" , method = RequestMethod.PUT) @ResponseBodypublic String helloWorld() { return "Hello World" ; } |
7. @RestController
我們經常見到一些控制器實現了REST的API,只為服務于JSON,XML或其它自定義的類型內容,@RestController用來創建REST類型的控制器,與@Controller類型。@RestController就是這樣一種類型,它避免了你重復的寫@RequestMapping與@ResponseBody。
1
2
3
4
5
6
7
8
|
@RestController public class FavRestfulController { @RequestMapping (value= "/getUserName" ,method=RequestMethod.POST) public String getUserName( @RequestParam (value= "name" ) String name){ return name; } } |
8. HttpEntity
HttpEntity除了能獲得request請求和response響應之外,它還能訪問請求和響應頭,如下所示:
1
2
3
4
5
6
|
@RequestMapping ( "/something" ) public ResponseEntity<String> handle(HttpEntity< byte []> requestEntity) throws UnsupportedEncodingException { String requestHeader = requestEntity.getHeaders().getFirst( "MyRequestHeader" )); byte [] requestBody = requestEntity.getBody(); // do something with request header and body HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set( "MyResponseHeader" , "MyValue" ); return new ResponseEntity<String>( "Hello World" , responseHeaders, HttpStatus.CREATED); } |
9. @ModelAttribute
@ModelAttribute可以作用在方法或方法參數上,當它作用在方法上時,標明該方法的目的是添加一個或多個模型屬性(model attributes)。該方法支持與@RequestMapping一樣的參數類型,但并不能直接映射成請求。控制器中的@ModelAttribute方法會在@RequestMapping方法調用之前而調用,示例如下:
1
2
3
4
5
6
7
8
9
10
|
@ModelAttribute public Account addAccount( @RequestParam String number) { return accountManager.findAccount(number); } @ModelAttribute public void populateModel( @RequestParam String number, Model model) { model.addAttribute(accountManager.findAccount(number)); // add more ... } |
@ModelAttribute方法用來在model中填充屬性,如填充下拉列表、寵物類型或檢索一個命令對象比如賬戶(用來在HTML表單上呈現數據)。
@ModelAttribute方法有兩種風格:一種是添加隱形屬性并返回它。另一種是該方法接受一個模型并添加任意數量的模型屬性。用戶可以根據自己的需要選擇對應的風格。
@ModelAttribute作用在方法參數上
當@ModelAttribute作用在方法參數上時,表明該參數可以在方法模型中檢索到。如果該參數不在當前模型中,該參數先被實例化然后添加到模型中。一旦模型中有了該參數,該參數的字段應該填充所有請求參數匹配的名稱中。這是Spring MVC中重要的數據綁定機制,它省去了單獨解析每個表單字段的時間。
@ModelAttribute是一種很常見的從數據庫中檢索屬性的方法,它通過@SessionAttributes使用request請求存儲。在一些情況下,可以很方便的通過URI模板變量和類型轉換器檢索屬性。