@RequestParam vs @PathVariable
와의 차이는 무엇입니까?@RequestParam
그리고.@PathVariable
특수 캐릭터를 다루면서요?
+
에 의해 받아들여졌다.@RequestParam
공간으로서.
의 경우@PathVariable
,+
로 받아들여졌다+
.
@PathVariable
는 URI에서 플레이스 홀더를 취득하는 것입니다(스프링에서는 URI 템플릿이라고 부릅니다).「Spring Reference Chapter 16.3.2 URI Template Patterns 」를 참조해 주세요.@RequestParam
파라미터도 URI에서 가져옵니다.「 Spring Reference Chapter 16 . 3 . 3 . 3 . Binding request parameters to method param 」를 참조해 주세요.
URL이http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013
는 2013년 12월 5일에 사용자 1234에 대한 청구서를 받습니다.컨트롤러 방법은 다음과 같습니다.
@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
@PathVariable("userId") int user,
@RequestParam(value = "date", required = false) Date dateOrNull) {
...
}
또한 요청 파라미터는 옵션이며 Spring 4.3.3부터는 경로 변수도 옵션입니다.단, 이로 인해 URL 경로 계층이 변경되어 요청 매핑 충돌이 발생할 수 있습니다.예를 들어,/user/invoices
사용자에게 송장을 제공하다null
또는 ID가 "invoices"인 사용자에 대한 상세 정보?
@RequestParam 주석은 요청에서 쿼리 파라미터 값에 액세스하기 위해 사용됩니다.다음 요청 URL을 확인합니다.
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
위의 URL 요구에서 param1 및 param2 값은 다음과 같이 액세스할 수 있습니다.
public String getDetails(
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
...
}
다음은 @RequestParam 주석이 지원하는 파라미터 목록입니다.
- default Value : 요구에 값이 없거나 비어 있는 경우 폴백메커니즘으로서의 기본값입니다.
- name : 바인드할 파라미터 이름
- required : 파라미터가 필수인지 여부를 나타냅니다.true일 경우 해당 파라미터를 전송하지 못하면 실패합니다.
- value : 이름 속성의 에일리어스입니다
@PathVariable(경로변수)
@PathVariable은 착신 요구에 대해 URI에서 사용되는 패턴을 식별합니다.다음 요청 URL을 살펴보겠습니다.
http://localhost:8080/springmvc/hello/101?spring1=10&spring2=20
위의 URL 요청은 다음과 같이 Spring MVC에 작성할 수 있습니다.
@RequestMapping("/hello/{id}") public String getDetails(@PathVariable(value="id") String id,
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
.......
}
@PathVariable 주석에는 요청 URI 템플릿을 바인딩하기 위한 Atribute 값은 1개뿐입니다.단일 메서드에서 여러 @PathVariable 주석을 사용할 수 있습니다.단, 같은 패턴을 가진 메서드는 1개뿐이어야 합니다.
또한 @MatrixVariable이라는 흥미로운 주석이 하나 더 있습니다.
컨트롤러의 방법
@RequestMapping(value = "/{stocks}", method = RequestMethod.GET)
public String showPortfolioValues(@MatrixVariable Map<String, List<String>> matrixVars, Model model) {
logger.info("Storing {} Values which are: {}", new Object[] { matrixVars.size(), matrixVars });
List<List<String>> outlist = map2List(matrixVars);
model.addAttribute("stocks", outlist);
return "stocks";
}
다만, 다음의 기능을 유효하게 할 필요가 있습니다.
<mvc:annotation-driven enableMatrixVariables="true" >
@RequestParam은 http://localhost:8080/calculation/pow?base=2&ext=4와 같은 쿼리 파라미터(정적값)에 사용됩니다.
@PathVariable은 http://localhost:8080/calculation/sqrt/8과 같은 동적 값에 사용됩니다.
@RequestMapping(value="/pow", method=RequestMethod.GET)
public int pow(@RequestParam(value="base") int base1, @RequestParam(value="ext") int ext1){
int pow = (int) Math.pow(base1, ext1);
return pow;
}
@RequestMapping("/sqrt/{num}")
public double sqrt(@PathVariable(value="num") int num1){
double sqrtnum=Math.sqrt(num1);
return sqrtnum;
}
1)@RequestParam
쿼리 파라미터를 추출하기 위해 사용됩니다.
http://localhost:3000/api/group/test?id=4
@GetMapping("/group/test")
public ResponseEntity<?> test(@RequestParam Long id) {
System.out.println("This is test");
return ResponseEntity.ok().body(id);
}
동시에@PathVariable
URI 로부터 데이터를 추출하기 사용됩니다.
http://localhost:3000/api/group/test/4
@GetMapping("/group/test/{id}")
public ResponseEntity<?> test(@PathVariable Long id) {
System.out.println("This is test");
return ResponseEntity.ok().body(id);
}
2)@RequestParam
는 쿼리 웹 에서 더 합니다.@PathVariable
「URL」 「RESTful Web」 「URL」 「RESTful Web」 。
3)@RequestParam
쿼리 파라미터가 존재하지 않거나 빈 경우 주석을 사용하여 기본값을 지정할 수 있습니다.defaultValue
Atribute한 Atribute)의 Atribute(Atribute)false
:
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/name")
String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
return "Required element of request param";
}
}
application/x-www-form-urlencoded midia 타입은 공간을 +로 변환하고 수신자는 +를 공간으로 변환하여 데이터를 디코딩할 수 있습니다.자세한 것은, http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 를 참조해 주세요.
@PathVariable - must be placed in the endpoint uri and access the query parameter value from the request
@RequestParam - must be passed as method parameter (optional based on the required property)
http://localhost:8080/employee/call/7865467
@RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
public List<Calls> getAgentCallById(
@PathVariable(“callId") int callId,
@RequestParam(value = “status", required = false) String callStatus) {
}
http://localhost:8080/app/call/7865467?status=Cancelled
@RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
public List<Calls> getAgentCallById(
@PathVariable(“callId") int callId,
@RequestParam(value = “status", required = true) String callStatus) {
}
두 주석 모두 정확히 동일한 방식으로 작동합니다.
주석 @PathVariable 및 @RequestParam에서는 특수 문자 '!'과 '@'만 허용됩니다.
동작을 확인하고 확인하기 위해 컨트롤러가 1개밖에 없는 스프링 부트애플리케이션을 만들었습니다.
@RestController
public class Controller
{
@GetMapping("/pvar/{pdata}")
public @ResponseBody String testPathVariable(@PathVariable(name="pdata") String pathdata)
{
return pathdata;
}
@GetMapping("/rpvar")
public @ResponseBody String testRequestParam(@RequestParam("param") String paramdata)
{
return paramdata;
}
}
다음 요청을 눌렀을 때 동일한 응답을 받았습니다.
- localhost: 7000/sysar/!@#$%^&*()_+-=[]{}|;'',/<>?
- localhost: 7000/rpvar?var=!@#$%^&*()_+-=[]{}|;'', /<>?
!@가 양쪽 요구에서 응답으로 수신되었습니다.
@RequestParam:키 값 쌍 @PathVariable과 같은 쿼리 파라미터라고 할 수 있습니다.- URI에서 왔습니다.
언급URL : https://stackoverflow.com/questions/13715811/requestparam-vs-pathvariable
'programing' 카테고리의 다른 글
두 날짜 사이의 일수는 어떻게 계산하나요? (0) | 2022.09.18 |
---|---|
ODBC를 사용하여 전체 LOB에서 읽는 가장 좋은 방법은 무엇입니까? (0) | 2022.09.18 |
ERROR 1115(42000):알 수 없는 문자 집합: 'utf8mb4' (0) | 2022.09.18 |
Ubuntu 16.04 MariaDb 설정 예 없음 (0) | 2022.09.18 |
안드로이드 java.langVerify Error? (0) | 2022.09.18 |