[ Team LiB ] Previous Section Next Section

Writing Simple Servlets

At this time, we've learned enough to write a simple servlet. As mentioned earlier, the most popular servlet implementation is based on HTTP protocol, and we'll use this servlet type to write our first servlet. At this point, we won't go into details about the Servlet interface or the different auxiliary objects and interfaces available for the servlet developer to implement a servlet. We'll stick to the methods we've covered so far as part of the servlet life cycle.

Servlets could very well be used for other purposes, such as FTP, SMTP, and so on. These servers could be implemented using the protocol-independent GenericServlet or by directly implementing the Servlet interface. But the most important use of servlets is for handling HTTP requests in Web and application servers. Generic Servlets and custom implementation of the Servlet interface are very rarely done.

First Servlet

The simple servlet takes a string as input, converts it to uppercase letters, and prints it on the browser. Listing 14.1 lists the complete servlet.

Listing 14.1 Simple Servlet
package wlsunleashed.servlets;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SimpleServlet extends HttpServlet
     private String defaultString="HELLO WORLD";

     public void service(HttpServletRequest req, HttpServletResponse res)
        throws IOException

         String convertedString, inputString;

        //read the request parameter INPUT_STRING
       // If the input String is null
       // it returns "hello world" In uppercase

        if ((inputString = req.getParameter("INPUT_STRING"))
            != null) {
            convertedString = inputString.toUpperCase();
        else {
            convertedString =defaultString.toUpperCase() ;

        // Set the content type first

        // get the PrintWriter
        PrintWriter out = res.getWriter();


        out.println("The input string upper case(d):" + convertedString );

Anatomy of the Simple Servlet

The anatomy covers all the sections of the simple servlet from the package imports to the output of the converted string.

Package Imports

The package imports needed for the basic servlet are the following:

  • javax.servlet— Defines among other classes; the core of the servlet API–servlet interface

  • javax.servlet.http— Defines the classes related to the HTTP protocol

  • java.io— Imports IOException, which is thrown in the service-processing methods

The Servlet Class

The SimpleServlet class is derived from the base class HttpServlet. In this servlet, the service method is used to handle the different kinds of HTTP requests. We'll go over that later in the chapter. All methods except the service method are default implementations defined in the HttpServlet.

Service Method

The service method in this servlet does all the processing; that is, it reads the input string given by the user, converts the string to uppercase letters, and flushes the output to the user output stream (that is usually the user browser).

Configuring the Simple Servlet

The last thing we have to know to use this servlet is about configuring this servlet. This is a basic servlet with no fancy requirements. Listing 14.2 gives the complete listing of the web.xml file for the simple servlet. The basic elements for configuring a servlet are the servlet and servlet mapping elements.

Listing 14.2 Web Application Descriptor (web.xml)
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http:/
      <param-value>Hello World</param-value>
Using the Init Method

As explained earlier, the init method can be used for reading any configuration parameters defined in the deployment descriptor. In the SimpleServlet, an init parameter can be used to read the default string to display on the user screen if the input string isn't given. By doing this, we can eliminate the need to hard-code a default value inside the code. The following code snippet implements the init method required for the simple servlet implementation:

public void init(ServletConfig config) throws ServletException

        // Check for all initialization parameters
        //Read the INPUT_STRING parameter.

        if ((defaultString= getInitParameter("DEFAULT_STRING")) == null)
            defaultString = "Hello World";


The init parameter DEFAULT_STRING read in the method is defined in the Web deployment descriptor, web.xml. We've already declared DEFAULT_STRING previously, refer to Listing 14.2.

Executing the Simple Servlet

Servlets in WebLogic Server can be accessed from a Web browser using the following URL format:



  • host is the machine name where the WebLogic Server instance is running.

  • port is the port number where the WebLogic Server is listening for requests. By default, this is port 7001.

  • webApplicationName is the name of the Web application where the accessed servlet is bundled.

  • mappedServletName is the logical name given for the accessed servlet in the Web deployment descriptor.

All strings following the ? represent the input for the accessed servlet. If the earlier rule is translated to access the SimpleServlet described earlier, the URL will look like the following:


Alternatively, the input can be obtained using form-based input designed using HTML. Listing 14.3 gives an idea of how this HTML will look like for our simple example.

Listing 14.3 Input Form (simple.html)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<H1 ALIGN="CENTER">A Sample FORM using POST</H1>
<FORM ACTION="/wlsUnleashed/SimpleServlet" METHOD="POST">

The HTML file is to be placed under the root directory of the Web application. The directory structure was covered in detail in Chapters 5, "Enterprise Application Design with WebLogic Server," and 6, "Introduction to WebLogic Web Applications." The HTML has to be invoked in the same fashion as that used with the simple servlet shown earlier.


Figure 14.2 displays the output from the SimpleServlet. You can note the link used to access the simple servlet in the address bar of the Web browser.

Figure 14.2. Simple servlet output.


    [ Team LiB ] Previous Section Next Section