Developing servlets

Note: This is a feature of JBuilder Professional and Enterprise.

JavaTM Servlets provide web developers with a simple, consistent mechanism for extending the functionality of a web server and for accessing existing business systems. A servlet can almost be thought of as an applet that runs on the server side -- without a face. Java Servlets have made many web applications possible.

Servlets are the Java platform technology of choice for extending and enhancing Web servers. Servlets provide a component-based, platform-independent method for building web-based applications, without the performance limitations of CGI programs. And unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), Servlets are server- and platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools.

Written in Java, Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets also access library of HTTP-specific calls, and all the benefits of the mature Java language, including portability, performance, reusability, and crash protection.

Today, Servlets are a popular choice for building interactive web applications. Third-party Servlet containers are available for Apache Web Server, iPlanet Web Server (formerly Netscape Enterprise Server), Microsoft IIS, and others. Servlet containers can also be integrated with web-enabled application servers, such as BEA WebLogic Application Server, IBM WebSphere, Netscape Application Server, and others.

You might want to check out the latest information on JavaServer PagesTM (JSP). JSP technology is an extension of the servlet technology created to support authoring of HTML and XML pages. It makes it easier to combine fixed or static template data with dynamic content. Even if you're comfortable writing servlets, there are several compelling reasons to investigate JSP technology as a complement to your existing work. For more information on writing JSPs, see "Developing JavaServer Pages (JSP)".

For more information on all things Servlet, visit Sun's Java software site at http://java.sun.com/products/servlet/index.html.

JBuilder provides several methods for developing servlets.

Other Servlet tutorials are located on the Sun Microsystems Web site at http://jserv.java.sun.com/products/java-server/documentation/webserver1.1/servlets/servlet_tutorial.html.

Using the default Web server

Sun Microsystems has delivered the latest versions of JavaServer PagesTM (JSP) and Servlets source code to the Apache Software Foundation http://www.apache.org to be developed and released under the Apache development process as the official JSP 1.1/Servlets 2.2 reference implementation. Apache, Sun, and a variety of other companies and individuals are openly developing a robust Reference Implementation that is freely available to any company or individual. This reference implementation, developed under the project name Jakarta and code-named Tomcat, will be the only reference implementation available. This implementation is available to any company or developer to be used in Web servers, development tools, and to create dynamic, interactive Web sites. JBuilder delivers Tomcat "in the box" to use as your Web server so that you can successfully develop and test your JSPs and Servlets within the JBuilder development environment.

Overview: Creating a servlet using the Servlet wizard

In JBuilder Professional and Enterprise, you can use the Servlet wizard to create a Java file that extends javax.HTTPServlet. The JBuilder Servlet wizard generates servlets of the following content type:

The following steps provide an outline of steps necessary to develop the different types of servlets. For a tutorial that creates a simple HTML servlet, see "Tutorial: Creating a servlet using the Servlet wizard."

  1. If you want to develop a servlet within an existing project, select the project (.jpx) file in the project pane. Otherwise, create a new project in JBuilder,
    1. Select File|Close Project from the JBuilder menu.
    2. Select File|New Project.
    3. Enter the project name and directory.
    4. Optionally, enter the Title, Author, Company, and Description fields.
    5. Click Finish.

  2. If you have a Web server, you can set project properties so that files are copied to the correct locations for deployment, and so that the servlet can be more easily debugged. Refer to your Web server documentation for the specifics of where to generate the files. To set the locations,
    1. Select Project|Project Properties.
    2. Select the Paths tab.
    3. Set the appropriate Output Path.
    4. Close the dialog by selecting OK.

  3. Start the JBuilder Servlet wizard by selecting File|New and then double-clicking the Servlet icon from the New tab of the Object Gallery. The Servlet wizard appears,

    If all defaults are accepted, files named Servlet1.java and Servlet1.shtml will be added to your project. The Enable Web Run/Debug From Context Menu option is automatically set for the Servlet1.java file to enable you to run the servlet independent of the SHTML file. For a description of the options available in the Servlet wizard, see Servlet wizard options.

    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 {
      private static final String CONTENT_TYPE = "text/html";
    
      /**Initialize global variables*/
      public void init(ServletConfig config) throws 
         ServletException {
        super.init(config);
      }
    
      /**Process the HTTP Get request*/
      public void doGet(HttpServletRequest request, 
         HttpServletResponse response) throws 
            ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<font color=\"green\">");
        out.println("<p>The servlet has received a GET. This is 
           the reply.</p>");
        out.println("</font>");
      }
    }
    

    The generated file Servlet1.shtml, that can also launch the servlet looks like this:
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;
       charset=windows-1252" />
    <title>
    Servlet1
    </title>
    </head>
    <body>
    
    <p>launches servlet Servlet1</p>
    <servlet
      codebase=""
      code="untitled1.Servlet1.class"
    >
    </servlet>
    <p><a href="/servlet/untitled1.Servlet1">
       Click here to call Servlet: Servlet1</a></p>
    </body>
    </html>
    

  4. Add functionality to the Servlet1.java file. For example, the simple servlet tutorial in this chapter adds code to count the number of visitors to a site.

  5. Compile the servlet. To compile the servlet, right-click Servlet1.java, and select Make. Compilation errors are displayed in the lower pane.

    To debug servlets, set a breakpoint, and then choose Debug from the context menu. This starts the Servlet engine, in this case Tomcat, in debug mode, configured so that it can see the project's HTML and servlets, and switches the IDE into a Web View browser so that you can see the output.

  6. Test the servlet. To do this, right-click the Servlet1.java file, select Web Run.

    The program runs: two new tabs appear in the content pane for the servlet: Web View and Web View Source. These tabs display the output from the running servlet in raw HTML and in parsed HTML. If you made no modifications to the Servlet wizard, clicking the link sends a GET request to the servlet, and the reply appears in the Web View browser.

  7. Deploy the servlet. Deploying the servlet is discussed in more detail in "Deploying servlets".

