You are on page 1of 16

JSPtube.

com
Free servlet jsp tutorials
 Home
 Servlet tutorials
 JSP tutorials
 Examples

Bookmark this tutorial


If you like our site please bookmark this and help us

Home » J2EE web development tutorials


Simple Servlet example
 Servlet tutorials

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.

The next step is to understand how the application works.


How the application works.
When you access the application by navigating to URL http://localhost:8080/servletexample/
the web server serves the form.html file. \pages\form.html file is specified as welcome file in
web.xml file so web server serves this file by default.
When you fill the form field and click on submit form button, browser sends the HTTP POST
request with name parameter. Based on the servlet mapping in web.xml, the web container
delegates the request to WelcomeServlet class.
When the request is received by WelcomeServlet it performs following tasks.
 Extract the name parameter from HttpServletRequest object.
 Generate the welcome message.
 Generate the HTML document and write the response to HttpServletResponse object.

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

‹ Servlet File Upload Example up The JSP page directive ›


 Login to post comments
Home
Copyright © 2010 JSPtube.com
JSPtube.com
Free servlet jsp tutorials
 Home
 Servlet tutorials
 JSP tutorials
 Examples

Bookmark this tutorial


If you like our site please bookmark this and help us

Home » J2EE web development tutorials


A simple HTML form processing servlet example
 Servlet tutorials

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

Create HTML Form


Copy following code into form.jsp file under /pages directory.
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<html>
<head>
<title>A simple form processing Servlet example</title>
</head>
<body>
<h3>User registration example</h3>
<form action="formServlet" method="post">
<table>
<tr>
<td>User Name</td>
<td><input type="text"
name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password"
name="password"></td>
</tr>
<tr>
<td>Bio</td>
<td><textarea rows="5" cols="50"
name="bio"></textarea> </td>
</tr>
<tr>
<td>Country</td>
<td>
<select name="country">
<option
value="ind">India</option>
<option
value="usa">America</option>
<option
value="ca">Canada</option>
<option
value="aus">Australia</option>
</select>
</td>
</tr>
<tr>
<td>Subscribe for newsletter</td>
<td>
<label
for="newsletter1">Yes</label>
<input type="radio"
id="newsletter1" name="newsletter" value="Yes" checked="checked">
<label
for="newsletter2">No</label>
<input type="radio"
id="newsletter2"name="newsletter" value="No">
</td>
</tr>
<tr>
<td>Preferences</td>
<td>
<label for="preference1">Receive
mail from members</label>
<input type="checkbox"
id="preference1" name="receivemail" value="yes" checked="checked"><br/>
<label for="preference2">Receive
notifications</label>
<input type="checkbox"
id="preference2" name="receivenotification" value="yes"><br/>
</td>
</tr>
<tr>
<td>
<input type="submit"
value="Submit">&nbsp;
<input type="reset">
</td>
<td></td>
</table>
</form>
</body>
</html>
Create a Servlet to process HTML form submission
Copy following code into FormServlet.java, compile the class and put it under WEB-INF/classes
directory
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
 
public class FormServlet extends HttpServlet {
 
protected void doGet(HttpServletRequest req, HttpServletResponse
resp) throws ServletException, IOException {
getServletContext().getRequestDispatcher("/WEB-
INF/pages/form.jsp").forward(req, resp);
}
 
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
String bio = request.getParameter("bio");
String country = request.getParameter("country");
String subscribeForNewsletter =
request.getParameter("newsletter");
String receiveMail =
request.getParameter("receivemail");
String reveiveNotifications =
request.getParameter("receivenotification");
 
response.setContentType("text/html");
 
PrintWriter writer = response.getWriter();
writer.write("<h2> You have entered following values
</h2>");
writer.write("<br/>");
writer.write("<table>");
startTableRow(writer);
addTableColumn(writer, "username");
addTableColumn(writer, userName);
closeTableRow(writer);
 
startTableRow(writer);
addTableColumn(writer, "password");
addTableColumn(writer, password);
closeTableRow(writer);
 
startTableRow(writer);
addTableColumn(writer, "Bio");
addTableColumn(writer, bio);
closeTableRow(writer);
 
startTableRow(writer);
addTableColumn(writer, "Country");
addTableColumn(writer, country);
closeTableRow(writer);
 
startTableRow(writer);
addTableColumn(writer, "Subscribe for news letter");
addTableColumn(writer, subscribeForNewsletter);
closeTableRow(writer);
 
startTableRow(writer);
addTableColumn(writer, "Receive mail from members");
addTableColumn(writer, receiveMail);
closeTableRow(writer);
 
startTableRow(writer);
addTableColumn(writer, "Receive notification");
addTableColumn(writer, reveiveNotifications);
closeTableRow(writer);
 
writer.write("</table>");
 
writer.close();
 
}
 
private static void startTableRow(PrintWriter writer) {
writer.write("<tr>");
}
 
private static void closeTableRow(PrintWriter writer) {
writer.write("</tr>");
}
 
private static void addTableColumn(PrintWriter writer, String
value) {
writer.write("<td> "+ value + "</td>");
}
 
 
}
Define servlet in deployment descriptor (web.xml)
A servlet must be defined into web.xml deployment descriptor. Copy the following code into
web.xml file and save it under WEB-INF directory.
<?xml version="1.0" encoding="ISO-8859-1"?>
 
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
 
<web-app>
<servlet>
<servlet-name>formServlet</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>formServlet</servlet-name>
<url-pattern>formServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/formServlet</welcome-file>
</welcome-file-list>
</web-app>
Deploy form processing servlet application to tomcat server
You just need to create war file of our web application and copy it to webapp directory under
your tomcat installation to deploy application to tomcat.
Open command prompt and go to root directory of our application (FormExample). Create a
war file using following command.

Understanding the GenericServlet class


