Getting Started with Java Servlets using Apache JServ

In the quest for more dynamic content, web server technologies have flourished. One particular solution to provide this dynamic content is Java Servlet technology. As a replacement to the traditional CGI script approach, servlets give developers a powerful tool to create web enabled applications. Not only does the servlet solution give developers the ease of using the Java language, it is also offers a more efficient solution in terms of CPU power.

In the quest for more dynamic content, web server technologies have flourished. One particular solution to provide this dynamic content is Java Servlet technology. As a replacement to the traditional CGI script approach, servlets give developers a powerful tool to create web enabled applications. Not only does the servlet solution give developers the ease of using the Java language, it is also offers a more effecient solution in terms of CPU power.

A variety of servlet engines have been implemented to take advantage of this rapidly maturing technology. However, in the majority of these products, the sheer price of the commercial servlet engines puts this technology out of the hands of developers without the cash to front for these products.

Enter Apache, the internet’s most popular web server. The Apache group has already proven the ability of open source to produce high quality, mission critical software. The Apache-Jserv project is an open-source implementation of Suns’ servlet specification. For those of you that want to hack on this stuff at home on your linux box, to those that want to deploy servlet technology for business critical applications, Apache Jserv delivers an easily accessible, robust solution.

Some of the benefits of servlets over CGI include:

  • Faster than CGI scripts. Since the servlets are kept in memory, each request handled by a servlet doesn’t have to fork a new process as is the case with traditional CGI scripts.
  • The ability to leverage all of the advantages of the Java programming language, including platform independence.
  • The ability to use a variety of API’s available to the Java platform.
  • Session Management (Persistence)

This introductory article to servlets will review how a servlet works, and also go into detail explaining an example servlet demonstrating how one might leverage JDBC and sessions with servlets.

{mospagebreak title=How the servlet class works}

Because servlets are kept loaded in the servlet engine’s JVM, each incoming request does not need to instantiate a new servlet class. Once the servlet environment is initialized, the servlet is then loaded and the servlet’s service() method handles requests. However, you should be aware that more than one instance of your servlet can be loaded in the JVM, depending on the server load and the configuration of your servlet engine.

Each servlet must either directly or indirectly implement the javax.servlet.Servlet interface. Typically, it is most convenient to extend the javax.servlet.http.HttpServlet class and override the doGet() and/or doPost() methods. The servlet API also allows for handling other types of HTTP 1.1 requests, like DELETE, PUT, TRACE, and OPTIONS. Since these types of HTTP 1.1 requests are uncommonly used, most developers will be interested in the doGet() and doPost() methods.

Two important classes your should know about are HttpServletRequest and HttpServletResponse.

The HttpServletRequest object contains methods which let you inspect it and find information on the request type. In PERL CGI’s, a lot of these variables are found in the %ENV associative array; things like METHOD (getMethod()), REMOTE_ADDR (getRemoteAddr), CONTENT_LENGTH (getContentLength()), etc. Data passed to the servlet in forms is automatically parsed from the QUERY_STRING or what’s received from a POST request. These form variables are accessed by the getParameter(String name) method, where the name is the name of the variable set in the HTML form.

The HttpServletResponse‘s most popular method would probably be its getWriter() method. This returns a PrintWriter to which you can println() output. If you servlet is going to be returning binary data, like a dynamically created gif or jpg, you would then need to use getOutputStrem() instead.

Servlet Lifecycle

  • init()

    When the servlet is first requested, it is loaded by the servlet implementation’s classloader and the servlet’s init() is called. This is where you initialize expensive resources, like database connections, for example.

  • service()

    Once the servlet’s init() method is finished executing, the servlet is now in a ‘ready’ state, waiting to handle requests. Once a request comes in to which the servlet is mapped to service, the service() method is executed.

    Depending on the HTTP 1.1 request type (typically GET or POST), the service() method then passes the request on to the doGet() method if it is a GET request, or the doPost() method if it is a POST request. Usually POST requests are used for submitting data, while GET requests are for retrieving data.

  • destroy()

    Servlet engines are not required to keep the servlets in memory. If they should decide to unload a servlet to conserve resources or for what ever other reason, the servlet’s destroy() method will be called. This allows the servlet to do things like save its current state and release resources before being unloaded.

Quick Example