Servlet wizard options

When you select File|New, then select Servlet from the New page of the Object Gallery, the Servlet wizard appears to make the creation, debugging, and testing of servlets easy!

Servlet wizard - Step 1

Servlet wizard - Step 1

On the first page of the Servlet wizard, you can enter the Package to which you want the servlet to belong, and name the servlet in the Class field. In the first step of the Servlet wizard, the Generate Content Type and Implement Methods fields require further discussion.

Generate Content Type

The options for Generate Content Type include:

Implement methods

This option of the Servlet wizard provides options for overriding the standard servlet methods. HttpServlet provides an abstract class that you can subclass to create an HTTP servlet, which receives requests from and sends responses to a Web iste. When you subclass HttpServlet, you must override at least one method, usually one of these. For more information on the methods, refer to the Servlet documentation at http://java.sun.com/products/servlet/index.html. The methods generated when HTML is the content type look like this:

Servlet wizard - Step 2

Servlet wizard - Step 2

The second step of the Servlet wizard is the SHTML file details page if you selected either HTML or XHTML from the Generate Content Type option. With JBuilder and the Tomcat servlet engine, you can run a servlet directly from the Servlet1.java file. When the servlet is created using the Servlet wizard, the Java properties option to Enable Web Run/Debug From Context Menu is turned off (to see this, right-click on the Java file, and select Properties from the context menu). If you want to run the servlet directly, as described in "Invoking a servlet from a browser window," unselect the Generate SHTML File option here.

If you want to call the servlet from an HTML page, as described in "Calling servlets from an HTML page," leave this option selected. An SHTML file, such as that shown in "Overview: Creating a servlet using the Servlet wizard," with the same name as the servlet, is added to the project when this option is selected.

Servlet wizard - Step 3

Servlet wizard - Step 3

When HTML or XHTML are the content types, this is Step 3. If WML or XML are selected, this is Step 2. This page allows you to enter servlet parameters. For example, in the servlet tutorial, "Tutorial: Creating a servlet using the Servlet wizard," a parameter of type String is created to allow entry of the user's name. Servlet URLs can take the parameter as a query, for example, the simple servlet created in the tutorial can be run by entering the following URL for the servlet:

http://localhost:8080/servlet/firstServlet.firstServlet?userName=Honey

Running servlets

The following topics discuss a few ways to invoke servlets:

Each option is discussed in more detail in the following sections.

Invoking a servlet from a browser window

Servlets can be called directly by typing their URL into a browser's location window. The general form of a servlet URL, where servlet-file-name corresponds to the name you have given the servlet, is:

http://machine-name:port-number/servlet/servlet-file-name 

For example, an URL in the format of any of the following examples should enable you to run the servlet:

Servlet URLs can contain queries, such as for HTTP GET requests. For example, the servlet in the tutorial takes the user name as a query. The servlet's name is firstServlet; the URL for the servlet to get and display the user name is:

http://localhost:8080/servlet/firstServlet.firstServlet?userName=John

