You are on page 1of 21

Chapter seven: Introduction to Servlets

What are Servlets?


Java Servlets are programs that run on a Web or Application server and act as a middle layer
between requests coming from a Web browser or other HTTP client and databases or applications on
the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.

Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.

Servlets Tasks:
Servlets perform the following major tasks:

 Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an Applet or a custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media
types and compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may require talking to a database,
invoking a Web service, or computing the response directly.

1
 Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in
a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.

Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet
specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard
part of the Java's enterprise edition, an expanded version of the Java class library that supports large-
scale development projects.

These classes implement the Java Servlet and JSP specifications. Java servlets have been created and
compiled just like any other Java class. After you install the servlet packages and add them to your
computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current
compiler.

Setting up Web Server: Tomcat


A number of Web Servers that support servlets are available in the market. Some web servers are freely
downloadable and Tomcat is one of them.

Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages
technologies and can act as a standalone server for testing servlets and can be integrated with the
Apache Web Server.

Servlets - Life Cycle

A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet

2
 The servlet is initialized by calling the init () method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in details.

The init( ) method :


The init method is designed to be called only once. It is called when the servlet is first created, and not
called again for each user request. So, it is used for one-time initializations, just as with the init method
of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you
can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request
resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply
creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {


// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write the
formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns/generates a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and
calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

3
Here is the signature of this method:

public void service(ServletRequest request,ServletResponse response)


throws ServletException, IOException{

The service ( ) method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service ( ) method but you
override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods within each service request. Here is the
signature of these two methods.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has no METHOD
specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and it should
be handled by doPost() method.

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

4
The destroy() method :
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your
servlet a chance to close database connections, halt background threads, write cookie lists or hit counts
to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The destroy
method definition looks like this:

public void destroy() {


// Finalization code...
}

Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.

 First the HTTP requests coming to the server are delegated to the servlet container.
 The servlet container loads the servlet before invoking the service( ) method.
 Then the servlet container handles multiple requests by spawning multiple threads, each thread
executing the service( ) method of a single instance of the servlet.

5
Servlets - Examples

Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet
interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet,
an abstract class that implements the Servlet interface and is specially designed to handle HTTP
requests.

Sample Code for Hello World:


Following is the sample source code structure of a servlet example to write Hello World:

// Import required java libraries


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

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// TODO output your page here
out.println("<html>");

6
out.println("<head>");
out.println("<title>Welcome to java servlet</title>");
out.println("</head>");
out.println("<body>");

out.println("<h1> This is my first java servlet program</h1>");

out.println("<a href=\"http://www.google.co.za\">google</a>");
out.println("</body>");
out.println("</html>");

} finally {
out.close();
}
} }

Servlets Form Data/query data

Before looking into how a servlet can read data submitted via a form, it is necessary to understand how
data from an HTML form is passed to the web server by the browser.

There are two common ways of passing data from the web browser to the web server. They are called
POST and GET methods. Both of these methods pass the data in a 'key=value' format. The key for each
data field is specified as part of the tag describing the relevant field.

7
GET method:

The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? character as follows:

http://www.test.com/hello?key1=value1&key2=value2

The GET method is the default method to pass information from browser to web server and it
produces a long string that appears in your browser's Location: box. Never use the GET method if you
have password or other sensitive information to pass to the server. The GET method has size limitation:
only 1024 characters can be in a request string.

This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using doGet()
method.

POST method:
A generally more reliable method of passing information to a backend program is the POST method.
This packages the information in exactly the same way as GET methods, but instead of sending it as a
text string after a ? in the URL it sends it as a separate message. This message comes to the backend
program in the form of the standard input which you can parse and use for your processing. Servlet
handles this type of requests using doPost() method.

Reading Form Data using Servlet:


Servlets handles form data parsing automatically using the following methods depending on the
situation:

 getParameter(): You call request.getParameter() method to get the value of a form parameter.

 getParameterValues(): Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.

8
 getParameterNames(): Call this method if you want a complete list of all parameters in the
current request.

GET Method Example Using URL:


Below is Formdatausinggetmethod.java servlet program to handle input given by web browser. We are
going to use getParameter() method which makes it very easy to access passed information:

// Import required java libraries


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 Formdatausinggetmethod extends HttpServlet {

/* Processes requests for both HTTP <code>GET</code> and <code>POST</code>


methods.

*/
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// TODO output your page here

out.println( "<html>");
out.println( "<head><title> Using GET Method to Read Form Data </title></head>");
out.println( "<body bgcolor=pink");

out.println("<form action=Formdatausinggetmethod method=GET>");

out.println("First Name: <input type=text name=first_name>");


out.println("<br />");
out.println("Last Name: <input type=text name=last_name />");
out.println("<input type=submit value=Submit />");
out.println("</form>");

out.println( "<h1 align=center> Using GET Method to Read Form Data </h1>");
out.println( "<ul>");
out.print( " <li><b>First Name</b>: ");
out.println( request.getParameter("first_name"));
out.print( " <li><b>Last Name</b>: ");
out.println( request.getParameter("last_name"));
out.println( "</ul>");
out.println( "</body></html>");

} finally {
9
out.close();
}
}

