Servlet의 생명주기
WAS는 서블릿 요청을 받으면 해당 서블릿이 메모리에 있는지 확인한다.
메모리에 없다면, 해당 서블릿 클래스를 메모리에 올리고, init() 메서드를 실행한다.
메모리에 있다면, service() 메서드를 실행한다.
WAS가 종료되거나, 웹 어플리케이션이 새롭게 갱신될 경우 destroy() 메서드가 실행된다.
참고 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | @WebServlet("/LifeCycleServlet") public class LifeCycleServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LifeCycleServlet() { System.out.println("LifeCycleServlet 생성"); } public void init(ServletConfig config) throws ServletException { System.out.println("init 호출"); } public void destroy() { System.out.println("destroy 호출"); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("service 호출"); } } | cs |
실행 결과
1. 클라이언트가 /LifeCycleServlet으로 서버에게 요청을 하면, 서버는 url을 받아서 LifeCycleServlet 클래스로 넘어온다.
그런 다음, 해당 클래스가 메모리에 존재하는지를 확인하며, 메모리에 존재하지 않는다면 이 객체를 생성해야 하므로 생성자가 호출된다.
2. 브라우저를 새로고침하거나 다른 브라우저를 통해 들어가도 service만 호출된다.
서블릿은 서버에 서블릿 객체를 여러 개 만들지 않는다.
요청이 여러 번 들어오면 매번 생성하는 것을 반복하는 것이 아니라 실제 요청된 객체가 메모리에 있는지 없는지를 확인하고 있다면
service 메서드만 호출한다.
service()
service 메서드는 HttpServlet에 이미 구현이 되어 있다.
내가 만든 클래스가 service 메서드를 가지고 있지 않다면, 부모 클래스(HttpServlet)의 service 메서드가 실행된다.
HttpServlet의 service 메서드는 템플릿 메서드 패턴으로 구현되어 있다.
클라이언트의 요청이 GET일 경우에는 자신이 가지고 있는 doGet 메소드를 호출하고,
POST일 경우에는 자신이 가지고 있는 doPost 메소드를 호출한다.
참고 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | @WebServlet("/LifeCycleServlet") public class LifeCycleServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LifeCycleServlet() {} @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>form</title></head>"); out.println("<body>"); out.println("<form method='post' action='/firstweb/LifeCycleServlet'>"); out.println("name : <input type='text' name='name'><br>"); out.println("<input type='submit' value='ok'><br>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); out.close(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); out.println("<h1> hello " + name + "</h1>"); out.close(); } } | cs |
실행 결과
1. URL로 직접 요청할 경우 method 값이 GET으로 넘어간다.
따라서 HttpServlet이 가진 service 메서드는 doGet 메서드를 호출하며, 아래와 같은 화면이 보여지게 된다.
2. input 태그에 "hh_lin"이라는 문자열을 입력 후 ok 버튼을 누르게 되면 form이 POST 방식으로 전송된다.
따라서 HttpServlet이 가진 service 메서드는 doPost 메서드를 호출하며, 아래와 같은 화면이 보여지게 된다.
참고 자료
'Web > 기초' 카테고리의 다른 글
[WEB] redirect (0) | 2018.12.09 |
---|---|
[WEB] Request, Response (0) | 2018.11.21 |
[WEB] Servlet (0) | 2018.11.21 |
[WEB] Apache Tomcat (0) | 2018.11.20 |
[WEB] WAS (0) | 2018.11.16 |