• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Servlet » Examples » Servlets First Examples
Next →
← Prev

Servlets First Examples

By Dinesh Thakur

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

We’ll be covering the following topics in this tutorial:

  • Creating the Application Directory
  • Write the Servlet Source Code
  •  
  •  
  •  
  •  
  •  
  •  
  • Compile Your Source Code
  • Run the Servlet
  • Welcome to 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

https://ecomputernotes.com:8080/examples/servlet/SimpleServlet

in the URL. The result will be shown as follows

Welcome to Servlet

You’ll also like:

  1. Types of Servlets
  2. Advantages of Servlets
  3. Servlets Client HTTP Request
  4. Steps for Using Sessions in Servlets
  5. Additional Capabilities of HTTP Servlets
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Servlet Tutorials

Servlet Tutorials

  • Servlet - Home
  • Servlet - Types
  • Servlet - Advantages
  • Servlet - Container
  • Servlet - API
  • Servlet - Chaining
  • Servlet - Life Cycle
  • Servlet - Developement Way
  • Servlet - Servlet Vs CGI
  • Servlet - Server Side
  • Servlet - HttpServletRequest
  • Servlet - Cookies Advantages
  • Servlet - JDBC Architecture
  • Servlet - HttpServlet
  • Servlet - HttpServletResponse
  • Servlet - Web Technology
  • Servlet - Applet Communication
  • Servlet - Html Communication
  • Servlet - HTTP POST Request
  • Servlet - HTTP GET Request

Other Links

  • Servlet - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW