WAS가 서블릿 요청을 받으면 해당 서블릿이 메모리에 있는지 확인
if (메모리에 해당 서블릿 없음) {
- 해당 서블릿 클래스를 메모리에 올림(이때 생성자 함수 호출)
- init() 메소드를 실행
}
- service()메소드를 실행 -> 요청이 들어왔을 때 응답해야 하는 모든 내용은 service method에 저장해야 함
package examples;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LifecycleServlet
*/
@WebServlet("/LifecycleServlet")
public class LifecycleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LifecycleServlet() {
System.out.println("LifecycleServlet 생성");
// TODO Auto-generated constructor stub
}
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 호출");
}
}
package examples;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LifecycleServlet")
public class LifecycleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LifecycleServlet() {
System.out.println("LifecycleServlet 생성");
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException {
System.out.println("init 호출");
}
public void destroy() {
System.out.println("destroy 호출");
}
//service() 메서드 비활성화
// protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// System.out.println("service 호출");
// }
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<head><title>form</title></head>");
out.println("<body>");
out.println("<form method='post' action='/firstweb/LifecycleServlet'>"); //form: action의 url으로 method를 요청한다는 의미
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 req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String name = req.getParameter("name"); //request의 요청 정보로부터 name값을 가져옴
out.println("<h1> hello " + name + "</h1>");
out.close();
}
}