A servlet is a java class that can have embedded html inside it. They are generally used in j2ee web applications. A servlet can run inside a j2ee container. Various j2ee containers available are tomcat, weblogic, jrun etc.
First a web application containing the servlet is created following the j2ee directory structure. Then the web application is deployed into the server, and the server is started.
When a http request is sent to a particular servlet, it sends back a response to the client. The sent response is purely html. Lets assume that we have created a servlet called login.java
When a request is sent for login.java to the server. The server tries to find out whether an object of this servlet is already created or not. If it has been created then it uses that object else it creates a new object of the servlet.
A servlet object has many methods like init(ServletConfig sg), service(ServletRequest sr, ServletResponse ss), destroy(), getServletInfo(), getServletConfig(). The server calls the methods one after the other in a pattern. It calls the init method first. While calling the init method it passes a ServletConfig type object as parameter. The server creates a ServletConfig type object by taking help of the deployment descriptor. After calling the init method of the servlet the server calls the service method. While calling the service method it passes two arguments. The arguments passed to the service method are ServletRequest type object and a ServletResponse type object.
Whatever we want the servlet to do should be placed in the service method. So response for a servlet generally comes from the service method. The destroy method of the servlet is called only when a servlet object gets destroyed.
Some of the interfaces and classes that will be required for writing servlets are Servlet, ServletConfig, ServletRequest, ServletResponse SingleThreadModel, GenericServlet. We have to implement the Servlet interface to create a servlet. We have to provide implementations of all the methods inside the Servlet interface.
Proper understanding of servlet is very much important if one wants a successful career in J2ee. Because servlets is the base of other related technologies in j2ee.
Source by Chinmay Patel
Post a Comment