After running, try to enter First Name and Last Name and then click submit button to see the result on
your local machine where tomcat is running. Based on the input provided, it will generate similar result
as shown below.

If you click submit button you will get the query data at the URL address as follows

http://localhost:8085/Servletexamples12/Formdatausinggetmethod?first_name=Selam&last_name=Taye

10
If everything goes fine, above compilation would produce Formdatausinggetmethod.class file. Next you
would have to copy this class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes
and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/

<servlet>
<servlet-name> Formdatausinggetmethod </servlet-name>
<servlet-class> Formdatausinggetmethod </servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> Formdatausinggetmethod </servlet-name>
<url-pattern>/ Formdatausinggetmethod </url-pattern>
</servlet-mapping>

POST Method Example Using Form:


Let us do little modification in the above servlet, so that it can handle GET as well as POST methods.
Below is Formdatausingpostmethod.java servlet program to handle input given by web browser using
GET or POST methods.

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 Formdatausingpostmethod extends HttpServlet {

/*Processes requests for both HTTP <code>GET</code> and <code>POST</code>


methods. */

11
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// TODO output your page here

out.println( "<html>");
out.println("<head><title> Using POST Method to Read Form Data </title></head>");
out.println( "<body bgcolor=pink");

out.println("<form action=Formdatausingpostmethod method=POST>");


out.println("First Name: <input type=text name=first_name>");
out.println("<br />");
out.println("Last Name: <input type=text name=last_name />");
out.println("<input type=submit value=Submit />");
out.println("</form>");

out.println("<h1 align=center> Using POST Method to Read Form Data </h1>");


out.println( "<ul>");
out.print( " <li><b>First Name</b>: ");
out.println( request.getParameter("first_name"));
out.print( " <li><b>Last Name</b>: ");
out.println( request.getParameter("last_name"));
out.println( "</ul>");
out.println( "</body></html>");
} finally {
out.close();
}
}

Based on the input provided, it would generate similar result as mentioned in the above examples.

12
Passing Checkbox Data to Servlet Program
Checkboxes are used when more than one option is required to be selected.

Here is example HTML code, CheckBox.htm, for a form with two checkboxes

<html>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" />
Chemistry
13
<input type="submit" value="Select Subject" />
</form>
</body>
</html>

The result of this code is the following form

Maths Physics Chemistry

