
Servelt = Server + Applet
javax.servlet.Servlet 인터페이스를 기반으로 한다.Servlet과 ServletConfig 구현을 모아 둔 추상 클래스가 GenericServlet 이다.HttpServlet 클래스를 상속한다.HttpServlet은 GenericServlet을 상속javax.servlet.ServletException (현재는 jakarta.servlet.ServletException) 사용.실제로 우리가 작성하는 서블릿은 대부분 다음 형태이다.
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 로직
}
}
init() 호출service() 호출doGet(), doPost() 등으로 분기destroy() 호출service()를 호출한다.web.xml VS @annotaion 을 기반으로 서블릿을 등록·매핑load-on-startup), 종료 시 destroy() 호출webapp/WEB-INF/web.xml<web-app>: 루트 태그<servlet>: 서블릿 정의 (servlet-name, servlet-class, init-param 등)<servlet-mapping>: 서블릿 매핑 정보<context-param>: 애플리케이션 전체에서 공유하는 초기값<error-page>: 에러 코드에 따른 페이지 설정<session-config>: 세션 타임아웃 설정<filter>, <listener> 등web.xml 기반 매핑@WebServlet 애노테이션 매핑<servlet>
<servlet-name>xmlmapping</servlet-name>
<servlet-class>com.section01.xml.LifeCycleTestServlet</servlet-class>
<load-on-startup>100</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>xmlmapping</servlet-name>
<url-pattern>/xml-lifecycle</url-pattern>
</servlet-mapping>
<servlet>과 <servlet-mapping>은 세트로 묶어서 사용<load-on-startup> 숫자가 낮을수록 서버 구동 시 먼저 로딩@WebServlet("/annotation-lifecycle")
public class LifeCycleTestServlet extends HttpServlet {
// ...
}
@WebServlet(value = "/annotation-lifecycle", loadOnStartup = 1)
public class LifeCycleTestServlet extends HttpServlet {
// ...
}
<servlet> 내부 <init-param> 으로 설정web.xml 예시
<servlet>
<servlet-name>configTest</servlet-name>
<servlet-class>com.example.ConfigTestServlet</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@example.com</param-value>
</init-param>
</servlet>
서블릿에서 사용
public class ConfigTestServlet extends HttpServlet {
@Override
public void init() throws ServletException {
ServletConfig config = getServletConfig();
String adminEmail = config.getInitParameter("adminEmail");
System.out.println("Admin Email = " + adminEmail);
}
}
포인트
<web-app> 아래 <context-param> 사용web.xml 예시
<context-param>
<param-name>fileUploadPath</param-name>
<param-value>/upload</param-value>
</context-param>
서블릿에서 사용
public class ContextTestServlet extends HttpServlet {
@Override
public void init() throws ServletException {
ServletContext context = getServletContext();
String uploadPath = context.getInitParameter("fileUploadPath");
System.out.println("Upload Path = " + uploadPath);
}
}
비교 요약
http://localhost:포트/컨텍스트경로/서블릿URL예시
http://localhost:8800/first/test1.dofirst → context path/test1.do → 서블릿 매핑 URL핵심 메서드 3개
init()service() → doGet(), doPost() 등destroy()동작 순서
init() 한 번만 호출service() 호출doGet(), doPost() 등 호출destroy() 호출, 자원 정리예시 코드 (라이프사이클 로그)
@WebServlet(value = "/lifecycle", loadOnStartup = 1)
public class LifeCycleTestServlet extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("init() 호출: 서블릿 초기화");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("service() 호출");
super.service(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doGet() 호출");
resp.getWriter().println("Lifecycle Test");
}
@Override
public void destroy() {
System.out.println("destroy() 호출: 자원 반납");
}
}
암기 포인트
init() 은 최초 한 번service() 는 모든 요청마다destroy() 는 종료 시 한 번HttpServlet 상속.service() → `doGet/doPostServletConfig: 서블릿 개별 초기값 (<init-param>).ServletContext: 애플리케이션 공용 초기값 (<context-param>).load-on-startup 을 사용하면 서버 구동 시 서블릿을 미리 로딩 가능.