Three Life Cycle Methods of Servlet:
public void init() throws ServletException {
// Initialization code...
}
service Method:
public void service(ServletRequest request, ServletResponse response)
throws ServlertException,IOException{
}
destroy Method:
Signature of the destroy() method:
public void destroy() {
// Finalization code...
}
- init
- service
- destroy
- The servlet is initialized by calling the init () method.
- The init method is designed to be called only once.
- It is called when the servlet is first created, and not called again for each user request.
- When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate.
public void init() throws ServletException {
// Initialization code...
}
service Method:
- The service() method is the main method to perform the actual task.
- The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
- Each time the server receives a request for a servlet, the server create a new thread and calls service.
- The service() method checks the HTTP request type (GET, POST, etc.) and calls doGet, doPost etc. methods as appropriate.
public void service(ServletRequest request, ServletResponse response)
throws ServlertException,IOException{
}
- So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
- The doGet() and doPost() are most frequently used methods with in each service request.
destroy Method:
- The destroy() method is called only once at the end of the life cycle of a servlet.
- This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
- After the destroy() method is called, the servlet object is marked for garbage collection.
- servlet is garbage collected by the garbage collector of the JVM.
Signature of the destroy() method:
public void destroy() {
// Finalization code...
}
No comments:
Post a Comment