Spring從2.5版本開始在編程中引入註解,用戶可以使用@RequestMapping, @RequestParam, @ModelAttribute等等這樣類似的註解。到目前為止,Spring的版本雖然發生了很大的變化,但註解的特性卻是一直延續下來,並不斷擴展,讓廣大的開發人員的雙手變的更輕鬆起來,這都離不開Annotation的強大作用,今天我們就一起來看看Spring MVC 4中常用的那些註解吧。
1. @Controller
Controller控制器是通過服務接口定義的提供訪問應用程序的一種行為,它解釋用戶的輸入,將其轉換成一個模型然後將試圖呈獻給用戶。Spring MVC 使用 @Controller 定義控制器,它還允許自動檢測定義在類路徑下的組件並自動註冊。如想自動檢測生效,需在XML頭文件下引入 spring-context:
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請求參數。
@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模板變量的值上。如下代碼所示:
String findOwner( String , Model model) {
FavUser favUser = favUserService.findFavUser();
model.addAttribute(
;
}
URI模板 “favusers/{favUserId}"指定變量的名字 favUserId ,當控制器處理這個請求的時候, favUserId的值會被設定到URI中。比如,當有一個像“favusers/favccxx”這樣的請求時,favUserId的值就是 favccxx。
@PathVariable 可以有多個註解,像下面這樣:
@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>類型的參數時, Map會填充到所有的URI模板變量中。/<string>
@PathVariable支持使用正則表達式,這就決定了它的超強大屬性,它能在路徑模板中使用佔位符,可以設定特定的前綴匹配,後綴匹配等自定義格式。
@PathVariable還支持矩陣變量,因為現實場景中用的不多,這就不詳細介紹了,有需要的童鞋請查看官網的文檔。
4. @RequestParam
@RequestParam將請求的參數綁定到方法中的參數上,如下面的代碼所示。其實,即使不配置該參數,註解也會默認使用該參數。如果想自定義指定參數的話,如果將@RequestParam的 required 屬性設置為false(如@RequestParam(value="id",required=false))。
5. @RequestBody
@RequestBody是指方法參數應該被綁定到HTTP請求Body上。
@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格式的數據時,會經常用到,代碼見下圖:
@RequestMapping(value = "/something", method = RequestMethod.PUT)@ResponseBodypublic String helloWorld() { return "Hello World";
}
7. @RestController
我們經常見到一些控制器實現了REST的API,只為服務於JSON,XML或其它自定義的類型內容,@RestController用來創建REST類型的控制器,與@Controller類型。@RestController就是這樣一種類型,它避免了你重複的寫@RequestMapping與@ResponseBody。
@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響應之外,它還能訪問請求和響應頭,如下所示:
@RequestMapping("/something")public ResponseEntity<string> handle(HttpEntity<byte> requestEntity) throws UnsupportedEncodingException {/<byte>/<string>
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);/<string>
}
9. @ModelAttribute
@ModelAttribute可以作用在方法或方法參數上,當它作用在方法上時,標明該方法的目的是添加一個或多個模型屬性(model attributes)。該方法支持與@RequestMapping一樣的參數類型,但並不能直接映射成請求。控制器中的@ModelAttribute方法會在@RequestMapping方法調用之前而調用,示例如下:
@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模板變量和類型轉換器檢索屬性。
註解的出現終結了XML配置文件漫天飛的年代,它讓程序擁有更高的可讀性,可配置性與靈活性。當然,也有一些人說註解不如配置文件顯的結構清晰,個人覺得所謂的結構應該是一個統一的規範,而不是將一堆文件結構糅合在一起。這就好比是面向對象與面向結構,你能說面向對象的邏輯不清晰嗎?
閱讀更多 java互聯網架構 的文章