
만약, bogang.com에서 기사를 보여주는 웹페이지를 만들었다고 해보자. 클라이언트가 기사를 요청하면 news.html 파일을 응답으로 보낼 수 있다. 기사는 변하지 않기에 어느 사용자에게나 동일한 화면이 보일 것이다. 이때 news.html를 정적컨텐츠라고 한다. Web Server는 정적 데이터만을 전달할 수 있었다.
그러나 만약 클라이언트가 본인이 스크랩한 뉴스들에 대한 리스트를 보고 싶다면?
해당 데이터는 클라이언트마다 다를 것이고, 각 클라이언트마다 다른 화면을 동적으로 보여줄 수 있어야한다.
각 클라이언트의 스크랩 리스트 즉, 동적 컨텐츠를 위해 등장한 것이 Web Application Server (WAS) 이다.

WAS가 요청에 따른 동적 컨텐츠를 간편하게 제공할 수 있게 해주는 도구가 Servlet이다.
💡 Servlet이란?
동적컨텐츠를 만드는 데에 사용되는 자바 기반의 웹 어플리케이션 프로그래밍 기술 혹은 그 기술에서 사용되는 객체

Client가 동적 컨텐츠를 요청할 시 Web Container는 각 요청마다 Thread를 생성하고 Servlet을 실행시킨다.
Servlet Container는 Servlet을 담는 바구니로 생각할 수 있다. Servlet Container는 Servlet의 생명주기를 관리하고 클라이언트의 요청을 ServletRequest 객체로 만들어서 Servlet에 넘겨준다.
Servlet Container의 종류 중 하나가 그 유명한 Apache Tomcat이다.
스프링에서 구현하는 Servlet의 코드를 살펴보면,
package javax.servlet;
import java.io.IOException;
public interface Servlet {
void init(ServletConfig var1) throws ServletException;
ServletConfig getServletConfig();
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
String getServletInfo();
void destroy();
}
init()
실행할 Servlet 인스턴스가 없을 경우 해당 메서드로 Servlet을 생성한다.
service()
사용자의 요청을 처리하는 실제 기능을 수행하는 메서드이다. 해당 메서드로 ServletRequest를 비즈니스 로직으로 처리하여 ServletResponse로 응답한다.
destroy()
Servlet 인스턴스를 삭제한다.
해당 메서드들은 Sevlet Container가 호출하여 싱글톤으로 관리한다! 이런 과정을 생명주기를 관리한다고 한다.
웹에서는 표준 프로토콜인 HTTP를 사용하여 통신한다. HTTP를 사용한 요청과 응답을 다루기 위해 자바에는 HttpServlet이 있다.

HttpServlet의 계층 구조는 이렇다
Servlet이 HTTP 요청을 처리하는 과정을 살펴보자
구현된 HttpServlet.class에서 주요 메서드만을 살펴보면,
public abstract class HttpServlet extends GenericServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_get_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_post_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_put_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_delete_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
...
}
doXXX() 메서드로 각 HTTP 메서드 요청에 따른 메서드를 호출 할 수 있다.
@WebServlet(name = "myServlet", urlPatterns = "/scrap")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
PrintWriter writer = res.getWriter();
writer.println("Get My Articles!");
}
}
각 요청에 대해 처리하기 위해 서비스 메서드를 재정의한 코드이다. 이렇게 각 메서드를 재정의함으로써 요청에 대한 처리 방법을 지정할 수 있다
또한 Servlet 3.0 API부터는 @WebServlet 어노테이션을 통해 servlet이름과 url를 등록함으로써 매핑해줄 수 있다. /scrap URL로 get 요청이 들어오면 doGet() 메서드가 실행된다.
(이전버전까지는 Web.xml에 클래스 경로와, url 패턴, 서블릿 이름을 정의해주었다.)
HttpServletResponse에 응답 결과를 담은 후 Servlet Container로 전달되고, Servlet Container가 응답 메시지를 생성 후 클라이언트에게 전달한다.
아래는 위키피디아에서 확인할 수 있는 포트 80의 www.example.com HTTP 메시지의 예시다.
GET/restapi/v1.0HTTP/1.1
Accept: application/json
Authorization: Bearer UExBMDFUMDRQV1MwMnzpdvtYYNWMSJ7CL8h0zM6q6a9ntw
HTTP/1.1 200OKDate: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Content-Length: 138
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Connection: close
<html>
<head>
<title>An Example Page</title>
</head>
<body>
Hello World, this is a very simple HTML document.
</body>
</html>
HTTP 프로토콜은 말그대로 규칙이다. 개발자는 응답과 요청을 규약에 맞게 다루어야한다. 그치만 요청과 응답을 파싱하여 하나하나 구하는 건 너무나 번거롭고 힘들다.
이러한 과정을 미리 구현해둔 것이 Servlet이다!
HttpServlet에는 관련된 메서드가 많이 구현되어 있고 해당 메서드를 통해 요청 정보를 얻을 수 있고, 처리 결과를 응답 형식에 맞게 변환할 수 있다.
이처럼 Servlet은 개발자가 비즈니스 로직 구현에 집중할 수 있도록 한다!
테코톡 [10분 테코톡] 🐶 코기의 Servlet vs Spring
https://www.youtube.com/watch?v=calGCwG_B4Y
테코톡 [10분 테코톡] 🌻타미의 Servlet vs Spring
https://www.youtube.com/watch?v=2pBsXI01J6M
[10분 테코톡] 리오, 밀리의 Servlet & Spring MVC
https://www.youtube.com/watch?v=3gmOuUWPZV4&t=10s