SpringMVC中常用的注解分析_第1頁
SpringMVC中常用的注解分析_第2頁
SpringMVC中常用的注解分析_第3頁
SpringMVC中常用的注解分析_第4頁
SpringMVC中常用的注解分析_第5頁
已閱讀5頁,還剩5頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、 SpringMVC中常用的注解 spring從2.5版本開始在編程中引入注解,用戶可以使用RequestMapping, RequestParam, ModelAttribute等等這樣類似的注解。到目前為止,Spring的版本雖然發(fā)生了很大的變化,但注解的特性卻是一直延續(xù)下來,并不斷擴展,讓廣大的開發(fā)人員的雙手變的更輕松起來,這都離不開Annotation的強大作用,今天我們就一起來看看Spring MVC 4中常用的那些注解吧。     1. Controller     Controll

2、er控制器是通過服務(wù)接口定義的提供訪問應(yīng)用程序的一種行為,它解釋用戶的輸入,將其轉(zhuǎn)換成一個模型然后將試圖呈獻給用戶。Spring MVC 使用 Controller 定義控制器,它還允許自動檢測定義在類路徑下的組件并自動注冊。如想自動檢測生效,需在XML頭文件下引入 spring-context:12345678910111213<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/sch

3、ema/beans"    xmlns:xsi="/2001/XMLSchema-instance"    xmlns:p="/schema/p"    xmlns:context="/schema/context"    

4、;xsi:schemaLocation="        /schema/beans        /schema/beans/spring-beans.xsd        

5、/schema/context        /schema/context/spring-context.xsd">     <context:component-scan base-package="org.springframework.samples.petclinic.web"/>     &

6、lt;!- . -></beans>     2. RequestMapping     我們可以 RequestMapping 注解將類似 “/favsoft”這樣的URL映射到整個類或特定的處理方法上。一般來說,類級別的注解映射特定的請求路徑到表單控制器上,而方法級別的注解只是映射為一個特定的HTTP方法請求(“GET”,“POST”等)或HTTP請求參數(shù)。 1234567891011121314151617181920212223242526272829303132333

7、43536ControllerRequestMapping("/favsoft")public class AnnotationController          RequestMapping(method=RequestMethod.GET)    public String get()        retur

8、n ""             RequestMapping(value="/getName", method = RequestMethod.GET)    public String getName(String userName)       

9、;  return userName;             RequestMapping(value="/day", method=RequestMethod.GET)    public String getDay(Date day)        Da