 Servlet tutorials
The GenericServlet class
GenericServlet class defines a generic protocol independent servlet. It is protocol independent
in the sense it can be extended to provide implementation of any protocol like FTP, SMTP etc.
Servlet API comes with HttpServlet class which implements HTTP protocol. Generally when
developing web application, you will never need to write a servlet that extends GenericServlet.
Most of the Servlets in your application will extend HttpServlet class to handle web requests.
GenericServlet class provides implementation of Servlet Interface. This is an abstract class, all
the subclasses must implement service () method.
Public abstract class GenericServlet implements
Servlet,ServletConfig,Serializable
In addition to those methods defined in Servlet Interface, GenericServlet defines following
additional methods.
Public void init()
Public void log(String message)
Public void log(String message, Throwable t)
Initializing the Servlet
Public void init(ServletConfig config)
Public void init()
Public void init(ServletConfig config) method is an implementation of init() method defined in
Servlet interface, it stores the ServletConfig object in private transient instance variable.
getServletConfig() method can be used to get the reference of this object. If you override this
method, you should include a class to super.init(config) method. Alternatively, you can
override no-argument init() method.
Handling requests
Public abstract void service (ServletRequest request, ServletResponse
response);
This is an abstract method, and you must override this method in your subclass to handle
requests. All the code related to request processing and response generation goes here.
Destroying the Servlet
Public void destroy()
This method provides default implementation of destroy () method defined in the Servlet
interface. You can override this method in your subclasses to do some cleanup tasks when
servlet is taken out of service.
Accessing the environment
GenericServlet class also implements ServletConfig interface so all the methods of
ServletConfig interface can be called directly without first obtaining reference to ServletConfig
instance.
Public string getInitParameter(String name) : used to obtaing value of servlet initialization
parameter.
Public String getInitParameterNames() : returns names of all initialization parameters.
Public ServletContext getServletContext() : returns reference to ServletContext object.
getServletName() : used to obtain name of the servlet.
Writing to server log file
Public void log(String message)<br />
Public void log(String message, Throwable t)
GenericServlet class provides two utility methods for writing to server log file. log(String
message) method writes servlet name and message to web containers log file. the other
method log(string message, Throwable t), writes servlet name, string message and the
exception stack trace of the given Throwable exception to web containers log file.
Generic Servlet Example
package com.jsptube.servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
public class GenericServletExample extends GenericServlet {
 
public void init() {
log("inside init() method");
}
 
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
log("Handling request");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head><title>GenericServle example</title></head>");
out.write("<body><h1>GenericServlet: Hallo world </h1></body></html>");
out.close();
}
 
public void destroy() {
log("inside destroy() method");
}
 
}
Web.xml deployment descriptor
<?xml version="1.0" encoding="ISO-8859-1"?>
<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">
 
<servlet>
<servlet-name>GenericServlet</servlet-name>
<servlet-class>com.jsptube.servlet.GenericServletExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GenericServlet</servlet-name>
<url-pattern>/exampleservlet</url-pattern>
</servlet-mapping>
</web-app>
‹ The Life Cycle of a Servlet up Understanding the structure of web applications ›
 Login to post comments

Home

You might also like