Servlets

Servlets are the server-side version of an applet: a small piece of Java code that is loaded by a Web server and used to deal with client requests, much like CGI. Sun Microsystems is aiming to make servlets the new Web server programming paradigm. Servlets are persistent, platform independent, and incorporate all sorts of advanced features including security, easy database access, and much easier integration with Java applets.

Java Servlets are a standard JDK 1.2 extension to JDK 1.1.x. Java Servlet API enables the creation of Java Servlets. Servlets are a means of extending the functionality of servers. For example, servlets can extend a web server's functionality in the same way that CGI scripts do. Servlets, however, are much less resource intensive than CGI scripts. Because servlets are written entirely in Java, again unlike CGI scripts, they are cross-platform as well. JBuilder provides a Servlet Wizard to simplify the creation of servlets. For a tutorial using the Servlet Wizard to create a servlet, see tutorial.

Visit http://www.borland.com/techpubs/jbuilder/ for updates to this topic.

Visit http://www.borland.com/jbuilder/ for a white paper on using servlets in JBuilder.

A Servlet Tutorial is located on the JavaSoft web site at http://www.javasoft.com/products/jdk/1.2/docs/ext/servlet/servlet_tutorial.html.

A Java Servlet Reference Guide with links to sites of interest in the servlet world is located at http://webreview.com/97/10/10/feature/guide.html.

Creating a servlet in JBuilder

In the Client/Server and Professional editions, JBuilder provides a Servlet Wizard for creating a Java file that extends javax.HTTPServlet. There are several kinds of servlets. The JBuilder Servlet Wizard handles the following kinds:

To develop with servlets,

  1. Download the Sun Java Developer's Kit (JDK) 1.2 from http://www.javasoft.com/products/jdk/1.2/index.html.

  2. In JBuilder's Navigation pane, select the project (.jpr) file. To create a new project in JBuilder,

    1. Select File|Close all from the JBuilder menu.
    2. Select File|New Project.
    3. Accept all defaults.

  3. Select File|Project Properties from the JBuilder menu. On the Paths tab, set the Target JDK version to JDK 1.2. If it does not show on the list, click the Define button, then click the New button, and browse to the location of the JAVA.EXE file.

    The Class Path options will automatically show the location of the CLASSES.ZIP file. Click the Browse (...) button, then click Add Zip/JAR to also add the file SERVLET.JAR (located in the \lib\ext\ directory of the JDK 1.2 installation).

  4. Start the JBuilder Servlet Wizard by selecting File|New and then double-clicking the Servlet icon.

  5. If all defaults are accepted, a file named Servlet1.java and Servlet1.html will be added to your project. For a description of the options available in the Servlet wizard, see Servlet wizard.

    The generated, default Servlet1.java file that defines the servlet looks like this:


    package untitled1;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    
    public class Servlet1 extends HttpServlet {
      //Initialize global variables
      public void init(ServletConfig config) throws ServletException{
        super.init(config);
      }
      //Process the HTTP Post request
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("text/html");
        PrintStream out = new PrintStream (response.getOutputStream());
        out.println("<html>");
        out.println("<head><title>Servlet1</title></head>");
        out.println("<body>");
        out.println("</body></html>");
      }
      //Get Servlet information
      public String getServletInfo() {
        return "untitled1.Servlet1 Information";
      }
    }
    

    The generated file Servlet1.html, that will launch the servlet looks like this:


    <HTML>
    <HEAD>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
    <TITLE>
    Servlet1
    </TITLE>
    <BODY>
    
    <FORM  action=http://yourServerUrl//servelet/untitled1.Servlet1 method=POST>
    <BR><BR> press Submit to launch servlet Servlet1
    <BR><BR><input type=submit><input type=reset></form>
    </BODY>
    </HTML>
    

  6. Add functionality to the Servlet1.java file.

  7. Compile the application in JBuilder by selecting Build|Make Project.

  8. You can exit JBuilder at this point.

