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