Darren's Devlog

스프링의정석 CH02-03,04 HTTP 요청과 응답 본문

Spring/스프링의정석

스프링의정석 CH02-03,04 HTTP 요청과 응답

Darren Gwon 2022. 8. 1. 22:21
반응형

psvm의 매개변수 String[] args으로 값이 넘어가는 것과 비슷한 원리로,

URL로 GET요청을 보내게 되면, 톰캣에서 HttpServletRequest 객체를 생성을 하고,

요청과 함께 전송된 데이터를 request객체에 담아 매서드의 매개변수로 제공을 해준다.

 

HttpServletRequest는 ServletRequest 인터페이스를 구현한 클래스이다.

https://tomcat.apache.org/tomcat-9.0-doc/servletapi/javax/servlet/http/HttpServletRequest.html

 

HttpServletRequest (Servlet 4.0 API Documentation - Apache Tomcat 9.0.65)

Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters. Because this method returns a StringBuffer, not a string, you can mo

tomcat.apache.org

 

요청을 보낼 때, 우리가 원하는 데이터를 포함하여 같이 보내줄 수 있다.

http://111.222.333.444:8080/myrequest?writer=darren&message=helloworld

위에 같이 URL 끝 물음표 이후에 name=value 형식으로 요청을 같이 보내면,

HttpServletRequest 객체의 .getParameter("name")메서드를 통해 값을 받아올 수 있다.

 

response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<img src='resources/img/dice"+idx1+".jpg'>");
out.println("<img src='resources/img/dice"+idx2+".jpg'>");
out.println("</body>");
out.println("</html>");
out.close();

또한 HttpServletResponse 객체를 통해 요청에 대한 응답을 보낼 수 있다.

 

웹 프로그래밍을 쉽게 말하자면 요청에 대해서 동적으로 html(view)을 만들어 응답해주면

그게 곧 웹 프로그래밍이라고 할 수 있다.

반응형
Comments