[부스트코스] 1. 웹 프로그래밍 기초 : Servlet 작성, 라이프싸이클
강의 링크 : https://www.edwith.org/boostcourse-web/lecture/16687/
[LECTURE] 2) Servlet 작성 방법 : edwith
들어가기 전에 현재 프로젝트에서 웹을 개발할 때 서블릿을 직접 써서 개발하지는 않습니다. 조금 더 편하게 사용할 수 있게 도와주는 다양한 프레임워크를 사용해서 개발하는 경우가 더 ... - 부스트코스
www.edwith.org
Servlet 작성 방법
1. Servlet 3.0 이상
- web.xml 파일 사용 X
- 자바 어노테이션 사용
2. Servlet 3.0 미만
- servlet을 등록할 때 web.xml 파일에 등록
첫 번째 방법으로 실습을 해보자!
exam31라는 프로젝트를 생성하여 1부터 10까지 출력하는 TenServlet을 작성해본다.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<h1>1부터 10까지 출력</h1>");
for (int i=1;i<=10;i++) {
out.print(i+"<br>");
}
out.close();
}
Servlet 라이프 싸이클
life cycle : 어떤 객체의 생성부터 소멸까지의 과정
서블릿의 라이프 싸이클을 알아보기 위해 init, destroy, service 세 가지 메소드를 오버라이딩해보자!
public LifeCycleServlet() {
super();
System.out.println("LifeCycleServlet 생성");
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init");
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
System.out.println("destroy");
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("service");
}
이 코드를 서버에 run해보면?
콘솔에 아래와 같은 결과를 얻는다.
해당 URL로 클라이언트가 서버에게 요청을 하면 LifeCycleServlet이라는 URL을 통해 누군지 알아내고
이 해당 클래스가 메모리에 존재하는지 체크한다.
서버가 메모리에 없다고 판단해서 LifeCycleServlet 메소드를 생성한다.
새로 고침을 한다면?
service만 출력이 되었다.
요청된 객체가 메모리에 있을 때는 service 메소드만 호출한다.
destroy() 메소드는 서블릿이 수정되었을 때 더 이상 사용될 수 없으므로 호출된다.
서블릿 Life Cycle
- WAS는 서블릿 요청을 받으면 해당 서블릿이 메모리에 있는지 확인함
- 메모리에 없다면 해당 클래스를 메모리에 올리고(객체생성) init() 메소드를 실행 -> service() 메소드 실행
- 웹 어플리케이션이 갱신되거나 WAS가 종료되면 destroy() 메소드 실행
service (request, response) 메소드
- HttpServlet의 service 메소드는 템플릿 메소드 패턴으로 구현됨
- 클라이언트의 요청 = GET : doGET 메소드 호출
- 클라이언트의 요청 = POST : doPost 메소드 호출
doGet, doPost 오버라이딩
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();
}
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();
}