springMVC注解@RequestParam和@PathVariable區(qū)別

@RequestParam?和?@PathVariable?注解是用于從request中接收請求的,兩個(gè)都可以接收參數(shù),關(guān)鍵點(diǎn)不同的是@RequestParam?是從request里面拿取值,而?@PathVariable?是從一個(gè)URI模板里面來填充



@PathVariable 映射 URL 綁定的占位符

帶占位符的URL?是Spring3.0?新增的功能,該功能在SpringMVC 向REST?目標(biāo)挺進(jìn)發(fā)展過程中具有里程碑的意義

通過@PathVariable?可以將URL?中占位符參數(shù)綁定到控制器處理方法的入?yún)⒅校篣RL 中的 {xxx} 占位符可以通過@PathVariable(“xxx“) 綁定到操作方法的入?yún)⒅小?/p>

實(shí)例:

SpringMVCTest.java

//@PathVariable可以用來映射URL中的占位符到目標(biāo)方法的參數(shù)中

@RequestMapping("/testPathVariable/{id}")

public String testPathVariable(@PathVariable("id") Integer id)

? ? {

System.out.println("testPathVariable:"+id);

returnSUCCESS;

? ? }

index.jsp

<a href="springmvc/testPathVariable/1">testPathVariable</a>




@RequestParam

看下面一段代碼:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20

根據(jù)上面的這個(gè)URL,你可以用這樣的方式來進(jìn)行獲取

public String getDetails(

? ? @RequestParam(value="param1", required=true) String param1,

? ? ? ? @RequestParam(value="param2", required=false) String param2){

...

}

@RequestParam 支持下面四種參數(shù)

defaultValue 如果本次請求沒有攜帶這個(gè)參數(shù),或者參數(shù)為空,那么就會啟用默認(rèn)值

name 綁定本次參數(shù)的名稱,要跟URL上面的一樣

required 這個(gè)參數(shù)是不是必須的

value 跟name一樣的作用,是name屬性的一個(gè)別名

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容