Steps to create a servlet example

There are five steps to create a servlet. These steps are required for all the servers. Now see these steps-

  • Create directory structure
  • Create Servlet java file
  • Compile the Servlet java file
  • Create a deployment descriptor
  • Start the server and deploy the first servlet application

Now learn full description of Servlet Example

1.Create directory structure

The directory structure defines that where to put the all different types of files so that easily web container get the all information and respond to the client. The Sun Microsystem defines a unique standard to be followed by all the server vendors.

java servlet tutorial

You can see all file is separated and separated folder and web.xml file must be in WEB-INF folder.

2. Create servlet java file

  1. By implementing the Servlet interface
  2. By inheriting the GenericServlet class
  3. By inheriting the HttpServlet class

The HttpServlet class is used to create the servlet because it provides methods to handle http requests such as doGet(), doPost, doHead() etc.

import javax.servlet.*;  
import javax.servlet.http.*;  

public class FirstServlet extends HttpServlet{  
public void doGet(HttpServletRequest req,HttpServletResponse res)  
throws ServletException,IOException  


res.setContentType("text/html");//content type  
PrintWriter pw=res.getWriter();//get the stream to write the data  
pw.println("Welcome to First Servlet Example");  
pw.close();//closing the stream  


3.Compile the Servlet java file

java servlet example
  1. Oracle s web application (Formerly Bea web Logic)
  2. Oracle s GlassFish Server (Formerly sun GlassFish server)
  3. IBM s websphere
  4. RedHot JBoss server

In order to compile servlet implementation class of servlet api are required. These class are provide by web and application server different server provide these server throw jar file for example.

Web/application Server Jar File
Tomcat(web) servlet-api.jar
Oracle WebLogic(app) weblogic.jar
Oracle glassfish server (from sun gfs) javaee.jar
JBoss javaee.jar

Create a Deployment Descriptor

web.xml file


Description of the elements of web.xml

There are too many elements in the web.xml file. The elements are as follows:

  • <web-app>represents the full application.
  • <servlet>is sub element of <web-app> and represents the servlet.
  • <servlet-name>is sub element of <servlet> represents the name of the servlet.
  • <servlet-class>is sub element of <servlet> represents the class of the servlet.
  • </servlet-mapping>s sub element of <web-app>. It is used to map the servlet.
  • <url-pattern>is sub element of </servlet-mapping>. This pattern is used at client side to invoke the servlet.