這篇文章主要介紹了spring mvc常用註解,詳細的介紹了@RequestMapping, @RequestParam, @ModelAttribute等等這樣類似的註解,有興趣的可以了解一下
#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
@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 { 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方法调用之前而调用,示例如下:
@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模板变量和类型转换器检索属性。
以上是介紹spring mvc中常用的註解方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Java是平台獨立的,因為其"一次編寫,到處運行"的設計理念,依賴於Java虛擬機(JVM)和字節碼。 1)Java代碼編譯成字節碼,由JVM解釋或即時編譯在本地運行。 2)需要注意庫依賴、性能差異和環境配置。 3)使用標準庫、跨平台測試和版本管理是確保平台獨立性的最佳實踐。

Java'splatFormIndenceIsnotsimple; itinvolvesComplexities.1)jvmcompatiblemustbebeeniblemustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

thejvmistheruntimeenvorment forexecutingjavabytecode,Cocucialforjava的“ WriteOnce,RunanyWhere”能力

JavaremainsatopchoicefordevelopersduetoitsplatFormentence,對象與方向設計,強度,自動化的MememoryManagement和ComprechensivestAndArdArdArdLibrary

Java'splatFormIndependecemeansDeveloperScanWriteCeandeCeandOnanyDeviceWithouTrecompOlding.thisAcachivedThroughThroughTheroughThejavavirtualmachine(JVM),WhaterslatesbyTecodeDecodeOdeIntComenthendions,允許univerniverSaliversalComplatibilityAcrossplatss.allospplats.s.howevss.howev

要設置JVM,需按以下步驟進行:1)下載並安裝JDK,2)設置環境變量,3)驗證安裝,4)設置IDE,5)測試運行程序。設置JVM不僅僅是讓其工作,還包括優化內存分配、垃圾收集、性能調優和錯誤處理,以確保最佳運行效果。

toensurejavaplatFormIntence,lofterTheSeSteps:1)compileAndRunyOpplicationOnmultPlatFormSusiseDifferenToSandjvmversions.2)upureizeci/cdppipipelinelikeinkinslikejenkinsorgithikejenkinsorgithikejenkinsorgithikejenkinsorgithike forautomatecross-plateftestesteftestesting.3)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3漢化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版