브라우저에서 요청 URL에 Parameter에 따라 맞는 PageController Method를 사용하고 싶으면 @RequestParam Annotaion을 이용하면 된다.



사용방법 01. @RequestParam("변수명") 변수타입 변수명



@GetMapping(value="m1")
@ResponseBody
public String m1(
@RequestParam("name") String name,
@RequestParam("age") int age) {
return String.format("m1(): name=%s, age=%d", name, age);
}
//localhost:8080/main/m1?name="park"&age="28" 을 입력하면 해당 메서드에 진입할 수 있다.



주의 사항!

localhost:8080/main/m1?name="park"&age="hello"

단 age가 int 값으로 설정돼있는데 위에 처럼 hello 같이 순수 문자로 구성된 파라미터 값을 넘기면 Bad Request 에러가뜬다.

- 그 이유는 기본 입력 파라미터의 타입은 문자열이고 받게 지정된 파라미터 값이 기본 데이터 형(primitive type) 이면 frontController가 자동으로 바꿔준다. 

그런데 hello가 int형으로 존재할 수 없기에 Bad Request 에러가 뜬다.

HTTP Status 400 – Bad Request
Type Status Report

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Apache Tomcat/9.0.10


사용방법 02. @RequestParam() 변수타입 변수명


만약 브라우저에서 넘긴 Parameter 이름과 @RequestParam("") String name이 같으면 @RequestParam("")안에 이름을 지정안해도된다.


public String m2(
@RequestParam() String name,
@RequestParam() int age) {
return String.format("m3(): name=%s, age=%d", name, age);
}


@ReuqestParam을 붙여서 넘겨받을 Parameter 명을 지정했으면 default값이 없으면 불가피하게 무조건 받아야한다.

URL에 Parameter값을 입력안하면 Required int parameter 'age' is not present 라는 에러가 뜬다

HTTP Status 400 – Bad Request
Type Status Report

Message Required int parameter 'age' is not present

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Apache Tomcat/9.0.10

그 이유는 @RequestParam에는 @RequestParam(required=true) 라는 숨겨진 메서드가 존재하기 때문이다.


그러기에 @RequestParam(required=false) int age 처럼 개발자가 직접 required를 false로 설정을 해주거나 @RequestParam()을 생략한 int age만 사용하거나 default값을 설정해주면 된다.



1.@RequestParam()을 생략한 방법

public String m3(
String name,
int age) {
return String.format("m3(): name=%s, age=%d", name, age);
}


2. required=false를 직접 선언한 방법

public String m4(
@RequestParam(required=false) String name,
@RequestParam(required=false) int age) {
return String.format("m4(): name=%s, age=%d", name, age);
}

3. defaultValue 를 설정하여 입력하지 않아도 기본값으로 입력받게 하는 방법

public String m5(
String name,
@RequestParam(defaultValue="20") int age) {
return String.format("m5(): name=%s, age=%d", name, age);
}