Introduction to Java Servlets

Java Servlets are server side Java programs that require either a Web Server or an Application Server for execution

Introduction to Java Servlets

     

Java Servlets are server side Java programs that require either a Web Server or an Application Server for execution. Examples for Web Servers include Apache?s Tomcat Server and Macromedia?s JRun. Web Servers include IBM?s Weblogic and BEA?s Websphere server. Examples for other Server programs include Java Server Pages (JSPs) and Enterprise Java Beans (EJBs). In the forthcoming sections, we will get acquainted with Servlet fundamentals and other associated information required for creating and executing Java Servlets.

  1. Basic Servlet Structure
      

    As seen earlier, Java servlets are server side programs or to be more specific; web applications that run on servers that comply HTTP protocol. The javax.servlet and javax.servlet.http packages provide the necessary interfaces and classes to work with servlets. Servlets generally extend the HttpServlet class and override the doGet or the doPost methods. In addition, other methods such as init, service and destroy also called as life cycle methods might be used which will be discussed in the following section. The skeleton of a servlet is given in Figure

 



  1. A Servlet?s Life Cycle
    The first time a servlet is invoked, it is the init method which is called. And remember that this is called only once during the lifetime of a servlet. So, you can put all your initialization code here. This method next calls the service method. The service method in turn calls the doGet or doPost methods (whichever the user has overridden). Finally, the servlet calls the destroy method. It is in a sense equivalent to the finally method. You can reset or close references / connections done earlier in the servlet?s methods (e.g. init, service or doGet /doPost). After this method is called, the servlet ceases to exist for all practical purposes. However, please note that it is not mandatory to override all these methods. More often than not, it is the doGet or doPost method used with one or more of the other life cycle methods.



  2. A Servlet Program


      



    Output Screens

    To appreciate the execution of the servlet life cycle methods, keep refreshing the browser (F5 in Windows). In the background, what actually happens is ? with each refresh, the doGet method is called which increments i?s value and displays the current value. Find below the screen shots (Figures 5 through 7) captured at random intervals. The procedure to run the servlets using a Web Server will be demonstrated in the next section (1.3.). 








Ads