生活随笔
收集整理的這篇文章主要介紹了
Spring mvc中@RequestMapping 6个基本用法小结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。
小結下spring mvc中的@RequestMapping的用法。??
1)最基本的,方法級別上應用,例如:??
???
Java代碼??
@RequestMapping(value="/departments")??public?String?simplePattern(){??????System.out.println("simplePattern?method?was?called");????return?"someResult";????}??
?? 則訪問http://localhost/xxxx/departments的時候,會調用 simplePattern方法了??
2) 參數綁定??
??
Java代碼??
@RequestMapping(value="/departments")??public?String?findDepatment(????@RequestParam("departmentId")?String?departmentId){??????????System.out.println("Find?department?with?ID:?"?+?departmentId);??????return?"someResult";????}??
????
? 形如這樣的訪問形式:??
?? /departments?departmentId=23就可以觸發訪問findDepatment方法了??
3 REST風格的參數??
??
Java代碼??
@RequestMapping(value="/departments/{departmentId}")??public?String?findDepatment(@PathVariable?String?departmentId){??????System.out.println("Find?department?with?ID:?"?+?departmentId);????return?"someResult";????}??
???
? 形如REST風格的地址訪問,比如:??
/departments/23,其中用(@PathVariable接收rest風格的參數??
4 REST風格的參數綁定形式之2??
?? 先看例子,這個有點象之前的:??
?
Java代碼??
@RequestMapping(value="/departments/{departmentId}")??public?String?findDepatmentAlternative(????@PathVariable("departmentId")?String?someDepartmentId){????????System.out.println("Find?department?with?ID:?"?+?someDepartmentId);??????return?"someResult";????}??
?
?? 這個有點不同,就是接收形如/departments/23的URL訪問,把23作為傳入的departmetnId,,但是在實際的方法findDepatmentAlternative中,使用??
@PathVariable("departmentId") String someDepartmentId,將其綁定為??
someDepartmentId,所以這里someDepartmentId為23??
5 url中同時綁定多個id??
?
?
?
Java代碼??
@RequestMapping(value="/departments/{departmentId}/employees/{employeeId}")??public?String?findEmployee(????@PathVariable?String?departmentId,????@PathVariable?String?employeeId){????????System.out.println("Find?employee?with?ID:?"?+?employeeId?+?????????"?from?department:?"?+?departmentId);??????return?"someResult";????}??
?
?? 這個其實也比較好理解了。??
6 支持正則表達式??
??
?
Java代碼??
@RequestMapping(value="/{textualPart:[a-z-]+}.{numericPart:[\\d]+}")??public?String?regularExpression(????@PathVariable?String?textualPart,????@PathVariable?String?numericPart){????????System.out.println("Textual?part:?"?+?textualPart?+?????????",?numeric?part:?"?+?numericPart);??????return?"someResult";??}??
?
?? 比如如下的URL:/sometext.123,則輸出:??
?
?
Textual part: sometext, numeric part: 123.?
?
?
?
?
見:http://my.oschina.net/jackyrong/blog/108859
總結
以上是生活随笔為你收集整理的Spring mvc中@RequestMapping 6个基本用法小结的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。