spring mvc常用注解_動力節(jié)點Java學院整理
Spring從2.5版本開始在編程中引入注解,用戶可以使用@RequestMapping, @RequestParam, @ModelAttribute等等這樣類似的注解。到目前為止,Spring的版本雖然發(fā)生了很大的變化,但注解的特性卻是一直延續(xù)下來,并不斷擴展,讓廣大的開發(fā)人員的雙手變的更輕松起來,這都離不開Annotation的強大作用,今天我們就一起來看看Spring MVC 4中常用的那些注解吧。
1. @Controller
Controller控制器是通過服務接口定義的提供訪問應用程序的一種行為,它解釋用戶的輸入,將其轉(zhuǎn)換成一個模型然后將試圖呈獻給用戶。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請求參數(shù)。
@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 方法請求數(shù)據(jù),但是一旦指定方法類型,就只能使用該類型獲取數(shù)據(jù)。
@RequestMapping 可以使用 @Validated與BindingResult聯(lián)合驗證輸入的參數(shù),在驗證通過和失敗的情況下,分別返回不同的視圖。
@RequestMapping支持使用URI模板訪問URL。URI模板像是URL模樣的字符串,由一個或多個變量名字組成,當這些變量有值的時候,它就變成了URI。
3. @PathVariable
在Spring MVC中,可以使用 @PathVariable 注解方法參數(shù)并將其綁定到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中的參數(shù)可以是任意的簡單類型,如int, long, Date等等。Spring會自動將其轉(zhuǎn)換成合適的類型或者拋出 TypeMismatchException異常。當然,我們也可以注冊支持額外的數(shù)據(jù)類型。
如果@PathVariable使用Map<String, String>類型的參數(shù)時, Map會填充到所有的URI模板變量中。
@PathVariable支持使用正則表達式,這就決定了它的超強大屬性,它能在路徑模板中使用占位符,可以設定特定的前綴匹配,后綴匹配等自定義格式。
@PathVariable還支持矩陣變量,因為現(xiàn)實場景中用的不多,這就不詳細介紹了,有需要的童鞋請查看官網(wǎng)的文檔。
4. @RequestParam
@RequestParam將請求的參數(shù)綁定到方法中的參數(shù)上,如下面的代碼所示。其實,即使不配置該參數(shù),注解也會默認使用該參數(shù)。如果想自定義指定參數(shù)的話,如果將@RequestParam的 required 屬性設置為false(如@RequestParam(value="id",required=false))。
5. @RequestBody
@RequestBody是指方法參數(shù)應該被綁定到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轉(zhuǎn)移到方法參數(shù)上, HttMessageConverser將 HTTP請求消息在Object對象之間互相轉(zhuǎn)換,但一般情況下不會這么做。事實證明,@RequestBody在構建REST架構時,比@RequestParam有著更大的優(yōu)勢。
6. @ResponseBody
@ResponseBody與@RequestBody類似,它的作用是將返回類型直接輸入到HTTP response body中。@ResponseBody在輸出JSON格式的數(shù)據(jù)時,會經(jīng)常用到,代碼見下圖:
@RequestMapping(value = "/something", method = RequestMethod.PUT)@ResponseBodypublic String helloWorld() { return "Hello World";
}
7. @RestController
我們經(jīng)常見到一些控制器實現(xiàn)了REST的API,只為服務于JSON,XML或其它自定義的類型內(nèi)容,@RestController用來創(chuàng)建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 {
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可以作用在方法或方法參數(shù)上,當它作用在方法上時,標明該方法的目的是添加一個或多個模型屬性(model attributes)。該方法支持與@RequestMapping一樣的參數(shù)類型,但并不能直接映射成請求。控制器中的@ModelAttribute方法會在@RequestMapping方法調(diào)用之前而調(diào)用,示例如下:
@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表單上呈現(xiàn)數(shù)據(jù))。
@ModelAttribute方法有兩種風格:一種是添加隱形屬性并返回它。另一種是該方法接受一個模型并添加任意數(shù)量的模型屬性。用戶可以根據(jù)自己的需要選擇對應的風格。
@ModelAttribute作用在方法參數(shù)上
當@ModelAttribute作用在方法參數(shù)上時,表明該參數(shù)可以在方法模型中檢索到。如果該參數(shù)不在當前模型中,該參數(shù)先被實例化然后添加到模型中。一旦模型中有了該參數(shù),該參數(shù)的字段應該填充所有請求參數(shù)匹配的名稱中。這是Spring MVC中重要的數(shù)據(jù)綁定機制,它省去了單獨解析每個表單字段的時間。
@ModelAttribute是一種很常見的從數(shù)據(jù)庫中檢索屬性的方法,它通過@SessionAttributes使用request請求存儲。在一些情況下,可以很方便的通過URI模板變量和類型轉(zhuǎn)換器檢索屬性。
相關文章
SpringBoot集成tomcat詳解實現(xiàn)過程
采用spring boot之后,一切變得如此簡單,打包->java-jar->運維,只需要一個jar包便可以隨意部署安裝。這篇文章,將對 spring boot集成tomcat的源碼進行分析,探索其內(nèi)部的原理2023-02-02
SpringSecurity中的EnableWebSecurity注解啟用Web安全詳解
這篇文章主要介紹了SpringSecurity中的EnableWebSecurity注解啟用Web安全詳解,@EnableWebSecurity是Spring?Security用于啟用Web安全的注解,典型的用法是該注解用在某個Web安全配置類上,實現(xiàn)了接口,需要的朋友可以參考下2023-12-12
Springboot+Jackson自定義注解數(shù)據(jù)脫敏的項目實踐
數(shù)據(jù)脫敏可以對敏感數(shù)據(jù)比如 手機號、銀行卡號等信息進行轉(zhuǎn)換或者修改,本文主要介紹了Springboot+Jackson?自定義注解數(shù)據(jù)脫敏,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-08-08
MyBatis中的collection兩種使用方法及效率比較
collection主要是應對表關系是一對多的情況,本文主要介紹了MyBatis中的collection兩種使用方法及效率比較,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06
Spring中的BeanFactory與FactoryBean區(qū)別詳解
這篇文章主要介紹了Spring中的BeanFactory與FactoryBean區(qū)別詳解,BeanFactory是一個接口,它是spring中的一個工廠,FactoryBean也是一個接口,實現(xiàn)了3個方法,通過重寫其中方法自定義生成bean,需要的朋友可以參考下2024-01-01