Here’s a quick example of how a simple servlet works (

import javax.servlet.http.*; import javax.servlet.*; import*; public class Hello extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get an PrintWriter from the response object PrintWriter out = response.getWriter(); // prepare the response’s content type response.setContentType(“text/html”); // get the IP address of the client String remoteAddress = request.getRemoteAddr(); // print to the output stream! out.println(“Hello there, web surfer from <b>” + remoteAddress + “</b>”); } }

The servlet is invoked when a URL mapped to the servlet ( like http://[domain]/servlet/Hello ) is requested. If it is not already loaded in the JVM, the servlet engine loads the servlet and calls the init() method. Now the servlet is ‘ready’ to handle requests, and the service( HttpServletRequest, HttpServletResponse ) method is now called. The service() method inspects the request object, and passes the HttpServletRequest and HttpServletResponse objects to the appropriate handler method. In this case, this servlet is only equipped to handle GET requests. If a POST or some other HTTP 1.1 request was handled by the servlet, the client browser would get a “<METHOD> not supported by this URL” error message. The servlet finishes executing the doGet() method and then waits for another request to service.

{mospagebreak title=Installation}

Setting up Apache Jserv is a fairly involved process, which includes installing serveral different components. The Jserv team already spent some considerable effort on the INSTALL document bundled with the Apache-Jserv package, and is an excellent document to get you started on how to set up your servlet-enabled Apache web server. Furthermore, more installation help is available at the Apache Jserv web site’s Instruction and Howto’s section. The articles there go over the whole installation process, as well as the issues involved in installing Apache Jserv on *nix systems as well as Windows operating systems. Ari Halberstadt’s “Using Apache Jserv 1.0 article is particularly good for installing Apache Jserv.

To help you get started, you may want to download these following components as you’re reviewing the INSTALL file.

  1. The latest version of Apache, (as of this writing, it is 1.3.6).
  2. The Apache Jserv module:
  3. The Java Servlet SDK version 2.0:
    Make sure you get the 2.0 version JSDK; Jserv hasn’t been patched to work with JSDK 2.1 yet.
  4. Java – for linux, the Blackdown JDK works well.
    Make sure you download the package that’s appropriate for your system (ie architecture and libc libraries). For Win32 systems, you can get java from Sun at
    IBM also has a JVM for linux as well, however the license for it expires after 90 days.

{mospagebreak title=Examples}

As stated previously, one of the big benefits of using Java on the server is the ability to use any of large number of API’s available for Java. One of the more common tasks in creating a web-enabled application is to make the html pages driven from a database. The following shows a simple example of a servlet accessing a database via JDBC. The database which my sample servlet will be connecting to is MySQL, a robust open-source database which has gained popularity in web applications because of it’s reliability and blazing speed. For this example, you’ll also need a JDBC driver for MySQL. One of which can be found at

The following example shows how one might use servlet technology in a simple shopping cart application. The product catalog will be stored in the database. Items placed in the customer’s cart will be stored in the HttpSession object.

Setting up the database:

  1. First, create the database:
    $ mysqladmin create testCart
    Make sure that you have the appropriate permissions to create databases and tables in your MySQL database.
  2. Create the table and import data.
    $ mysql testCart < cart.sql

The class displays a fictional product catalog where the customer can select items to add to their “cart”. When the customer is done adding items to their cart, they can click on the “View Your Cart” link and get an itemized list of each product they selected.

The “brains” of the servlet is contained within the doGet() method. The cutomer’s shopping cart is represented by a Java Hashtable. The key of the Hashtable is the productID of the item and the value of the Hashtable entry is the quantity of the products desired.

public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Hashtable cart; PrintWriter out; HttpSession session; out = response.getWriter(); response.setContentType(“text/html”); session = request.getSession(true); String id = request.getParameter(“id”); String command = request.getParameter(“command”); String requestURI = request.getRequestURI(); cart = (Hashtable) session.getValue(“cart”); if (cart == null) { cart = new Hashtable(); } out.println(“<h1>Shopping Cart</h1>”); try { if (command.equals(“add”)) { Integer num = (Integer) cart.get(id); if (num == null) { num = new Integer(0); } cart.put(id, new Integer(num.intValue() + 1) ); printCatalog(out, requestURI); } else if (command.equals(“viewcart”)) { printCart(cart, out, requestURI); } else { printCatalog(out, requestURI); } } catch (NullPointerException e) { printCatalog(out, requestURI); } session.putValue(“cart”, cart); }

After declaring serveral objects, the the PrintWriterout” is obtained from the HttpServletResponse’s getWriter() method, as described previously. If the servlet were to return a binary file, like a dynamically created GIF or JPEG for example, you would want to use the ServletResponse’s getOutputStream() method.

The next line,

session = request.getSession(true);
initiates a session in the servlet engine where information can be stored to have a persistent state. The customer’s shopping cart, represented by the Hashtable, will be stored in the HttpSession object. The boolean parameter passed to the getSession() method tells the servlet engine to start a session if one hasn’t already been started. If the parameter passed was ‘false’, then the servlet would return the already existing session object. Otherwise, the getSession() method will return null.

String id = request.getParameter(“id”); String command = request.getParameter(“command”);
The next two lines demonstrate how to get values passed to your servlet from HTML forms. The getParameter() doesn’t differentiate if the form data was passed in a GET request or a POST request. If the form parameter doesn’t exist, the method returns null. Alternatively, you can use the ServletRequest’s getParameterNames() method to get an Enumeration of parameter names you can iterate through with the getParameter() to get all of the form names and values.

Next, the cart is instantiated.

cart = session.getValue(“cart”); if (cart == null) { cart = new Hashtable(); }
If the Hashtable cannot be retrieved from the session object with the HttpSession.getValue(String key) method, then one is instantiated as a new Hashtable.

Now comes the logic of the servlet. The default behavior of the servlet is to print display the product catalog. If the customer click’s on the “Add to Cart” hyperlink, the command “add” and the product ID of the item is passed to the servlet. The value of the Hashtable entry with the productID as the key is incremented, and the product catalog is again displayed. If the “View your Cart” hyperlink is clicked, then the “viewcart” command is passed to the servlet and the contents of the customer’s cart is displayed.

Finally, after products have been added (optionally) to the the cart Hashtable, it is put back into the session object, replacing the old cart.

The product listing and cart content listing is generated dynamically from the database.

public void init(ServletConfig config) throws ServletException { super.init(config); dbc = null; try { Class.forName(“”).newInstance(); dbc = DriverManager.getConnection(“jdbc:mysql://localhost:3306/testCart?” + “user=dbUser&password=userPasswd”); } catch (Exception e) { e.printStackTrace(); } }
In the init() method, the database connection is initialized, and will be available to the servlet for its lifetime. In the JSDK 2.0 specification, the super.init(ServletConfig) method must be the first command in the method. However, in version 2.1 of the specification, this requirement has been fixed and is no longer necessary. If you are going to be using mutltiple servlets accessing a database, a better solution would be to use a database connection pool.

try { Statement stmt = dbc.createStatement(); stmt.execute(“select * from Products”); ResultSet rs = stmt.getResultSet(); while ( { out.println(“<tr>”); out.println(“<td><b>” + rs.getString(“name”) + “</b><br>” + rs.getString(“description”) + “</td>”); out.println(“<td align=”right”>” + nf.format(rs.getDouble(“price”)) + “</td>”); out.println(“<td><a href=”” + requestURI + “?command=add&id=” + String.valueOf(rs.getInt(“productID”)) + “”>Add to Cart</a></td>”); out.println(“</tr>”); } rs.close(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
The JDBC methods called in the printCatalog() and printCart() methods are fairly straightforward; we simply create a Statement from the database connection, execute the SQL query, and then iterate through the result set.

It is important to remember to free up the resources used in your servlet, as multiple accesses can impact your server quite quickly. In the example statements and result sets are closed after every request, and the database conncection is closed inside the servlet’s destroy() method.

{mospagebreak title=Future Directions}

At Java One this year, James Gosling announced project Jakarta, an Apache working group working on a 100% Pure Java Servlet and JavaServer Page implementation to be used in the Apache web server. As of this writing, developers are still waiting for the release of Sun’s JavaServer Web Development Kit source code. This promises to be an exciting development for Apache Jserv, as future releases can (and hopefully) coincide with the current JSDK specification.

Furthermore, the initial public release of the next version of the Servlet specification, 2.2, is also available. Aside from some relatively minor API changes and improvements, the new specifications introduces two new concepts. First, there is the “Web Application” concept. A web application is all the resources – servlets, jsp pages, images, classes, html pages and other resources that can be bundled – which can be packaged an run in servlet engines from different vendors. The next concept is a natural extension of the “Web Application” idea, the “Web Application Archive.” Similar in concept to the jar files, all the resources associated in a web application would be bundled and zipped up in to a single file. Ideally, these “.war” (Web ARchive) could be distributed and easily plugged into servlet compliant web servers, greatly easing the integration process.

{mospagebreak title=Links}

There’s a great number of resources available on the web.

  1. Java Servlet API Specification 2.1,
  2. Using Apache Jserv 1.0, Ari Halberstadt
[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye