Saturday, 13 September 2014

Servlet

Servlet is java Object and it is used to create dynamic web pages, which deployed in web server or application server (e.g tomcat, jboss). And invoked from web browser to run inside servelet container.
It is part of J2EE. Servlet works on client-server architecture. clients are browser and servers are container (webservers or application servers)where java codes deployed.


Server should have servlet container to handle request and response.When browser sends Http requests, servlet container checks the request of type servlet then it find the appropriate servlet and delegate the request to servlet and after finishing the execution of servlet, Http response is generated and response sent back to browser.

Servlet container is responsible to handle lifecycle for servlet. 

Servlet Lifecycle
A servlet passes through the following stages in its life.
  • Initialize
  • Service
  • Destroy



Servlets instance gets created by the web container which calls the init() method for first Http request. At init() method completion, Servlets is present in a ready state to service the requests from client. But make sure init() method execute once for first request not for all request.

Servlets service method is being called by container to handle every request, by spawning new threads. For every request, from thread pool of the web container there also exists the possibility to have one threaded servlet.

Before the instance gets destroyed, the destroy() method will be called by the container. After destroy(), the servlet is considered as a potential candidate, for collection of garbage.

Hence init(), service() and destroy() methods are the main methods of Servlet. Apart from these methods some other method are also present in the Servlet interface. To understand in more let's see below diagram, which present in javax.servlet package-




The Servlet interface is the base interface for all servlets. The GenericServlet interface, described later, implements this interface. The interface defines the basic methods that a servlet running inside a servlet engine defines to process client requests. The Servlet interface defines the following life cycle methods:
  • init()— Servlet initialization routine
  • service()— All-purpose routine to process client requests
  • destroy()— Clean-up routine for freeing resources, storing state information, and so forth
The interface also defines the getServletConfig() method, which returns the ServletConfig object that holds the initialization parameters and other configuration of the servlet defined by the user. These parameters are usually defined in the deployment descriptor of the Web application. Developers who want to implement the Servlet interface should take care of storing the ServletConfig object passed to the init method if the getServletConfig() method has to return the object when the servlet needs the configuration object. This interface also provides a getServletInfo() method, which can return information about the servlet, such as its author, version, and copyright text.

The ServletConfig interface is configuration object, which is passed into the servlet when it's instantiated (through the init method), provides user configuration information as name-value pairs.
getInitParameter
Takes a string representing the initialized parameter as argument and returns the value of the parameter.
getInitParameterNames
Returns all the names of the parameters.
getServletContext
Returns the ServletContext object, which represents the servlet's runtime environment. The ServletContext object is explained later.

The ServletContext interface is the servlet's view of the Web container. The getServletContext() method of ServletConfig returns the ServletContext object. This interface provides a lot of methods, and for easier understanding we can classify the methods into the categories in the following sections. 
getMajorVersion
the major version of the Servlet API supported by the container.
getMinorVersion
the minor version of the Servlet API supported by the container.
getMimeType(String file)
Returns the MIME type of the file. text/html is one of the common MIME types.
getRealPath
For the SimpleServlet2 example, the path returned is c:\bea\user_projects\mydomain\applications\wlsUnleashed\SimpleServlet2. As you can see, it's with respect to the location of the file in the computer and the OS on which the WebLogic Server is running. This method will return null if WebLogic Server cannot translate the virtual path to a real path.
getServerInfo
Returns the name and version of the servlet container. In our case, you'll an output similar to the following: WebLogic Server 8.1 Thu Mar 20 23:06:05 PST 2003 246620.
   


Let's create the first servlet example.


 
Above is the directory system to create web application (hope you have some idea).Create application name is mywewapp. create the below Servlet class and put inside classes folder inside WEB-INF.
 
package example; 
import java.io.*;

import javax.servlet.*;

public class MyServlet extends GenericServlet{ 
 
  public void service(ServletRequest req,ServletResponse res)
    throws ServletException, IOException
  {
    PrintWriter out = res.getWriter();

    out.println("Basic servlet example");
    out.close();
  }
}

Here we have created MyServlet class which extends GenericServlet. we have overrided here service method.Now write the servlet mapping to web.xml (deployment descripter) file  like below-

<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <display-name>Basic Servlet Application</display-name>
    <description>
        This is a simple web application
    </description>

    <servlet>
        <servlet-name>MyServletClass</servlet-name>
        <servlet-class>examples.MyServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>MyServletClass</servlet-name>
        <url-pattern>/myservlet</url-pattern>
    </servlet-mapping>

</web-app> 

web.xml deployment descriptor file, the <servlet> XML element declares the MyServlet, the examples.MyServlet Java class implements the servlet, and the <servlet-mapping> XML element specifies the /myservlet URL pattern that invokes the servlet in a browser.

Now put application in server and start the server.

URL will be  http://localhost:8080/mywewapp/myservlet invoked from browser. If this is first request then init() method calls first then service() method later. But if this is second request then directly service() method will be call.

service() method has two parameter ServletRequest and ServletResponse. One ServletRequest and one ServletResponse Object is always created per request and response. When request reached to the servlet it gives the ServletRequest Object to service() method This ServletRequest Object contains all the detail about request e.g. remotehost, remoteport, scheme, request parameter, header.This service() method is uses, value from ServletRequest to execute business logic and put response to the second parameter of service() method. This response is later given to the browser. Browser read and render  response object.

To go next chapter click here

No comments:

Post a Comment