10、teFormat df = new SimpleDateFormat("yyyy-MM-dd");        return df.format(day);             RequestMapping(value="/addUser", method=RequestMethod

11、.GET)    public String addFavUser(Validated FavUser favUser,BindingResult result)        if(result.hasErrors()            return "favUser"&#

12、160;               /favUserService.addFavUser(favUser);        return "redirect:/favlist"         RequestMapping("/test&

13、quot;)    ResponseBody    public String test()        return "aa"              RequestMapping 既可以作用在類級別,也可以作用在方法級別。當它定義在類級別時,標明該控制器處理所有

14、的請求都被映射到 /favsoft 路徑下。RequestMapping中可以使用 method 屬性標記其所接受的方法類型,如果不指定方法類型的話,可以使用 HTTP GET/POST 方法請求數(shù)據(jù),但是一旦指定方法類型,就只能使用該類型獲取數(shù)據(jù)。     RequestMapping 可以使用 Validated與BindingResult聯(lián)合驗證輸入的參數(shù),在驗證通過和失敗的情況下,分別返回不同的視圖。     RequestMapping支持使用URI模板訪問URL。URI模板像是URL模樣的字符串,由一個或多個變量名字組成,

15、當這些變量有值的時候,它就變成了URI。   3. PathVariable     在Spring MVC中,可以使用 PathVariable 注解方法參數(shù)并將其綁定到URI模板變量的值上。如下代碼所示:  String findOwner( String , Model model)     FavUser favUser = favUserService.findFavUser();

16、60;   model.addAttribute(       URI模板 “favusers/favUserId"指定變量的名字 favUserId ,當控制器處理這個請求的時候, favUserId的值會被設(shè)定到URI中。比如,當有一個像“favusers/favccxx”這樣的請求時,favUserId的值就是 favccxx。     PathVariable 可以有多個注解,像下面這樣: RequestMapping(value=&qu

17、ot;/owners/ownerId/pets/petId", method=RequestMethod.GET)public String findPet(PathVariable String ownerId, PathVariable String petId, Model model)     Owner owner = ownerService.findOwner(ownerId); &

18、#160;  Pet pet = owner.getPet(petId);    model.addAttribute("pet", pet);    return "displayPet"        PathVariable中的參數(shù)可以是任意的簡單類型,如int, long, Date等等。Spring會自動將其轉(zhuǎn)換成合適

19、的類型或者拋出 TypeMismatchException異常。當然,我們也可以注冊支持額外的數(shù)據(jù)類型。     如果PathVariable使用Map<String, String>類型的參數(shù)時, Map會填充到所有的URI模板變量中。     PathVariable支持使用正則表達式,這就決定了它的超強大屬性,它能在路徑模板中使用占位符,可以設(shè)定特定的前綴匹配,后綴匹配等自定義格式。      PathVariable還支持矩陣變量,因為現(xiàn)實場景中用的不多,這就不詳細介紹了,有

20、需要的童鞋請查看官網(wǎng)的文檔。     4. RequestParam     RequestParam將請求的參數(shù)綁定到方法中的參數(shù)上,如下面的代碼所示。其實,即使不配置該參數(shù),注解也會默認使用該參數(shù)。如果想自定義指定參數(shù)的話,如果將RequestParam的 required 屬性設(shè)置為false(如RequestParam(value="id",required=false)。     5. RequestBody   &

21、#160; RequestBody是指方法參數(shù)應(yīng)該被綁定到HTTP請求Body上。 RequestMapping(value = "/something", method = RequestMethod.PUT)public void handle(RequestBody String body, Writer writer) throws IOException     writer.

22、write(body);    如果覺得RequestBody不如RequestParam趁手,我們可以使用 HttpMessageConverter將request的body轉(zhuǎn)移到方法參數(shù)上, HttMessageConverser將 HTTP請求消息在Object對象之間互相轉(zhuǎn)換,但一般情況下不會這么做。事實證明,RequestBody在構(gòu)建REST架構(gòu)時,比RequestParam有著更大的優(yōu)勢。    6. ResponseBody     ResponseBody與RequestBod

23、y類似,它的作用是將返回類型直接輸入到HTTP response body中。ResponseBody在輸出JSON格式的數(shù)據(jù)時,會經(jīng)常用到,代碼見下圖: RequestMapping(value = "/something", method = RequestMethod.PUT)ResponseBodypublic String helloWorld()     return "Hello World"

24、     7. RestController        我們經(jīng)常見到一些控制器實現(xiàn)了REST的API,只為服務(wù)于JSON,XML或其它自定義的類型內(nèi)容,RestController用來創(chuàng)建REST類型的控制器,與Controller類型。RestController就是這樣一種類型,它避免了你重復(fù)的寫RequestMapping與ResponseBody。 RestControllerpublic class FavRestfulController  RequestMapping

25、(value="/getUserName",method=RequestMethod.POST)public String getUserName(RequestParam(value="name") String name)return name;     8. HttpEntity     HttpEntity除了能獲得request請求和response響應(yīng)之外,它還能訪問請求和響應(yīng)頭,如下所示: RequestMapping("/something"

26、;)public ResponseEntity<String> handle(HttpEntity<byte> requestEntity) throws UnsupportedEncodingException     String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader");    

27、byte requestBody = requestEntity.getBody();    / do something with request header and body    HttpHeaders responseHeaders = new HttpHeaders();    responseHeaders.set(&quo

28、t;MyResponseHeader", "MyValue");    return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);     9. ModelAttribute    ModelAttribute可以作用在方法或方法參數(shù)

29、上,當它作用在方法上時,標明該方法的目的是添加一個或多個模型屬性(model attributes)。該方法支持與RequestMapping一樣的參數(shù)類型,但并不能直接映射成請求??刂破髦械腗odelAttribute方法會在RequestMapping方法調(diào)用之前而調(diào)用,示例如下: ModelAttributepublic Account addAccount(RequestParam String number)     return accountManager.findAccount(nu

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論