Calling servlets from an HTML page

To invoke a servlet from within an HTML page just use the servlet URL in the appropriate HTML tag. Tags that take URLs include those that begin anchors and forms, and meta tags. Servlet URLs can be used in HTML tags anywhere a normal URL can be used, such as the destination of an anchor, as the action in a form, and as the location to be used when a META tag directs that a page be refreshed. This section assumes knowledge of HTML. If you don't know HTML you can learn about it through various books or by looking at the HTML 3.2 Reference Specification on the Web at http://www.w3c.org/TR/REC-html32.html.

For example, in the default servlet created in the overview section in this chapter, the SHTML page contains an anchor with a servlet as a destination:

<a href="/servlet/untitled1.Servlet1">Click here to call Servlet: Servlet1</a><BR>

The HTML pages also regularly use the following tags to invoke servlets:

Calling servlets from servlets

To have your servlet call another servlet,

This section addresses the second option. To call another servlet's public methods directly, you must:

To gain access to the Servlet object, use the ServletContext object's getServlet method. Get the ServletContext object from the ServletConfig object stored in the Servlet object.

Once you have the servlet object, you can call any of that servlet's public methods.

You must exercise caution when you call another servlet's methods. If the servlet that you want to call implements the SingleThreadModel interface, your call could violate the called servlet's single threaded nature. (The server has no way to intervene and make sure your call happens when the servlet is not interacting with another client.) In this case, your servlet should make an HTTP request of the other servlet instead of calling the other servlet's methods directly.

Tutorial: Creating a servlet using the Servlet wizard

This tutorial shows how to create a basic servlet. You can develop and test servlets within JBuilder using the Tomcat servlet engine shipped "inside" JBuilder. To deploy servlets, you will need to run a servlet-enabled Web server, such as the Java Web Server. As of this writing, you can get a trial version from the JavaSoft web site at http://www.sun.com/software/jwebserver/try/index.html.

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. Create a new project in JBuilder. To do this,
    1. Select File|Close from the JBuilder menu if any other projects are open.
    2. Select File|New, and then double-click the Servlet icon from the New tab of the Object Gallery.
    3. The Project wizard displays first. Change the Project Name and Project Directory Name to SampleServlet.
    4. Click Finish.

      The Servlet wizard starts.

  2. Create a new servlet by setting the following options:
    1. Enter firstServlet in the Class field.
    2. Select the doPost() method (the doGet() method should already be selected).
    3. Click Next.
    4. Leave the SHTML file details at their defaults. Click Next.
    5. Create a new Servlet Parameter by clicking the Add Parameter button. Adding this parameter here generates a text entry field in the SHTML file for the user to enter their name. Enter the following information:

      Name* UserName
      Type* String
      Desc Name of User
      Variable* userName
      Default Hey You

    6. Click Finish. Files named firstServlet.java and firstServlet.shtml are added to the project. The Servlet library is added to the Project Properties.

  3. Add functionality to the firstServlet.java file so that it appears as follows. Code to be entered appears in bold.
    package firstservlet;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    
    public class firstServlet extends HttpServlet {
      private static final String CONTENT_TYPE = "text/html";
    
      /**Initialize global variables*/
      int connections;
      public void init(ServletConfig config) throws ServletException {
        super.init(config);
        connections=0;
      }
    
      /**Process the HTTP Get request*/
      public void doGet(HttpServletRequest request, HttpServletResponse
      	  response) throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<font color=\"green\">");
        out.println("<p>The servlet has received a GET. This is
    	  the reply.</p>");
        out.println("</font>");
      }
    
      /**Process the HTTP Post request*/
      public void doPost(HttpServletRequest request, HttpServletResponse
      	  response) throws ServletException, IOException {
        //Name of User
        String userName = "Hey you";
        try {
          userName = request.getParameter("UserName");
        }
        catch(Exception e) {
          e.printStackTrace();
        }
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>firstServlet
    	   </title></head>");
        out.println("<body>");
        out.println("<p>The servlet has received a POST. 
    	   This is the reply.</p>");
        out.println("<p>Thanks for visiting, ");
        out.println(request.getParameter("UserName"));
        out.println("<P>");
        out.println("Hello World - my first Java Servlets program!");
        out.println("<P>You are visitor number ");
        connections++;
        out.println(Integer.toString(connections));
        out.println("</body></html>");
      }
    }
    


Compiling the servlet

