/ JSP

6. Servlet 2

SEOUL G-캠프

0. 목차



Chapter6. Servlet 본격적으로 살펴보기-Ⅱ

Ch6 - 1. Servlet 작동 순서

Ch6 - 2. Servlet 라이프 사이클

Ch6 - 3. Servlet 선처리/후처리



Ch6 - 1. Servlet 작동 순서


▶ Servlet 작동 순서

▷ 클라이언트에서 servlet 요청이 들어 오면
▷ 서버에서는 servlet 컨테이너를 만들고
▷ 요청이 있을 때마다 스레드 생성




Ch6 - 2. Servlet 라이프 사이클


▶ Servlet의 사용도가 높은 이유 : 빠른 응답 속도

▷ Servlet은 최초 요청 시, 객체가 생성 → 메모리에 로딩
▷ 이후 요청 시, 기존의 객체 → 재활용
▷ 객체 생성을 줄여 동작 속도가 빨라질 수 밖에 만듦


▶ 실습

▷ ex 서블릿 생성
▷ ServletLifeTimeEx 클래스 생성
@WebServlet("/ServletLifeTimeEx")
public class ServletLifeTimeEx extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    // 생성자
    public ServletLifeTimeEx() {
        super();
    }
    
    // doGet
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet");
    }
    
    // doPost
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet");
    }
▷ init() 오버라이드
▷ destroy() 오버라이드
// init
@Override
public void init() throws ServletException {
    System.out.println("init");
}

// destroy
@Override
public void destroy() {
    System.out.println("destroy");
}
▷ 서버 구동
// conosle

init // 최초 한번
doGet // 새로고침 할 때마다 생성
doGet
doGet
doGet
doGet
...
destroy // 종료할 때 한번
...



Ch6 - 3. Servlet 선처리/후처리


▶ Servlet 선처리

@PostConstruct
▷ init() 실행 전


▶ Servlet 후처리

@PreDestroy
▷ destroy() 실행 후


▶ 실습

@PostConstruct 작성
@PreDestroy 작성
@PostConstruct
private void initPostConstruct() {
    System.out.println("initPostConstruct");
}

@PreDestroy
private void destroyPreDestroy() {
    System.out.println("destroyPreDestroy");
}
▷ 서버 구동
// console

...
initPostConstruct // 선처리, @PostConstruct
init
doGet
doGet
doGet
doGet
doGet
doGet
doGet
...
destroy 
destroyPreDestroy // 후처리, @PreDestroy
...