The servlet runs from inside a Web Server program. Web Servers take HTML pages as their input/ouput. After you have compiled the servlet, you can test and/or debug the servlet by using the Deployment Wizard to bundle up the servlet or by copying the classes to your Web Server to test the servlet. You must deploy the servlet onto your Web Server in order to test it. You can download an evaluation copy of the Java Web Server from http://jserv.javasoft.com/products/webserver/index.html.

Launch the servlet by viewing Servlet1.html file in a Web browser and clicking the Submit button.

Tutorial: Creating and running a servlet

This tutorial shows how to create a basic servlet. To develop and deploy servlets, you will need to run a servlet-enabled Web server and use Java Development Kit 1.2, both of which can be downloaded from JavaSoft.

To demonstrate how to develop a Java servlet, we will build a fairly basic "Hello World"-type application that illustrates the general servlet framework. This first servlet will display a welcome message, the user's name, and the number of connections since the servlet was started.

All servlets are built by extending a basic Servlet class and defining Java methods to deal with incoming connections. This sample servlet will extend the HttpServlet class that understands the Web's HTTP protocol and handles most of the underlying "plumbing" required for a Web application.

To build firstServlet, we extend the base HttpServlet class and define a method to output several lines of HTML, including the user's name.

To develop the sample "Hello World" servlet in JBuilder,

  1. Download the Sun Java Developer's Kit (JDK) 1.2 from http://www.javasoft.com/products/jdk/1.2/index.html.

  2. In JBuilder's Navigation pane, select the project (.jpr) file. To create a new project in JBuilder,

    1. Select File|Close all from the JBuilder menu.
    2. Select File|New Project.
    3. Click the Browse button and enter firstServlet in the File Name field.
    4. Click Save.
    5. Click Finish.

  3. Select File|Project Properties from the JBuilder menu. On the Paths tab, set the Target JDK version to JDK 1.2. If it does not show on the list, click the Define button, then click the New button, and browse to the location of the JAVA.EXE file.

    The Class Path options will automatically show the location of the CLASSES.ZIP file. Click the Browse (...) button, then click Add Zip/JAR to also add the file SERVLET.JAR (located in the \lib\ext\ directory of the JDK 1.2 installation).

  4. Start the JBuilder Servlet Wizard by selecting File|New and then double-clicking the Servlet icon.

  5. Under Servlet Style, check Generate HTML Page. Under Servlet Methods, make sure that Generate Service() Method is the only servlet method selected.

    Enter firstServlet in the Class field. Click Finish. Files named firstServlet.java and firstServlet.shtml will be added to your project.

    If the generated servlet handles doPost() or doGet() methods, an HTML form is generated, otherwise a servlet tag is put in the the HTML and the file is labeled with the SHTML extension. These files need the SHTML extension to be processed correctly by the Web server. In this example, the service() method is generated, so the file is labeled with the SHTML extension.

  6. Add functionality to the firstServlet.java file so that it appears as follows. Use Alt+Z to enlarge the Source window, if necessary.
    package firstServlet;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    
    public class firstServlet extends HttpServlet {
    //Initialize global variables
      
      public void init(ServletConfig config) throws ServletException {
        super.init(config);
        connections = 0;
      }
    //Service the request
      
      public void service(HttpServletRequest request, HttpServletResponse response) 
    	throws ServletException, IOException {
    
        //Get Servlet information
        //Get a channel to the Web browser,
        //so we can send output
    
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("text/html");
    
        //Required for HTTP
    
        out.println("<HTML><HEAD><TITLE>Servlets Tutorial</TITLE></HEAD>");
        out.print("Hello World - my first Java Servlet Program, ");
        out.println(request.getParameter("userName"));
        out.print("<P>You are visitor number ");
        connections++;
        out.println(Integer.toString(connections));
    
        //Close the output stream
        out.close();
        }
        int connections;
       
      public String getServletInfo() {
        return "firstServlet.firstServlet Information";
      }
    }
    

Once we create the Java code, we have to compile it and place the resulting file on the Web server. Compile the application in JBuilder by right-clicking firstServlet.java in the Navigation pane, then selecting Make.

