본문 바로가기
events/부스트코스

[부스트코스] 1. 웹 프로그래밍 기초 | 5. Servlet - BE | Request, Response 객체

by kimtahen 2020. 2. 28.
반응형

1. WAS의 요청과 응답

  먼저 이 다이어그램을 보자.

https://www.edwith.org/boostcourse-web/lecture/16689/

클라이언트의 웹 브라우저에서는 서버의 WAS로 요청을 보낸다. 그럼, WAS는 요청 시의 정보를 가지고 HttpServletRequest 객체를 생성하고, 웹 브라우저에 반대로 응답을 보내기 위한 HttpServletResponse 객체를 생성한다. 이 두가지의 객체를 서블릿으로 전달하고, 서블릿에서는 이 객체를 사용하여 여러 작업들을 하게 된다. 실제로 doGet, doPost 메서드의 파라미터로 

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}

HttpServletRequest, HttpServletResposne를 가지고 있다.

 

HttpServletRequest

  이 객체는 HTTP 프로토콜의 요청 정보를 담고 있기 때문에, 서블릿으로 이 정보를 전달할 수 있다. 대표적으로 헤더 정보, 파라미터, 쿠키, URI, URL 등의 정보를 가져 올 수 있는 메서드를 포함하고 있다. 

https://tomcat.apache.org/tomcat-10.0-doc/servletapi/jakarta/servlet/http/HttpServletRequest.html?is-external=true

 

HttpServletRequest (Servlet {servlet.spec.version} API Documentation - Apache Tomcat 10.0.0-M1)

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

Tomcat 10.0의 공식문서에 업로드 되어있는 HttpServletRequest 객체의 메서드들의 요약과 설명이다.

 

HttpServletResponse

  이 객체는 요청을 보낸 클라이언트에게 응답을 보내기 위해 사용된다. 대표적으로 content type, 응답코드, 응답 메시지 등을 전송한다.

https://tomcat.apache.org/tomcat-10.0-doc/servletapi/jakarta/servlet/http/HttpServletResponse.html?is-external=true

 

HttpServletResponse (Servlet {servlet.spec.version} API Documentation - Apache Tomcat 10.0.0-M1)

Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the loca

tomcat.apache.org

Tomcat 10.0의 공식문서에 업로드 되어있는 HttpServletResponse 객체의 메서드들의 요약과 설명이다.

2. HttpServletRequest, HttpServletResponse 객체 활용하기

  eclipse를 실행해서 doGet 메서드를 가지고 있는 Servlet 하나를 이렇게 만들어보자

당연히, doGet 메서드의 파라미터에는 request객체와 response 객체가 있다.

 

Query String을 가져와서, HTML로 응답하는 작업을 수행하도록 해보자.

URL 뒤에는 추가적으로 웹 서버에 전송할 수 있는 Query String을 덧붙일 수 있다. Query String의 시작은 '?' 기호이며 '&'으로 구분할 수 있다. 그리고 각각은 Parameter과 Value로 표현된다.

 

아래와 같이 doGet 메서드를 작성해보자. 상단에 import java.io.PrintWriter; 코드를 써주어 임포트 시킨다.

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String color = request.getParameter("color");
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head></head>");
		out.println("<body>");
		out.println("name : " + name);
		out.println("<br>");
		out.println("color : " + color);
		out.println("</body>");
		out.println("</html>");
	}

Parameter은 무조건 '문자열' 타입이기 때문에 String을 사용한다. HttpServletRequest의 request 객체는 클라이언트의 요청에 대한 정보를 담고 있고, 그렇기에 Query String 정보도 가지고 있다. 코드에서 request.getParameter( ) 메서드가 바로 괄호 안의 인수에 대한 Value를 찾는 역할을 한다. name과 color 값을 두 변수에 저장하고 이를 출력하기 위해 저번 포스팅에서 했던 방식과 마찬가지로 PrintWriter 객체를 가져와서 name과 color 정보를 담은 html을 출력한다.

 

이제 Servlet을 실행시켜보자.

Query String 을 입력하지 않았으니 null값이 뜨는 것은 당연하다. 

 

이번에는 URL 뒤에 ?name=KimTaeHyeon&color=navy 라고 쿼리스트링을 덧붙여보자. 그리고 새로고침을 클릭하면

이렇게 서블릿에서 정상적으로 파라미터를 추출하는 것을 볼 수 있다.

반응형

댓글