[์ฐธ๊ณ ๊ฐ์] ๊น์ํ๋์ ์คํ๋ง MVC 1ํธ - ๋ฐฑ์๋ ์น ๊ฐ๋ฐ ํต์ฌ ๊ธฐ์
React,Vue.js๋ฅผ CSR+SSR ๋์์ ์ง์ํ๋ ์น ํ๋ ์์ํฌ๋ ์์
SSR์ ์ฌ์ฉํ๋๋ผ๋, ์๋ฐ์คํฌ๋ฆฝํธ๋ฅผ ์ฌ์ฉํด์ ํ๋ฉด ์ผ๋ถ๋ฅผ ๋์ ์ผ๋ก ๋ณ๊ฒฝ ๊ฐ๋ฅ
HTML์ ํธ๋ฆฌํ๊ฒ ์์ฑํ๋ ๋ทฐ ๊ธฐ๋ฅ
@ServletComponentScan ์ถ๊ฐ
@ServletComponentScan //์๋ธ๋ฆฟ ์๋ ๋ฑ๋ก
@SpringBootApplication
public class ServletApplication {
public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}
}
@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);
}
}
application.properties
logging.level.org.apache.coyote.http11=debug
์๋ธ๋ฆฟ์ ๊ฐ๋ฐ์๊ฐ HTTP ์์ฒญ ๋ฉ์์ง๋ฅผ ํธ๋ฆฌํ๊ฒ ์ฌ์ฉํ ์ ์๋๋ก ๊ฐ๋ฐ์ ๋์ ์ HTTP ์์ฒญ ๋ฉ์์ง๋ฅผ ํ์ฑํ๋ค. ๊ทธ๋ฆฌ๊ณ ๊ทธ ๊ฒฐ๊ณผ๋ฅผ HttpServletRequest ๊ฐ์ฒด์ ๋ด์์ ์ ๊ณตํ๋ค.
HttpServletRequest๋ฅผ ์ฌ์ฉํ๋ฉด ๋ค์๊ณผ ๊ฐ์ HTTP ์์ฒญ ๋ฉ์์ง๋ฅผ ํธ๋ฆฌํ๊ฒ ์กฐํํ ์ ์๋ค.
POST /save HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded
username=kim&age=20
HTTP ์์ฒญ ๋ฉ์์ง๋ฅผ ํตํด ํด๋ผ์ด์ธํธ์์ ์๋ฒ๋ก ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ๋ ๋ฐฉ๋ฒ
๋ฉ์์ง ๋ฐ๋ ์์ด, URL์ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ฅผ ์ฌ์ฉํด์ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํด๋ณด๊ฒ ๋ค
์) ๊ฒ์, ํํฐ, ํ์ด์ง๋ฑ์์ ๋ง์ด ์ฌ์ฉํ๋ ๋ฐฉ์
URL์ ?๋ฅผ ์์์ผ๋ก ์ฟผ๋ฆฌํ๋ผ๋ฏธํฐ๋ฅผ ๋ณด๋ผ ์ ์๋ค. ์ถ๊ฐ ํ๋ผ๋ฏธํฐ๋ &๋ก ๊ตฌ๋ถํ๋ค.
String username = request.getParameter("username");
//๋จ์ผ ํ๋ผ๋ฏธํฐ ์กฐํ
Enumeration<String> parameterNames = request.getParameterNames();
//ํ๋ผ๋ฏธํฐ ์ด๋ฆ๋ค ๋ชจ๋ ์กฐํ
Map<String, String[]> parameterMap = request.getParameterMap();
//ํ๋ผ๋ฏธํฐ๋ฅผ Map ์ผ๋ก ์กฐํ
String[] usernames = request.getParameterValues("username");
//๋ณต์ ํ๋ผ๋ฏธํฐ ์กฐํ
username=hello&username=kim ๊ณผ ๊ฐ์ด ํ๋ผ๋ฏธํฐ ์ด๋ฆ์ ํ๋์ธ๋ฐ ๊ฐ์ด ์ค๋ณต์ผ ๊ฒฝ์ฐ์ request.getParameterValues()๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค.
request.getParameter()๋ ํ๋์ ํ๋ผ๋ฏธํฐ ์ด๋ฆ์ ๋ํด์ ๋จ ํ๋์ ๊ฐ๋ง ์์ ๋ ์ฌ์ฉํด์ผํ๋ค.
ํน์ง
์๋ฒ ์ ์ฅ์์๋ GET ์ฟผ๋ฆฌํ๋ผ๋ฏธํฐ ํ์๊ณผ POST Form ํ์์ด ๋์ผํ๋ฏ๋ก ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ์กฐํ ๋ฉ์๋๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉํ๋ฉด๋๋ค.
์ฐธ๊ณ )
GET URL ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ํ์์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ ๋๋ HTTP ๋ฉ์์ง ๋ฐ๋๋ฅผ ์ฌ์ฉํ์ง ์๊ธฐ ๋๋ฌธ์ content-type์ด ์๋ค.
POST HTML Form ํ์์ HTTP ๋ฉ์์ง ๋ฐ๋์ ํด๋น ๋ฐ์ดํฐ๋ฅผ ํฌํจํด์ ๋ณด๋ด๊ธฐ ๋๋ฌธ์ ๋ฐ์ดํฐ๊ฐ ์ด๋ค ํ์์ธ์ง content-type์ ๊ผญ ์ง์ ํด์ผ ํ๋ค. ์ด๋ ๊ฒ ํผ์ผ๋ก ์ ์กํ๋ ํ์์ pplication/x-www-form-urlencoded ๋ผ ํ๋ค.
๊ฐ์์ ๋ ์๋๋ฅผ ๋ด์ผ๊ฒ ๋น...!!!