Below is CheckBox.java servlet program to handle input given by web browser for checkbox button.

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 Formdatacheckbox extends HttpServlet {

/* Processes requests for both HTTP <code>GET</code> and <code>POST</code>


methods

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {

// TODO output your page here

out.println("<html>");

out.println("<head><title> Reading checkbox data</title></head>");

out.println("<body bgcolor=#f0f0f0>");

out.println("<form action=Formdatacheckbox method=POST>");

out.println("<input type=checkbox name=maths checked=checked /> Maths");

14
out.println("<input type=checkbox name=physics /> Physics");

out.println("<input type=checkbox name=chemistry checked=checked />Chemistry");

out.println("<input type=submit value=Select Subject />");


out.println("</form>");
out.println("<h1 align=center> Reading data checkbox data</h1>");
out.println("<ul>");
out.print("<li><b>Maths Flag : </b> ");
out.println( request.getParameter("maths"));
out.print(" <li><b>Physics Flag : </b> ");
out.println( request.getParameter("physics"));
out.print("<li><b>Chemistry Flag : </b> ");
out.println( request.getParameter("chemistry"));
out.println("</ul>");

out.println(" </body>");
out.println(" </html>");

} finally {
out.close();
}
}

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

15
Reading All Form Parameters:
Following is the generic example which uses getParameterNames() method of HttpServletRequest to
read all the available form parameters. This method returns an Enumeration that contains the parameter
names in an unspecified order.
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;

16
public class checkbox extends HttpServlet {

protected void processRequest(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
// TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Check Box Example</title>");
out.println("</head>");
out.println("<body bgcolor=pink>");
out.println("<form method=post action=checkbox>");
out.println("<p>Enter your name <input type=text name=txt1 /></p>");
out.println("<h3>Select Courses</h3>");
out.println("<p><input type=checkbox name=course value=VB.net /> VB.net");
out.println("<p><input type=checkbox name=course value=C++ /> C++ ");
out.println("<p><input type=checkbox name=course value=PHP /> PHP");
out.println("<p><input type=submit value=Submit> </p>");
out.println("</form> ");

String name;
String[] course;
name= req.getParameter("txt1");
course= req.getParameterValues("course");
if(course!=null)
{
out.println("<html><body bgcolor=#00fffff>");
out.println("Hi I am <h4>"+name+"</h4><br>");
out.println("Selected course(s) is/are:");
out.println("<ul>");
for(int i=0; i<course.length; i++){
out.println("<li>"+(course[i]));
}
out.println("</ul>");
out.println("</body></html>");
}
else
out.println("<p><font color=red>not selected</font></p>");
} finally { out.close(); }
}
}

Retrieving Data from the table using Statement

In this program we are going to fetch the data from the database in the table from our java program.  
17
To accomplish our goal we first have to make a class named as dbconnection which must extends the
abstract HttpServlet class, the name of the class should be such that the other person can understand
what this program is going to perform. The logic of the program will be written inside the doGet()
method which takes two arguments, first is HttpServletRequest interface and the second one is the
HttpServletResponse interface and this method can throw ServletException.

Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the data from the
database only and only if there is a connectivity between our database and the java program. Now use
the static method getConnection() of the DriverManager class. This method takes three arguments and
returns the Connection object. SQL statements are executed and  results are returned within the context
of a connection. Now your connection has been established. Now use the method createStatement() of
the Connection object which will return the Statement object. This object is used for executing a static
SQL statement and obtaining the results produced by it. As we need to retrieve the data from the table so
we need to write a query to select all the records from the table. This query will be passed in the
executeQuery() method of Statement object, which returns the ResultSet object. Now the data will be
retrieved by using the getString() method of the ResultSet object.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class dbconnection extends HttpServlet {
Connection con;Statement stmt; ResultSet rs;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "stud", "stud");
stmt=con.createStatement();

out.println("<h1> Deriver loaded </h1>");

rs=stmt.executeQuery("select * from dept1");


out.println("<html>");
out.println("<head>");
out.println("<title>Servlet dbconnection</title>");
18
out.println("</head>");
out.println("<body>");
out.println("<table border= 2> ");
out.println("<tr> ");
out.println("<td> did </td> <td> dname </td> ");
out.println("<br>");

while(rs.next()){
out.println("<tr> ");
out.println("<td>"+rs.getString(1) + "</td> <td>" +rs.getString(2)+"</td>" );
out.println("<br>");
}

}
catch(Exception e){
System.out.println(e);
}

Inserting data from the HTML page to the database

In this program we are going to make program in which we are going to insert the values in the database
table from the html form.

To make our program working we need to make one html form in which we will have two fields, one is
for the name and the other one  is for entering the password. At last we will have the submit form,
clicking on which the values will be passed to the server.

The values which we have entered in the Html form will be retrieved by the server side program which
we are going to write. To accomplish our goal we first have to make a class named as
Servletinsertingdatatodb which must extends the abstract HttpServlet class, the name of the class
should be such that the other person can understand what this program is going to perform. The logic of
the program will be written inside the doGet() method which takes two arguments, first is
HttpServletRequest interface and the second one is the HttpServletResponse interface and this method
can throw ServletException.

Inside this method call the getWriter() method of the PrintWriter class. We can insert the data in the
database only and only if there is a connectivity between our database and the java program. To
establish the connection between our database and the java program we firstly need to call the method
19
forName() which is static in nature of the class Class. It takes one argument which tells about the
database driver  we are going to use. Now use the static method getConnection() of the
DriverManager class. This method takes three arguments and returns the Connection object. SQL
statements are executed and  results are returned within the context of a connection. Now your
connection has been established. Now use the method prepareStatement() of the Connection object
which will return the PreparedStatement object and takes one a query which we want to fire as its input.
The values which we have got from the html will be set in the database by using the setString() method
of the PreparedStatement object.

If the record will get inserted in the table then output will show "record has been inserted"  otherwise
"sorry! Failure".

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Servletinsertingdatatodb extends HttpServlet {
Connection con; Statement stmt; ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(" <html>");
out.println(" <head>");
out.println("<title>Wel come to data insertion page</title> </head>");
out.println("<body>");
out.println("<form method=POST action=Servletinsertingdatatodb >");
out.println(" <p>Enter Dept ID: <input type=text name=did size=20></p>");
out.println(" <p>Enter Dept Name: <input type=text name=dname size=20 </p>");
out.println("<input type=submit value=Submit name=B1></p>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "stud", "stud");
stmt=con.createStatement();
out.println("<h1> Deriver loaded </h1>");
String id = request.getParameter("did");
String name = request.getParameter("dname");
out.println(id);
out.println(name);
PreparedStatement pst = con.prepareStatement("insert into dept1 values(?,?)");
pst.setString(1,id);
pst.setString(2,name);
int i = pst.executeUpdate();
if(i!=0){
20
out.println("<br>Record has been inserted");
}
else{
out.println("failed to insert the data");
}
}
catch (Exception e){
out.println(e);
} }

21

You might also like