Files called firstServlet.class and firstServlet.dependency are generated in the directory specified in File|Project Properties Output Root Directory field.

Deploying the servlet onto a Web server

The servlet runs from inside a Web Server program. Web Servers take HTML pages as their input/ouput. After you have compiled the servlet, you can test and/or debug the servlet by using the Deployment Wizard to bundle up the servlet or by copying the classes to your Web Server to test the servlet. You must deploy the servlet onto your Web Server in order to test it.

The first servlet-enabled Web server was JavaSoft's Jeeves, now renamed Java Web Server (JWS). A number of additional server developers have adopted the standard. The latest version of the World Wide Web Consortium's free JigSaw Web Server has servlet support, as does O'Reilly WebSite Pro v2.0. For those running Netscape servers, IIS, Apache and others, JavaSoft distributes the Java Servlet Developers Kit, which allows most standard Web servers to load servlets. Finally, the IBM has released a tool called ServletExpress that makes servlets easier to manage on Web servers lacking native Java support.

To deploy a servlet onto a Web server,

  1. If you do not have a Web server, download an evaluation copy of the Java Web Server from java.sun.com/javastore/jserv/buy_try.html. See the document titled "Installation and Startup" at http://jserv.javasoft.com/products/java-server/documentation/webserver1.1/installation.html for installation instructions.

    Two items of importance are:

  2. If you are using Java Web Server, you can install the sample servlet by copying the generated class file firstServlet.class into your servlets/ directory. For other servers, check for their specific installation procedures.

  3. To test the servlet, open your Web browser, and enter this URL: http://localhost:8080/servlet/firstServlet?userName=John, where localhost is the name of your computer and :8080 is the location assigned to the external port.

    The path in this example assumes that you are running the default Java Web Server installation. (The lack of a trailing s on "servlet" is not a misprint: the directory is called "servlets" and the URL calls for "servlet").  In this example, we are simulating the submission of a FORM to the server with a variable "userName" by passing this variable in the URL.

  4. To test this servlet on the Web Review server, enter your name below and click the submit button:

    Your name: 

In this example, a form is presented asking for you to enter your name. When you click the submit button, your submission is sent to the servlet, and the servlet returns its output to your browser.

Picking The Servlet Apart

The HTTPServlet class defines methods to handle different kinds of HTTP connections. The developer defines two methods to provide customized content, init() and service().

HttpServlet.init(ServletConfig conf) is executed the first time the servlet loads. Any resources created here (assuming that they are visible to the entire class, like the connections variable) will be accessible to every single servlet invocation. So this is where global variables are created, as well as any resources that do not depend on the individual page request. In this (simplified) example, a variable is initialized to keep track of how many requests have been made for that page.

HttpServlet.service(HttpServletRequest, HttpServletResponse) takes two parameters, the HttpServletRequest and the HttpServletResponse. These are Java objects that exchange information between the servlet and the server, much like the AppletContext object in applets.  In this example, HttpServletResponse obtains a ServletOutputStream, which allows the contents to be sent back to the Web browser. In standard CGI, the program would write to standard output.

The three ServletOutputStream methods used are:

The setContentType(String) method is used to tell the browser what type of content it should expect to receive. Normally, this will be "text/html". For reliable operation, this should come before any actual output.

HttpServletRequest includes all the information provided to the servlet by the browser and the Web server (environment information, HTTP variables, form variables and so forth). The HttpServlet.getParameterName(String) method is used to read CGI form variables. In this case, the servlet was passed a variable named "userName" with a value of "John", and the command request.getParameter("userName") will return a String variable containing the text "John".

Other sample servlets

For other sample servlets, link to http://jserv.javasoft.com:80/products/java-server/documentation/webserver1.0.2/servlets/sample.html, the JavaServer Product Group page with samples for the following applications:

To see what these servlets do, download a copy of the JavaServer (with documentation), run it, and enter a URL of the form: http://server_host_name/system/doc/sample.html.