[๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ปTA9 ์ธํ„ด 23์ผ์ฐจ]Spring boot @Controller, @RestController, @RequestParam, @PathVariable, @RequestBody

Goofiยท2023๋…„ 8์›” 9์ผ
0

Annotaion

Java ์†Œ์Šค์ฝ”๋“œ์— ์ถ”๊ฐ€์ ์ธ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š” ๋ฐฉ๋ฒ•.
@์œผ๋กœ ์‹œ์ž‘ํ•˜๋ฉฐ ํด๋ž˜์Šค, ๋ฉ”์†Œ๋“œ, ๋ฉค๋ฒ„๋ณ€์ˆ˜, ํŒŒ๋ผ๋ฏธํ„ฐ ๋“ฑ์— ๋ถ€์ฐฉ ๊ฐ€๋Šฅ.

@Controller

view๋ฅผ ์‘๋‹ต(html ํŒŒ์ผ ๋“ฑ)

@RestController

data๋ฅผ ์‘๋‹ต(๋ฌธ์ž์—ด, Json, xml ๋“ฑ)

@RequestMapping

RequestMapping์ด ๋ถ™์–ด ์žˆ๋Š” ๋ฉ”์†Œ๋“œ๋Š” Client์˜ ํŠน์ • ์š”์ฒญ์ด ์™”์„ ๋•Œ Spring Framework์— ์˜ํ•ด ํ˜ธ์ถœ๋œ๋‹ค.

@RequsetMapping(value="/hello")

@RequestParms

Query String์˜ ํ™œ์šฉ

  • name : query string์˜ key, key์™€ ๋ณ€์ˆ˜๋ช…์ด ๊ฐ™์„ ๊ฒฝ์šฐ ์ƒ๋žต ๊ฐ€๋Šฅ
  • required : ํ•„์ˆ˜ ์—ฌ๋ถ€
  • defaultValue : ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์„ ๊ฒฝ์šฐ ๊ธฐ๋ณธ ๊ฐ’
@RequsetParam(name = "category", required = false, defaultValue = "it") String catefory

URI์— ์ด์–ด์ง€๋Š” โ€˜?โ€™ ๋’ค์— key1=value1&key2=value2&... ํ˜•ํƒœ๋กœ ์ž‘์„ฑ

@RequsetMapping(value= "/post")
public String getPost(@RequestParam(name="category") String category, @RequestParam(name = "id") Integer id) {
	return "You requested " + category + "_" + id + " post";
}

http://localhost:8080/post?category=it&id=10

@PathVariable

Path Parameter์˜ ํ™œ์šฉ
@RequestMapping value URI์— {}๋กœ Path Param์ž„์„ ํ‘œ์‹œ

@RequestMapping(value = "/user/{type}/id/{id}")
public String getUser(@PathVariable(name="type") String type, @PathVariable(name = "id") Integer id){
	return "You requested " + type + "_" + " user";
}

http://localhost:8080/user/admin/id/100

Query String vs Path Parameter

์ผ๋ฐ˜์ ์ธ ์ถ”์ฒœ ์‚ฌํ•ญ

  • ํŠน์ • ์ž์›์„ ์š”์ฒญ ํ•˜๋Š” ๊ฒฝ์šฐ๋Š” Path Param์„, ์ •๋ ฌ์ด๋‚˜ ์ถ”๊ฐ€ ํ•„ํ„ฐ๋ง์„ ์œ„ํ•œ ๋ฐ์ดํ„ฐ๋Š” Query String ์‚ฌ์šฉ
  • https://codepresso.kr/courses/spring?order=latest
    ํ•„์ˆ˜ ๋ฐ์ดํ„ฐ๋Š” Path Param์œผ๋กœ ์„ ํƒ์  ๋ฐ์ดํ„ฐ๋Š” Query String ์‚ฌ์šฉ
  • Path Param์ด ํฌํ•จ ๋œ URI๋Š” Client๊ฐ€ ์˜ํ–ฅ์„ ๋ฐ›๊ธฐ ๋•Œ๋ฌธ์— ๋ณ€๊ฒฝ ๋น„์šฉ ๋†’์Œ
  • Query String์€ ์ƒ๋Œ€์ ์œผ๋กœ ํŽธํ•˜๊ฒŒ ํ™•์žฅ ๊ฐ€๋Šฅ

@RequestBody

Client์—์„œ๋Š” JSON ๋ฐ์ดํ„ฐ๋ฅผ ์ „์†กํ•˜๊ณ , Spring์—์„œ๋Š” JSON ๋ฐ์ดํ„ฐ๋ฅผ Java ๊ฐ์ฒด ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ €์žฅ

Requst JSON Data

{
	"id" : 1,
  	"title" : "hello",
  	"content" : "nice to meet you",
  	"username" : "dhlee"
}

Code

@PostMapping
public String savePost(@RequestBody PostDto postDto){
	system.out.println(postDto.getId());
	system.out.println(postDto.getTitle());
	system.out.println(postDto.getContent());
	system.out.println(postDto.getUsername());
  	return "POST /post";
}
public class PostDto{
	Integer id;
    String title;
    String content;
    String username;
}

console

1
hello
nice to meet you
dhlee
profile
์˜ค๋Š˜๋ณด๋‹จ ๋‚ด์ผ์ด ๊ฐ•ํ•œ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค!!๐Ÿง‘๐Ÿปโ€๐Ÿ’ป

0๊ฐœ์˜ ๋Œ“๊ธ€

๊ด€๋ จ ์ฑ„์šฉ ์ •๋ณด