To compile the servlet, first set the runtime properties. To do this,

  1. Select Project|Project Properties. Select the Run tab. Select the JSP/Servlet tab.

  2. Select the Set button. Browse to the SHTML file created for this project.

  3. Change any properties of the Web server. The port number is the port on which the Web server will run. The default is 8080. If port 8080 is used, by default JBuilder will search for an unused port.

  4. Select OK until the dialog closes.

To compile and debug the servlet,

  1. Right-click firstServlet.shtml.
  2. Select Make.

The project compiles. Compilation errors are displayed in the lower pane.

Testing the servlet

To run the servlet,

  1. Right-click firstServlet.shtml.
  2. Select Web Run.
Note: You can also run servlets directly by right-clicking the JAVA file in the project pane, and selecting Web Run. In this example, we are running the servlet from the SHTML file because that is where the parameter input fields and Submit button are coded, based on our selections in the Servlet wizard.

Running the servlet starts Tomcat, the reference implementation of Servlet 2.2/JSP 1.1, done by the Apache Software Foundation, as part of its Jakarta project. Using Tomcat, you can run and debug servlets and JSP's. The output from Tomcat will appear on a new output pane in the lower part of the JBuilder IDE. Output from servlets or beans will be seen in this output pane. HTTP commands and parameter values are also echoed to the output pane.

Two new tabs appear in the content pane for the servlet: Web View and Web View Source. The running servlets displays in the Web View browser, looking like this:

Servlet running in the Web View browser

The Web View tab of the content pane displays the servlet after it has been processed by the JSP engine. The Web View pane will behave differently than the View pane. In the Web View pane, there may be a delay between when the JSP file is edited, and when the change is shown in the Web View pane. To see the most recent changes to an SHTML file, select the reset button, just as you would in any Web browser.

The servlet URL displays in the Web View browser. Now that the Web server, Tomcat, is launched, it displays as a tab below the message pane. To stop the Web server, click the red square directly above the tab. You must stop the Web browser in order to re-run the servlet after you make changes.

Enter a name in the text box, then click the Submit button. The doPost() method is called, and the response is displayed in the Web View browser, as shown below.

Servlet running after name submitted

When developing servlets with JBuilder, you have a number of other options for servlet testing and deployment, including

Deploying servlets

To deploy a servlet onto a Web server, see the documentation for your Web server.

Once you have deployed your application, you can run the client and server on either the same machine or on different machines in the same subnet.

Internationalizing servlets

Servlets present an interesting internationalization problem. Since the servlet outputs HTML source to the client, if that HTML contains characters that are not in the character set supported by the server on which the servlet is running, the characters may not be readable on the client's browser. For example, if the server's encoding is set to ISO-8859-1, but the HTML written out by the servlet contains double-byte characters, those characters will not appear correctly on the client's browser, even if the browser is set correctly to view them.

By specifying an encoding in the servlet, the servlet can be deployed on any server without having to know that server's encoding setting. Servlet's can also respond to user input and write out HTML for a selected language.

The following is example of how to specify the encoding setting in a servlet. In the Java source generated by the Servlet wizard, the doPost() method contains the following line:

PrintWriter out = new PrintWriter(response.getOutputStream());

This line can be replaced with:

OutputStreamWriter writer = new OutputStreamWriter(
	response.getOutputStream(), "encoding");
PrintWriter out = new PrintWriter(writer);

The second argument to the OutputStreamWriter constructor is a String representing the desired encoding. This string can be resourced, hard-coded, or set by a variable. A call to System.getProperty("file.encoding") will return a String representing the system's current encoding setting.

If the OutputStreamWriter constructor is called with only the first argument, the current encoding setting will be used.

Writing a data-aware servlet

JBuilder provides two new ways to simplify creating data-aware servlets: InternetBeans Express and JSQL/XMLServlet.

InternetBeans Express is a set of components that read HTML forms and generate HTML from dbSwing data models, making it easier to create data-aware servlets and JSPs. InternetBeans Express components generate HTML and are used with Servlets and JSP's to create dynamic content. They feature specific hooks and optimizations when used in conjunction with DataExpress components, but can be used with generic Swing data models. For more information on using InternetBeans Express, including a tutorial, see "Using InternetBeans Express."

JSQL is a command line tool that lets you specify a valid SQL query using XML. XMLServlet takes a SQL query and a description of thedesired report format int he form of XML input, supports a limited XML parser capable of recognizing XML tags, and generates output to an XML-enabled browser accordingly. For more information on using this feature, see "Using XMLServlet."