by Dinesh Thakur Category: Basic Servlet Examples

Once the Tomcat is installed and configured, you need to perform the following steps to create and run a servlet.

1. Create a directory structure under Tomcat for your application

2. Write the servlet source code

3. Compile your servlet source code

4. Run the Servlet

Creating the Application Directory

When you install Tomcat, several sub directories are automatically created under the Tomcat home directory (in our case c: \ Tomcat6). One of the subdirectory is 'webApps' in which you store your web applications. A web application is a collection of web resources such as servlets, html pages, images, multimedia contents, Java Server Pages, XML configuration files, Java support classes and Java support libraries.

A web application has a well-known directory structure in which all the files that are part of the application reside. The web application directory contains a context root - the top level directory for the entire web application. All the servlets, HTML documents, JSPs and supporting files such as images and class files reside in this directory or its subdirectories. The name of this directory is specified by the web application creator and is placed under 'webApps' directory. In our case, we create a context root directory named servletApp. Note that this directory name is important as it appears in the URL while accessing the servlet. A separate context root directory is dedicated to each servlet application.

Under the context root directory servletApp, create the src and WEB-INF directories. The src directory is for source files. The WEB-INF directory contains the resources that are not to be directly downloaded to the client (browser). Under the WEB-INF directory, create classes and lib directory. In the classes directory, you place serv1et class files and other utility classes used in a web application. If the classes are part of a package, the complete package directory structure would begin here. In the lib directory, you place Java achieve (JAR) files. The JAR files can contain servlet class files and other supporting class files used in web application.

If you have html files, you put them directly under servletApp directory. All your image files should be placed in the images directory under servletApp directory.

For convience, we are using examples directory under webApps directory for explaining various examples.

Write the Servlet Source Code

To write the servlet, perform the following steps:

1. Open a text editor such as MS-Notepad to edit a new file. Save this file in the working directory (in our case c: \javaprog\).

2. Enter the servlet import statements to include the appropriate packages. Most servlets need access to atleast three packages - javax.servlet, java.servlet.http and java.io. So when you create servlet source code, you start with the following import statements.

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

 

 

 

 

 

 

In addition, you may need additional import statements depending on what other processing your servlet does.

3. Extend the genericServlet class: Since all servlets are required to implement the javax.servlet. Servlet interface and the GenericServlet class provide an implementation of this interface, so our class should extend GenericServlet class.

After the import statements, type class declaration as follows.

public class SimpleServlet extends GenericServlet
{
      …………………………………………………
}

 

 

 

 

 

 

 

The SimpleServlet class extends the GenericServlet class of javax.servlet package. The GenericServlet class provides functionality that makes it easy to handle requests and responses.

4. Write the required servlet methods: After the SimpleServlet class declaration, override the service () method which is inherited from GenericServlet class. Inside service () method, the request is handled and appropriate response is returned. Information about the request is available through a ServletRequest object and the response is returned via a ServletResponse object. Since the service () method can throw two exceptions (javax.servlet. ServletException and java.io.IOException), so you must throw them in the method declaration.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleServlet extend GenericServlet
{
     public void service (ServletRequest request, ServletResponse response)
     throw ServletException, IOException
    {
         .........................
    }
         .........................
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

5. Get the request information (if any) and generate the appropriate response: In this step, we will write the code that displays a message Welcome to Servlet on the client's web browser when the browser issues a request to the servlet.

The source code for SimpleServlet.java is as follows,

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SimpleServlet extends GenericServlet
 {
   public void service (ServletRequest request, ServletResponse response) throws     IOException, ServletException
    {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<b>Welcome to Servlet</b>");
      out.close();
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The first line of the code in the service () method

response.setContentType(“text/html");

sets the content type for the response. The client's browser uses this information to know how to treat the response data. Since we are generating HTML output, the content type is being set to text/html".

Then the statement,

printWriter out = response.getWriter();

calls the getWriter () method that returns a PrintWriter object (out)for sending character text in the response. Finally, printIn () method of the PrintWriter object is used to write the servlet response (Welcome to Servlet in bold form).

Now edit the web.xml file

<servlet>

   <servlet-name>SimpleServlet </servlet-name>
   <servlet-class>SimpleServlet </servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>SimpleServlet </servlet-name>
   <url-pattern>/SimpleServlet </url-pattern>
</servlet-mapping>

 

 

 

 

 

 

 

 

Compile Your Source Code

In this step, compile the servlet source code file C:\javaprog\SimpleServlet. java. For this, change the directory to your working directory, c: \javaprog and compile your file,

C:\javaprog>javac SimpleServlet.java

On successful compilation, SimpleServlet.class is created. Now copy this class file into the directory that Tomcat uses

C:\Tomcat6\webApps\examples\WEB-INF\classes

so as to run your servlet.

Run the Servlet

Before running the servlet, you need to start the Tomcat if it is not running. Now start a web browser and type

http://localhost:8080/examples/servlet/SimpleServlet

in the URL. The result will be shown as follows

Welcome to Servlet





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.