The following example servlet prints how many times its service() method was called. Note that HttpServlet is a subclass of GenericServlet, an implementation of the Servlet interface. The service() method of HttpServlet class dispatches requests to the methods doGet(), doPost(), doPut(), doDelete(), and so on; according to the HTTP request. In the example below method service() is overridden and does not distinguish which HTTP request method it serves.
Code: Select all
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletLifeCycleExample extends HttpServlet {
private int count;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
getServletContext().log("init() called");
count=0;
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
getServletContext().log("service() called");
count++;
response.getWriter().write("Incrementing the count: Count = "+count);
}
@Override
public void destroy() {
getServletContext().log("destroy() called");
}
}
.........................................................................................................................
Servlets are most often used to (a) Process or store data that was submitted from an HTML form.
(b) Provide dynamic content such as the results of a database query.
(c) Manage state information that does not exist in the stateless HTTP protocol, such as filling the articles into the shopping cart of the appropriate customer.
N:B:-see more again.