[SPRING] 1. Controller๋ก api์ฃผ์ ๋ค๋ค๋ณด๊ธฐ
๐ฅController๋?
SPRING MVC ๊ตฌ์กฐ์์ C๋ฅผ ๋งก๊ณ ์๋ Controller๋ ํด๋ผ์ด์ธํธ ์ธก์ ์์ฒญ์ ์ง์ ์ ์ผ๋ก ์ ๋ฌ๋ฐ๋ ์๋ํฌ์ธํธ(Endpoint)๋ก์จ Model๊ณผ View์ ์ค๊ฐ์์ ์ํธ์์ฉ์ ํด์ฃผ๋ ์ญํ ์ ํ๋ค.
ํด๋ผ์ด์ธํธ ์ธก์ ์์ฒญ์ ์ ๋ฌ๋ฐ์ ๋น์ฆ๋์ค ๋ก์ง์ ๊ฑฐ์น ํ, Model ๋ฐ์ดํฐ๊ฐ ๋ง๋ค์ด์ง๋ฉด, ์ด Model ๋ฐ์ดํฐ๋ฅผ View๋ก ์ ๋ฌํ๋ ์ญํ ์ ํ๋ค.
๐ฅapi์ฃผ์๋?
API๋ Application Programming Interface์ ์ฝ์๋ก ์์ฉ ํ๋ก๊ทธ๋จ์์ ์ฌ์ฉํ ์ ์๋๋ก, ์ด์์ฒด์ ๋ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด๊ฐ ์ ๊ณตํ๋ ๊ธฐ๋ฅ์ ์ ์ดํ ์ ์๊ฒ ๋ง๋๋ ์ธํฐํ์ด์ค๋ฅผ ๋ปํ๋ค.
์น์์๋ ์น ๋ธ๋ผ์ฐ์ ๋ฅผ ์ํ ์ ํ๋ฆฌ์ผ์ด์
ํ๋ก๊ทธ๋๋ฐ ์ธํฐํ์ด์ค์ด๋ค. HTTP ์๋น์ค์ด๊ณ ๋ค์ํ ํด๋ผ์ด์ธํธ์์ ์ ๊ทผ์ด ๊ฐ๋ฅํ๋๋ก ์ค๊ณ๋์ด์๋ค. Web ํ๊ฒฝ์ ํตํด ์ ๊ณต๋๋ ๋ฐ์ดํฐ CRUD์ธํฐํ์ด์ค๋ฅผ ์ ๊ณตํ๋ค.
๐ฅPOSTMAN ์ฌ์ฉ
ํฌ์คํธ๋งจ์ API ๊ฐ๋ฐ ๋ฐ ํ ์คํธ๋ฅผ ์ํ ์ธ๊ธฐ์๋ ํ์ ๋๊ตฌ์ ๋๋ค. ์์ธํ ๊ฑด ๋ฐ ๋ธ๋ก๊ทธ์ ๊ฐ์ ํ์ธํ์ค ์ ์์ต๋๋ค.
https://parkjh7764.tistory.com/212
[POSTMAN] ํฌ์คํธ๋งจ ์ค์น ๋ฐ ์ฌ์ฉ๋ฒ / POSTMAN request ์์ฒญํด๋ณด๊ธฐ
Contents ํฌ์คํธ๋งจ(POSTMAN)์ด๋? POSTMAN์ API ๊ฐ๋ฐ ๋ฐ ํ ์คํธ๋ฅผ ์ํ ์ธ๊ธฐ์๋ ํ์ ๋๊ตฌ์ ๋๋ค. ์น ๊ธฐ๋ฐ์ผ๋ก ์ ๊ณต๋๋ฉฐ, ๊ฐ๋ฐ์๋ค์ด API๋ฅผ ๋์์ธํ๊ณ ๋ฌธ์ํํ๋ฉฐ, ํ ์คํธํ๊ณ ๊ณต์ ํ๋ ๋ฐ ์ฌ์ฉ๋ฉ๋๋ค
parkjh7764.tistory.com
๐ฅ ์ค์ต
demo ๋ฐ์๋ค๊ฐ Package๋ฅผ ๋ง๋ค์ด์ฃผ์๊ณ package ์ด๋ฆ์ controller๋ก ํ ๊ฒ์ ๋๋ค.
controller ๋ฐ์ HelloController๋ผ๋ Java Class๋ฅผ ์์ฑํด์ฃผ๊ฒ ์ต๋๋ค.
์ด ๋ ์๋ฐ ๋ช ๋ช ๊ท์น์ ๋ฐ๋ผ ํจํค์ง(ํด๋) ์ด๋ฆ์ ์๋ฌธ์๋ก Class๋ ๋๋ฌธ์๋ก ์์ํ๋๋ก ์ด๋ฆ์ ๋ง๋ค์ด ์ค๋๋ค.
์ปจํธ๋กค๋ฌ์๋ @RestController์ @Controller๊ฐ ์๋ค.
@Controller vs @RestController
@Controller๋ ๋ฐํ ๊ฐ์ด String์ผ ๋ ๋ทฐ ์ด๋ฆ์ผ๋ก ์ธ์ํ์ฌ ๋ทฐ๋ฅผ ์ฐพ๊ณ ๋ทฐ๊ฐ ๋๋๋ง๋๋ค.
๋ฐ๋ฉด, @RestController๋ ๋ฐํ ๊ฐ์ผ๋ก ๋ทฐ๋ฅผ ์ฐพ๋ ๊ฒ์ด ์๋, HTTP ๋ฉ์์ง ๋ฐ๋์ ๋ฐ๋ก ์ ๋ ฅ๋์ด ๋ฐํ๋ ๋ฌธ์์ด์ ๊ทธ๋๋ก ๋ ธ์ถ์ํฌ ์ ์๋ค.
*Controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hi(){
return "hello.html";
}
}
์ด๋ฅผ ํ์ธํ๊ธฐ ์ํด์ resource์ static์ด๋ ํ์ผ ๋ฐ์ hello.html์ด๋ผ๋ ํ์ผ์ด ์์ด์ผํ๋๋ฐ
์ปจํธ๋กค๋ฌ๋ static์ด๋ ํ์ผ ๋ฐ์ return ๊ฐ์ ๋๋๋ง ํ๋ค.
์ด๋ ๊ฒ ๋ง๋ค์ด์ฃผ๋ฉด /hello๋ ๊ณณ์ ๋ค์ด๊ฐ์ ๋ hello.html์ด ๋์จ๋ค.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
helloController๋ก ๋ค์ด์จ ํ์ด์ง ์
๋๋ค.
</body>
</html>
*RestController
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloRestController {
@RequestMapping("/hi")
public String hi(){
return "hi RestController๋ก ๋ค์ด์จ ํ์ด์ง ์
๋๋ค.";
}
}
๐ฅ๊ฒฐ๊ณผ ํ์ธ (POSTMAN)
* Controller
*RestController
๐ฅ๊ฒฐ๊ณผ ํ์ธ (WEB)
*Controller
*RestController