普通URL提交參數(shù)
該格式url為:url.do?param1=mahc¶m2=8888.00
需要在上文中的HelloController對象添加方法如下:
1
2
3
4
5
6
7
8
9
10
11
|
/** * Spring MVC URL提交參數(shù) * @param name * @return */ @RequestMapping ( "/param" ) public ModelAndView getInfo( @RequestParam ( "name" ) String name){ String str = name + " Spring MVC示例" ; return new ModelAndView( "message" , "str" , str); } |
訪問該方法的url格式為:param?name=hoking(Get方式)。該方式是很普通的提交方式。用注解@RequestParam綁定請求參數(shù)a到變量a當(dāng)請求參數(shù)a不存在時會有異常發(fā)生,可以通過設(shè)置屬性required=false解決,例如: @RequestParam(value="a", required=false)。如上文中,通過name獲取提交的參數(shù)。
RESTful風(fēng)格的URL參數(shù)
接下來我們了解一下Restful風(fēng)格。HTTP請求方法在RESTful Web 服務(wù)中的典型應(yīng)用資源GET PUT POST DELETE一組資源的URI,比如http://example.com/resources/單個資源的URI,比如http://example.com/resources/142。更多信息請閱讀如下文章。
具體的實現(xiàn)需要在上文中的HelloController對象添加方法如下:
1
2
3
4
5
6
7
8
9
10
|
/** * Spring MVC 支持RESTful風(fēng)格的URL參數(shù) * * @return */ @RequestMapping ( "/index/{username}" ) public String getMessage( @PathVariable ( "username" ) String username){ System.out.println(username); return "message" ; } |
上文使用了@PathVariable。PathVariable與RequestParam的不同在于。
使用@RequestMapping URI template樣式映射時,即 someUrl/{paramId}, 這時的paramId可通過@Pathvariable注解綁定它傳過來的值到方法的參數(shù)上。
訪問該方法的url格式為:index/mahoking。@PathVariable是用來獲得請求url中的動態(tài)參數(shù)的,十分方便。mahoking即是username的動態(tài)值。
上文中的getMessage()方法,返回String對象,該值代表頁面的跳轉(zhuǎn)地址,不包含擴展名(后綴名)。本例中為message.jsp頁面。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持服務(wù)器之家!
原文鏈接:http://blog.csdn.net/mahoking/article/details/43730093