First Java Servlet

Our first servlet is a simple servlet designed to handle the HTTP GET method. Create the following servlet HeiioWoridServiet.java using any text editor.

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloWorldServlet extends HttpServiet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException {

response.setContentType(”text/html”);

PrintWriter out = response.getWriter();

out.println(”<html><head><title>Hello World Servlet</title></head>”);

out.println(“<body>”);

out.println(“<h1>Hello World!</h1>”);

out.println(“</body></html>”);

out.close();

}

}

The class HeiioWoridServiet extends the HttpServiet class. So, it can handle HTTP requests. It is written to handle only the GET method. Therefore, only the doGet() method is overridden. The output of this servlet is a text document containing html tags. This is mentioned using the setContentType() method. To send the data back to the client, a PrintWriter object is obtained by calling the getWriter() method on the response object. Finally, it sends the following HTML document.

<html><head><title>Hello World Servlet</title></head>

<body>

<h1>Hello World!</h1>

</body></html>

At the end, we close the PrintWriter object. It is not mandatory as the web container closes the PrintWriter or ServietOutputStream automatically, when the serviced method returns. An explicit call to ciose() is useful when you want to perform some processing after responding to the client’s request. This also tells the web container that the response is completed and the connection to the client may be closed as well.

1. Installing Apache Tomcat web server

To install these servlets, we need a web server. Any web server that supports servlets may be used. A list of web servers supporting servlets may be found in Table 20.1 and Table 20.2. Note that the procedure for installing servlets varies from web server to web server. Please refer to the documentation of your web server for definitive instructions. All the servlets are tested in this book using Tomcat web server provided by Apache software foundation. Tomcat is a lightweight, easily configurable free web server and is widely used by users who are new to servlets.

Let us now discuss how to install and configure the Tomcat web server.

Before installing Tomcat, make sure that you have installed either Java 6 Standard Edition (JDK 1.7) or Java 5 Standard Edition (JDK 1.6) in your computer. Download and install Java from http://java.com/en/downioad/index.jsp. Once you have installed, include the Java “bin” directory in the PATH environment variable. For example, if you have installed Java in D:\Java\jdki.7.0_07, include D:\Java\jdki.7.0_07\bin subdirectory in the PATH environment variable. Additionally, create an environment variable JAVA_HOME and set it by the Java installation directory (D:\Java\ jdki.7.0_07 in our case).

Download the necessary files from http://tomcat.apache.org/. When I was writing this book, the latest version was Tomcat 8.0. It is recommended to download a .zip or .zip.tar file for the beginners. If you have downloaded an installer file, install it. If it is a .zip file or .zip.tar file, simply unzip it in a folder. We shall assume that you have installed Tomcat in the D:\apache- tomcat-8.0.0-RCi directory.

Tomcat has a predefined directory structure. A typical directory structure is shown in Figure 20.5:

Suppose $tomcat_home represents the root of the Tomcat installation directory. According to Figure 20.5:, it represents the D:\apache-tomcat-8.0.0-RCi directory. The following are some key Tomcat directories under $tomcat_home:

  • \bin—Startup, shutdown, and other scripts. The *.bat (for Windows) files and Unix/Linux counterparts *.sh
  • \conf — Configuration XML files. The primary configuration file is xml, which describes how the server starts, behaves and finds other information. All the information in the configuration files is loaded whenever the web server starts up. So, any change to the files needs a restart of the web server.
  • \lib — Binary jar files are needed for the server to function. You should put your custom jar files in this directory. Tomcat can find them at runtime.
  • \webapps — It contains web applications. The directory root under it contains the default web application, which can be accessed using the URL http://172.16.5.81:8080, where 16.5.81 is the IP address of the computer where this web server is running. You should create your own directory under it. We shall create a directory net (short for network programming) to put our servlet files. So, the document root of our website will be http://172.16.5.81:8080/net.

2. Building and Installing Servlet

To compile our HelloWorldServlet.java file, servlet class files are required. Tomcat comes with a .jar file that contains necessary class files. For Tomcat 8.0, the name of this .jar file is servlet-api. jar. You can find this jar file usually in the $TOMCAT_HOME\lib directory.

Compile the HelloWorldServlet.java using the following command:

javac -cp d:\apache-tomcat-8.0.0-RC1\lib\servlet-api.jar HelloWorldServlet.java

This generates the file HelloWorldServlet.class that contains the byte code for our servlet. Create the following directory structure under the webapps subdirectory.


Put this HelloWorldServlet.class file in the $TOMCAT_HOME\webapps\net\WEB-INF\classes directory.

The servlet class file is now ready to use. However, we have to inform the web server about the existence of this servlet and the URL that will be used to refer to this servlet. This is specified in the $TOMCAT_HOME\net\WEB-INF\web.xml file, which is the configuration XML file for this website. If the file does not exist, create this file first.

Now, insert the following lines in this file. Some IDE provides interfaces to generate the same information. However, it is recommended to beginners to do it manually. When you have sufficient knowledge about how to install servlets and how they work, you may use IDEs.

<servlet>

<servlet-name>HelloWorld</servlet-name>

<servlet-class>HelloWorldServlet</servlet-class>

</servlet>

This code maps the servlet class (HelloWorldServlet.class) file to a servlet name (HelloWorld). The <servlet> tag tells the Tomcat that an instance of the servlet has to be created. The name of the class file (without the extension class) for this servlet is specified by the <servlets-class> tag. Once this instance is created, it can be referred to by a name specified by the <servlet-name> tag. You then need to map this servlet name to a URL to be used to invoke this servlet. This is a URL relative to the document root for this website.

<servlet-mapping>

<servlet-name>HelloWorld</servlet-name>

<url-pattern>/servlet/HelloWorld</url-pattern>

</servlet-mapping>

The above <servlet-mapping> tag indicates that the servlet having the name HelloWorld can be invoked using the URL pattern /servlet/HelloWorld relative to the document root. In our case, the document root is http://172.16.5.81:8080/net. So, the complete URL of this servlet will be

http://172.16.5.81:8080/net/servlet/HelloWorld.

3. Invoking Servlet

Invoking this servlet is very easy. Start the Tomcat web server. If everything goes correct, your web application will be deployed successfully. A sample output containing Tomcat startup message is shown in Figure 20.6:

The deployment message for our simple web application is highlighted in the output screen. Now, type the following URL in the address bar of your web browser and press enter. Make sure that the computer where the web server runs is accessible from your computer.

http://172.16.5.81:8080/net/servlet/HelloWorld

It generates the result as shown in Figure 20.7:

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *