欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring中@PathVariable和@RequestParam注解的用法區(qū)別

 更新時(shí)間:2024年01月30日 08:48:42   作者:Ruby丶彬  
這篇文章主要介紹了Spring中@PathVariable和@RequestParam注解的用法區(qū)別,@PathVariable 是 Spring 框架中的一個(gè)注解,用于將 URL 中的變量綁定到方法的參數(shù)上,它通常用于處理 RESTful 風(fēng)格的請(qǐng)求,從 URL 中提取參數(shù)值,并將其傳遞給方法進(jìn)行處理,需要的朋友可以參考下

前言

@PathVariable和@RequestParam的作用都是從請(qǐng)求里面獲取參數(shù),只是用法不同

  • PathVariable:
  • http://localhost:8080/testPathVariable/parm1/111111/parm2/222222
  • RequestParam:
  • http://localhost:8080/testRequestParam?id1=11111&id2=22222

@PathVariable

首先看一下代碼以及響應(yīng)結(jié)果:

請(qǐng)求路徑url://localhost:8080/testPathVariable/parm1/111111/parm2/222222

代碼:

@GetMapping("/testPathVariable/parm1/{id1}/parm2/{id2}")
public String testPathVariable(@PathVariable(value = "id1") String id,@PathVariable String id2) {
     return "testPathVariable, param1:"+id+" , param2:"+id2;
}

請(qǐng)求結(jié)果:

在這里插入圖片描述

解析

@PathVariable用法: 請(qǐng)求路徑采用 “/ 參數(shù)” 向后臺(tái)傳入?yún)?shù) 后臺(tái)接收采用 {id1} 占位符形式的方式來(lái)接收請(qǐng)求參數(shù)

@PathVariable的參數(shù):

  • name: 與請(qǐng)求的具體哪個(gè)參數(shù)做綁定
  • required: 參數(shù)是否必須 true or false
  • value: 跟name一樣的作用,與請(qǐng)求的具體哪個(gè)參數(shù)做綁定

@RequestParam

首先看一下代碼以及響應(yīng)結(jié)果:

請(qǐng)求路徑://localhost:8080/testRequestParam?id1=11111&id2=22222

代碼:

@GetMapping("/testRequestParam")
public String testRequestParam(@RequestParam(value = "id1") String id, @RequestParam String id2) {
      return "testRequestParam, param1:"+id+" , param2:"+id2;
 }

請(qǐng)求結(jié)果:

在這里插入圖片描述

解析

@RequestParam用法: 請(qǐng)求路徑采用的是形如 /testRequestParam?id1=11111&id2=22222 的形式

后臺(tái)接收用@RequestParam注解,用value屬性綁定參數(shù)接收

@RequestParam的參數(shù):

  • name: 與請(qǐng)求的具體哪個(gè)參數(shù)做綁定
  • required: 參數(shù)是否必須 true or false
  • value: 跟name一樣的作用,與請(qǐng)求的具體哪個(gè)參數(shù)做綁定
  • defaultValue:如果請(qǐng)求沒(méi)有攜帶這個(gè)參數(shù)或者參數(shù)為空,采用默認(rèn)值

異同點(diǎn)

相同點(diǎn):都是從請(qǐng)求里面獲取參數(shù)

不同點(diǎn):@RequestParam多了一個(gè)defaultValue屬性,用于處理請(qǐng)求沒(méi)有這個(gè)參數(shù)的情況賦予一個(gè)默認(rèn)值

@GetMapping("/testRequestParam")
public String testRequestParam(@RequestParam(value = "id1",required = false,
defaultValue = "paramdefault") String id, @RequestParam String id2) {
      return "testRequestParam, param1:"+id+" , param2:"+id2;
}

在這里插入圖片描述

到此這篇關(guān)于Spring中@PathVariable和@RequestParam注解的用法區(qū)別的文章就介紹到這了,更多相關(guān)@PathVariable和@RequestParam用法區(qū)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論