๐Ÿต java

JAVA | @RequestParam

c0zi 2023. 6. 5. 13:36

๐Ÿ“Œ @RequestParam


1. @RequestParam์„ ์ƒ๋žตํ•˜๋Š” ๊ฒฝ์šฐ

// public String main2 (@RequestParam(name="year", required=false) String year) 
public String main2 (String year)

์œ„์˜ ๋‘ ๋ฌธ์žฅ์€ ๊ฐ™์€ ๋ฌธ์žฅ์ด๋ฉฐ, @RequestParam์€ ์ƒ๋žต ๊ฐ€๋Šฅํ•˜๋‹ค. required๋Š” ํ•„์ˆ˜ ์—ฌ๋ถ€ ๋‚˜ํƒ€๋‚ด๊ณ  ์œ„์™€ ๊ฐ™์€ ๊ฒฝ์šฐ์—๋Š” ํ•„์ˆ˜์ž…๋ ฅ์ด false์ด๋ฏ€๋กœ, year ๊ฐ’์„ ์ž…๋ ฅํ•ด์ฃผ์ง€ ์•Š์•„๋„ ๋œ๋‹ค.

 

์‚ฌ์šฉ์ž๊ฐ€ ์ฃผ์†Œ๋ฅผ ์ž…๋ ฅํ•  ๋•Œ์˜ ์˜ˆ์‹œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

//  http://localhost/ch2/requestParam2   --->> year = null
//  http://localhost/ch2/requestParam2?year   -->> year = "" (๋นˆ ๋ฌธ์ž์—ด)

2. @RequestParam์„ ์ƒ๋žตํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ

// public String main3(@RequestParam(name="year", required=true) String year)
public String main3(@RequestParam String year)

๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ƒ๋žตํ•˜์ง€ ์•Š๊ณ  ์•ž์— ์ ์–ด์ฃผ์—ˆ๋‹ค๋ฉด, year์˜ ๊ฐ’์„ ํ•„์ˆ˜์ ์œผ๋กœ ์ž…๋ ฅํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

 

ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ž…๋ ฅํ•˜์ง€ ์•Š์œผ๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด Error๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

//  http://localhost/ch2/requestParam3   --->> year = null (400Error, required๊ฐ€ true์ด๋ฏ€๋กœ)
//  http://localhost/ch2/requestParam3?year   -->> year = "" (๋นˆ ๋ฌธ์ž์—ด)

๋”ฐ๋ผ์„œ ํ•„์ˆ˜์ ์œผ๋กœ ๊ฐ’์„ ์ž…๋ ฅ๋ฐ›์•„์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ๋Š” ์ƒ๋žตํ•˜์ง€ ์•Š๋Š”๋‹ค.

 


3. ๊ทธ ์™ธ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š” ๊ฒฝ์šฐ

@RequestMapping("/requestParam8") 
	public String main8(@RequestParam(required=false) int year) {   
	//	http://localhost/ch2/requestParam8        ---->> 500 java.lang.IllegalStateException
	//	http://localhost/ch2/requestParam8?year   ---->> 400 Bad Request
		System.out.printf("[%s]year=[%s]%n", new Date(), year);
		return "yoil";
	}

 

ํ•„์ˆ˜์ž…๋ ฅ์ด ์•„๋‹ ๋•Œ๋„ ๊ณ ๋ คํ•ด์•ผ ํ•  ๋ถ€๋ถ„์ด ์žˆ๋‹ค. 

๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” ํ•„์ˆ˜ ์ž…๋ ฅ์ด ์•„๋‹ˆ์ง€๋งŒ, year๋ฅผ int ๊ฐ’์œผ๋กœ ์ž…๋ ฅ ๋ฐ›๋‹ค ๋ณด๋‹ˆ ์•„๋ฌด๊ฒƒ๋„ ์ž…๋ ฅํ•˜์ง€ ์•Š์œผ๋ฉด year = null์ด ๋˜๋ฉด์„œ int ๊ฐ’์œผ๋กœ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ์„œ๋ฒ„ ์—๋Ÿฌ์ธ 500 Error๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ๋˜ํ•œ year๊นŒ์ง€๋งŒ ์ž…๋ ฅํ•˜๊ณ  ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์ง€ ์•Š์œผ๋ฉด ์ด ๋˜ํ•œ ๋นˆ ๋ฌธ์ž์—ด๋กœ ์ธ์‹ํ•˜๊ธฐ ๋•Œ๋ฌธ์— int ํ˜•์œผ๋กœ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์—†๋‹ค. (400 Error)

 

๋”ฐ๋ผ์„œ, ํ•„์ˆ˜์ž…๋ ฅ์ด ์•„๋‹ ๋•Œ์—๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ธฐ๋ณธ๊ฐ’์„ ์ž…๋ ฅํ•ด ์ฒ˜๋ฆฌํ•œ๋‹ค.

@RequestMapping("/requestParam11")   
	public String main11(@RequestParam(required=false, defaultValue="1") int year) {   
//		http://localhost/ch2/requestParam11        ---->> year=1   
//		http://localhost/ch2/requestParam11?year   ---->> year=1   
		System.out.printf("[%s]year=[%s]%n", new Date(), year);
		return "yoil";