Simple Servlet Example: Bookmark This Tutorial
Simple Servlet Example: Bookmark This Tutorial
Simple Servlet Example: Bookmark This Tutorial
com
Free servlet jsp tutorials
Home
Servlet tutorials
JSP tutorials
Examples
You have learned about J2EE web containers,J2EE web application structure and
basics of Java Servlets in previous Servlet tutorials. This Servlet tutorial provides a very
simple servlet example.
What is covered in this Servlet example
1. How to write the servlet class.
2. How to compile the Servlet class.
3. How to extract the HTML form parameters from HttpServletRequest.
4. web.xml deployment descriptor file.
5. How to create the war (web application archive) file.
6. How to deploy and run the sample web application in tomcat web container.
You need the Java SDK and tomcat web server installed, to run the example Servlet
application developed in this tutorial. Setting up the Servlet development environment tutorial
explains how to setup the development environment.
If you don’t have the basic understanding of the J2EE web containers and web application
structure, read the previous Servlet tutorials which explain these basic things.
This is a very simple web application containing a HTML file and a servlet. The HTML document
has a form which allows the user to enter the name, when the form is submitted application
displays the welcome message to the user.
First of all we need to create the directory structure for our sample web application as
explained in the tutorial Understanding the directory structure of web applications. Create the
directory structure as shown in below figure.
Create the HTML file.
Copy the following code into form.html file and save it under servlet-example/pages directory.
<html>
<head>
<title>The servlet example </title>
</head>
<body>
<h1>A simple web application</h1>
<form method="POST" action="WelcomeServlet">
<label for="name">Enter your name </label>
<input type="text" id="name"
name="name"/><br><br>
<input type="submit" value="Submit Form"/>
<input type="reset" value="Reset Form"/>
</form>
</body>
</html>
The welcome Servlet class
Copy the following code into WelcomeServlet.java file and save it under servlet-example/WEB-
INF/src/jsptube/tutorials/servletexample directory.
Note: it is not necessary to crate /src directory under WEB-INF directory and you can safely
exclude WEB-INF/src directory when creating WAR file. You can put the source files any where
you want, but don’t forget to put the compiled classes into WEB-INF/classes directory before
creating the WAR file.
package jsptube.tutorials.servletexample;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
/*
* Get the value of form parameter
*/
String name = request.getParameter("name");
String welcomeMessage = "Welcome "+name;
/*
* Set the content type(MIME Type) of the response.
*/
response.setContentType("text/html");
PrintWriter out = response.getWriter();
/*
* Write the HTML to the response
*/
out.println("<html>");
out.println("<head>");
out.println("<title> A very simple servlet example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>"+welcomeMessage+"</h1>");
out.println("<a href="/servletexample/pages/form.html">"+"Click here to
go back to input page "+"</a>");
out.println("</body>");
out.println("</html>");
out.close();
}
public void destroy() {
}
}
Now compile the servlet class as explained below.
Open the command prompt and change the directory to the servlet-example/WEB-
INF/src/jsptub/tutorials/servletexample directory. Compile the WelcomeServlet.java using the
following command. javac WelcomeServlet.java It will create the file
WelcomeServlet.class in the same directory. Copy the class file to classes directory. All the
Servlets and other classes used in a web application must be kept under WEB-INF/classes
directory.
Note: to compile a servlet you need to have servlet-api.jar file in the class path.
The deployment descriptor (web.xml) file.
Copy the following code into web.xml file and save it directly under servlet-example/WEB-INF
directory.
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-
class>jsptube.tutorials.servletexample.WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file> /pages/form.html </welcome-file>
</welcome-file-list>
</web-app>
Create the WAR (Web application archive) file.
Web applications are packaged into a WAR (web application archive). There are many different
ways to create a WAR file. You can use jar command, ant or an IDE like Eclipse. This tutorial
explains how to create the WAR file using jar tool.
Open the command prompt and change the directory to the servlet-example directory, and
execute the following command.
jar cvf servletexample.war *
This command packs all the contents under servlet-example directory, including
subdirectories, into an archive file called servletexample.war.
We used following command-line options:
-c option to create new WAR file.
-v option to generate verbose output.
-f option to specify target WAR file name.
You can use following command to view the content of servletexample.war file.
Jar –tvf servletexample.war.
This command lists the content of the WAR file.
Deploying the application to tomcat web container.
Deployment steps are different for different J2EE servers. This tutorial explains how to deploy
the sample web application to tomcat web container. If you are using any other J2EE server,
consult the documentation of the server.
A web application can be deployed in tomcat server simply by copying the war file to
<TOMCAT_HOME>/webapp directory.
Copy servletexample.war to <TOMCAT_HOME>/webapp directory. That’s it! You have
successfully deployed the application to tomcat web server. Once you start the server, tomcat
will extract the war file into the directory with the same name as the war file.
To start the server, open the command prompt and change the directory to
<TOMCAT_HOME/bin> directory and run the startup.bat file.
Our sample application can be accessed at http://localhost:8080/servletexample/. If tomcat
server is running on port other than 8080 than you need to change the URL accordingly.
If the application has been deployed properly, you should see the screen similar to below
when you open the application in browser.
Enter your name in text box and click on submit button. It will display welcome message with
your name as shown in below figure.
Browser receives the HTML document as response and displays in browser window.
The next step is to understand the code.
Understanding the code.
Package declaration
WelcomeServlet class is a part of jsptube.tutorials.servletexample package. First line of code
declares the package.
package jsptube.tutorials.servletexample;
Import servlet packages:
The Java servlet API consists of two packages: javax.servlet and javax.servlet.http. Of these
two packages, the javax.servlet package contains classes and interfaces that are independent
of HTTP protocol. javax.servlet.http package contains classes and interfaces that are specific
to HTTP protocol.
The next lines of code import the required classes and interfaces.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
These are the most common classes and interfaces that you will need to import in every
servlet.
Servlet class declaration:
Next line of code declares the WelcomeServlet class.
public class WelcomeServlet extends HttpServlet {
Every servlet class needs to implement javax.servlet.Servlet interface. HttpServlet class
provides HTTP specific implementation of Servlet interface. Generally Servlets in web
application implements javax.servlet.Servlet interface indirectly by extending
javax.servlet.http.HttpServlet class.
The init() method:
Next lines of code declares the init() method. Init() method is a Servlet life cycle method and
defined in javax.servlet.Servlet interface.
public void init(ServletConfig config) throws ServletException {
super.init(config); }
Init() method is used to initialize the servlet. In our example servlet, init() method doesn’t do
anything, it just calls the super class version of the method.
Service the HTTP POST request:
Next lines of code declares the doPost() method. doPost() method is defined in HttpServlet
class. doPost() method is used to handle the HTTP POST request. This method takes
HttpSevletRequest and HttpServletResponse objects as arguments. HttpServletRequest object
encapsulates the information contained in the request. HttpServletResponse object
encapsulates the HTTP response.
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {<br />
You may wonder why there is no service() method defined in the WelcomeServlet class. The
answer is: because it is implemented by HttpServlet class. HttpServlet class provides the
implementation of service() method which calls either doGet() or doPost() method based on
the HTTP request method. Since we have used POST method in our HTML form, doPost() is
called.
Extract request parameters from HttpServletRequest object.
Following line of code extracts the value of name parameter.
String name = request.getParameter("name");
getParameter() method of HttpServletRequest interface is used to extract the value of form
parameters. getParameter() method takes the name of the form field as String argument and
returns whatever user has entered into the form as String value.
The next line is very simple it constructs the welcome message.
String welcomeMessage = "Welcome "+name;
Generate Response: The next line sets the content type of the response, in out example, this
is text/html.
response.setContentType("text/html");
Response can be returned to the client by writing to the java.io.PrintWriter object associated
with ServletResponse.
Following line obtains the PrintWriter object from HttpServletResponse object.
PrintWriter out = response.getWriter();<br />
Following lines of code writes the HTML to the response.
out.println("<html>");
out.println("<head>");
out.println("<title> A very simple servlet example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>"+welcomeMessage+"</h1>");
out.println("<a href="/servletexample/pages/form.html">"+"Click here to
go back to input page "+"</a>");
out.println("</body>");
out.println("</html>");
Close the PrintWriter object.
out.close();
Destroy() method: Next lines of code declares the destroy() method. Destroy() method is a
servlet life cycle method and defined in javax.servlet.Servlet interface.
public void destroy() { }
Destroy method is called by the web container when removing servlet instance out of service
or when the server is shutting down.
The web.xml Deployment descriptor file:
Web.xml file is called the deployment descriptor, it includes the configuration of our web
application. The first line in the deployment descriptor specifies the version of the XML and
encoding used.
Following lines declares the XML name space.
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
Next is the servlet definition. Every Servlets in a web application must be defined in the
web.xml file using <servlet> tag. Following lines defines the WelcomeServlet.
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>jsptube.tutorials.servletexample.WelcomeServlet</servlet-
class>
</servlet>
Servlet-name tag specifies the name of the servlet, this name is used later in servlet-mapping.
Servlet-class specifies the fully qualified class name of the servlet.
Next is servlet mapping. Servlet mapping is used to map the URLs to a servlet. The following
servlet mapping definition specifies that the request for the URL /WelcomeServlet should be
handled by WelComeServlet class.
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
We have used /WelcomeServlet as the value of action attribute in the HTML form.
<form method="POST" action="/WelcomeServlet">
So when the form is submitted, browser sends the POST request to path /WelcomeServlet
which is than handled by WelcomServlet class.
Next is welcome file list. Any public resource, such as an HTML or JSP document, can be
specified as a welcome file using the <welcome-file-list> element in the deployment
descriptor. When you type the URL path pointing to a web application (for example
http://localhost:8080/servletexample), the web container displays the welcome file
automatically.
Following lines specifies /pages/form.html as the welcome file. So when you access the URL
http://localhost:8080/servletexample, web container server pages/form.html file.
<welcome-file-list>
<welcome-file>
/pages/form.html
</welcome-file>
</welcome-file-list>
Next line ends the <web-app> tag.
</web-app>
Congratulations! You have learned how to develop simple web applications using Servlets.
Source code of this tutorial is attached here. I suggest that you download the source code and
try to run the application on your computer and see how it works.
Related tutorials
Setup servlet development environment
HTML Form processing servlet example
Generic servlet Example
J2EE web application directory structure
This servlet tutorial will teach you how to handle and process HTML form with
Servlet. You will learn following things
1. How to write HTML forms
2. How to forward request from a servlet to a JSP
3. How to read form parameters from request object
4. How to process HTML form input elements like text box, password fields, text area,
radio button and checkbox
5. How to generate response from servlet.
6. How to define servlet and servlet mapping in web.xml
Home