/* ์ด ๊ธ์ ๊น์ํ๋์ ๊ฐ์๋ฅผ ๋ณด๊ณ ์ ๋ฆฌํ๋ ค๊ณ ์์ฑํ ๊ธ์ ๋๋ค.
๊ฐ์ธ์ ์ธ ๊ณต๋ถ๋ฅผ ์ํด ์ฌ๋ฆฌ๋ ๊ธ์ด๋ฏ๋ก ์ค๊ฐ ์ค๊ฐ ์ฝ๋๋ ์๋ต๋์์ต๋๋ค. */
์คํ๋ง MVC 1ํธ - ๋ฐฑ์๋ ์น ๊ฐ๋ฐ ํต์ฌ ๊ธฐ์ | ๊น์ํ - ์ธํ๋ฐ
๊น์ํ | ์น ์ ํ๋ฆฌ์ผ์ด์ ์ ๊ฐ๋ฐํ ๋ ํ์ํ ๋ชจ๋ ์น ๊ธฐ์ ์ ๊ธฐ์ด๋ถํฐ ์ดํดํ๊ณ , ์์ฑํ ์ ์์ต๋๋ค. ์คํ๋ง MVC์ ํต์ฌ ์๋ฆฌ์ ๊ตฌ์กฐ๋ฅผ ์ดํดํ๊ณ , ๋ ๊น์ด์๋ ๋ฐฑ์๋ ๊ฐ๋ฐ์๋ก ์ฑ์ฅํ ์ ์์ต
www.inflearn.com
1. ์๋ธ๋ฆฟ์ด๋?
์๋ฐ๋ฅผ ์ฌ์ฉํ์ฌ ํ์ด์ง๋ฅผ ๋์ ์ผ๋ก ์์ฑํ๋ ์๋ฒ์ธก ํ๋ก๊ทธ๋จ์ผ๋ก, HTTP ์์ฒญ๊ณผ ์๋ต ์ฒ๋ฆฌ๋ฅผ ์ํ ์คํ๋ง์์ ์ ๊ณตํ๋ ํต์ฌ ๊ธฐ๋ฅ์ด๋ผ๊ณ ํ ์ ์๋ค.
HTTP๋ก ํต์ ํ ๋ ์์ฒ๋ผ ๋ง์ ๊ณผ์ ๋ค์ด ์กด์ฌํ๋๋ฐ, ์๋ธ๋ฆฟ์ ๊ทธ ๊ณผ์ ์ ๊ฐ์ํ ์์ผ์ฃผ๋ฉฐ ๊ฐ๋ฐ์๊ฐ ์๋ฏธ์๋ ๋น์ฆ๋์ค ๋ก์ง์ ์ง์คํ ์ ์๋๋ก ๋์์ค๋ค.
HTTP ์์ฒญ์ WAS๋ Request, Response ๊ฐ์ฒด๋ฅผ ์๋ก ๋ง๋ค์ด์ ์๋ธ๋ฆฟ ๊ฐ์ฒด๋ฅผ ํธ์ถํ๊ณ ,
๊ฐ๋ฐ์๋ Request ๊ฐ์ฒด์์ HTTP ์์ฒญ ์ ๋ณด๋ฅผ ๊บผ๋ด๊ณ , Response ๊ฐ์ฒด์ HTTP ์๋ต์ ๋ณด๋ฅผ ์ ๋ ฅํ ์ ์๋ค.
WAS๋ Response ๊ฐ์ฒด์ ๋ด๊ฒจ์๋ ๋ด์ฉ์ผ๋ก HTTP ์๋ต ์ ๋ณด๋ฅผ ์์ฑํ๋ค.
2. ์๋ธ๋ฆฟ ํ๊ฒฝ ๊ตฌ์ฑ
1) @ServletComponentScan ์ถ๊ฐ
@ServletComponentScan // ์๋ธ๋ฆฟ ์๋ ๋ฑ๋ก
@SpringBootApplication
public class ServletApplication {
public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}
}
- ์คํ๋ง๋ถํธ๋ ์๋ธ๋ฆฟ์ ์ง์ ๋ฑ๋กํด์ ์ฌ์ฉํ ์ ์๋๋ก @ServletComponentScan์ ์ง์ํ๋ค.
2) ์๋ธ๋ฆฟ ๋ฑ๋ก
@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("HelloServlet.service");
System.out.println("request = " + request);
System.out.println("response = " + response);
String username = request.getParameter("username");
System.out.println("username = " + username);
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
response.getWriter().write("hello " + username);
}
}
- @WebServlet : ์๋ธ๋ฆฟ ์ ๋ ธํ ์ด์ (name = ์๋ธ๋ฆฟ ์ด๋ฆ, urlPatterns = URL ๋งคํ)
- http://localhost:8080/hello?username=kim ์คํ
- ๊ฒฐ๊ณผ : hello kim
- ๊ฐ๋ฐ์ ๋๊ตฌ๋ก ํ์ธํ๋ฉด Response Headers์ ๋ด๊ฐ ์ง์ ํ Content-Type์ ํ์ธํ ์ ์๋ค.
* ์ฐธ๊ณ ๋ก ๋ก๊ทธ๋ฅผ ์กฐ๊ธ ๋ ์์ธํ ๋ณด๊ธฐ ์ํด์๋ application.properties์
logging.level.org.apache.coyote.http11=trace
๋ฅผ ์ถ๊ฐํด์ฃผ๋ฉด ์๋ฒ๊ฐ ๋ฐ์ HTTP ์์ฒญ ๋ฉ์ธ์ง๋ฅผ ์ถ๋ ฅํด์ค๋ค.
(์ด์์๋ฒ์ ๋ชจ๋ ์์ฒญ ์ ๋ณด๋ฅผ ๋ค ๋จ๊ธฐ๋ฉด ์ฑ๋ฅ์ ํ๊ฐ ๋ฐ์ํ ์ ์์ผ๋ฏ๋ก ๊ฐ๋ฐ ๋จ๊ณ์์๋ง ์ ์ฉ)