[Spring] @RequestParam에 대해 알아보자

[Spring] @RequestParam에 대해 알아보자

@RequestParam

요청의 파라미터를 연결할 매개변수에 붙이는 어노테이션

예제 1

@RequestMapping("/requestParam") //public String main(@RequestParam(name = "year", required = false) String year) { public String main(String year) { // 위와 동일 System.out.println("년도 : " + year); return "yoil"; }

속성

name : 쿼리스트링 이름

required : 필수여부 (false면 필수 x)

http://localhost/requestParam --> year = null http://localhost/requestParam?year --> year = ""

쿼리스트링으로 키값이 없으면 null로 처리되고 키값이 있으면 ""(빈문자열) 로 처리된다.

예제 2

@RequestMapping("/requestParam2") // public String main(@RequestParam(name = "year", required = true) String year) { public String main(@RequestParam String year) { System.out.println("년도 : " + year); return "yoil"; }

매개변수 앞에 @RequestParam을 붙이면 required=true와 동일하게 처리된다.

http://localhost/requestParam2 --> year = null ---> 400 Bad Request. http://localhost/requestParam2?year --> year = "" ---> 에러 X

이 상태에서 요청 쿼리스트링에 year가 없으면 404 Bad Request 처리된다. 왜냐하면 required가 true기 때문이다.

예제 3

@RequestMapping("/requestParam3") public String main(@RequestParam(required = false) int year) { System.out.println("년도 : " + year); return "yoil"; }

이번엔 매개변수로 받은 값 year의 타입을 int로 변환한다. 이 상태에서 요청이 들어오면,

//http://localhost/requestParam --> 500 에러 //http://localhost/requestParam?year --> 400 Bad Request.

요청 쿼리스트링에 year가 없으면 null값이 들어오기 때문에 null은 int로 변경할 수 없어서 서버에러가 발생한다.

요청 쿼리스트링에 year만 있으면 빈문자열("")로 들어오는데 빈문자열은 int로 변경할 수 없어서 클라이언트에러가 발생한다.

이럴댄 필수입력이 false라고 한다면 defaultValue 속성을 줘서 에러를 막아야 한다.

@RequestMapping("/requestParam3") public String main(@RequestParam(required = false, defaultValue="1") int year) { System.out.println("년도 : " + year); return "yoil"; }

예제 4

@RequestMapping("/requestParam4") public String main(@RequestParam(required = true) int year) { System.out.println("년도 : " + year); //http://localhost/requestParam --> year = null //http://localhost/requestParam?year --> year = "" return "yoil"; }

from http://byungmin.tistory.com/67 by ccl(A) rewrite - 2021-12-31 11:27:10