First Step Towards Servlet Programming

Servlet is an API used to develop web based Application. The following are the important packages available in servlet API. 
  • javax.servlet
  • javax.servlet.http
  • javax.servlet.annotation (Available from servlets 3.0 onwards)


The following are the most important Interfaces and classes in each package
Interfaces and classes of Servlet package
Fig1: Important Classes and Interfaces of Servlet API
Servlet: A servlet is a java program which provides the implementation of Servlet Interface directly or Indirectly.

Procedure to Develop a Servlet Program: 
Step 1: Develop a class which provides the implementation of the Servlet interface. The following figure shows you the servlet program, which implements servlet interface.
 
Servlet program
Fig: FirstServlet program

Step 2: We have to compile the servlet program. To compile we need to set the classpath to the jar file which provides the implementation of Servlet API. The name of the jar file which provides the implementation varies from server to server. In case of Tomcat, we use "Servlet-api.jar".
Step 3: Every Servlet must be configured in the project.
  1. Copy the .class file into classes folder of WEB-INF.
  2. Configure the servlet into web.xml file. The following is the web.xml file for the above FirstServlet program.
web.xml file
Deployment Descriptor

Step 4: Deploy the project. (place the project in to tomcat server (webapps) )
Step 5: Use the following URL to execute the servlet 

  • http://localhost:8080/webapps/<url-pattern>(given in web.xml file)

            Whenever we deploy a project, Server searches for web.xml file and store it in JVM's Memory. When the client sends the request(in the form of HTTP Request Format) to server, the server receives the request and creates two objects Request and Response. Now the server opens HTTP Request Format, read the data and store it in Request object. Then the server creates the servlet object. After creating Servlet object the server supply Request and Response objects as parameters to service() method. Service method returns the data to Response object. Now the server opens the Response object, read the data and sends the response to the client in the form of HTTP Response Format. Now the server deletes Request and Response objects.   

                         

No comments:

Post a Comment