ZeePedia

JAVA: Servlets Lifecycle

<< JAVA: Creating a Simple Web Application in Tomcat
JAVA: More on Servlets >>
img
Web Design & Development ­ CS506
VU
Lesson 28
Servlets Lifecycle
In the last handout, we have seen how to write a simple servlet. In this handout we will look more
specifically on how servlets get created and destroyed. What different set of method are invoked during the
lifecycle of a typical servlet.
The second part consists on reading HTML form data through servlet technology. This will be explored in
detail using code example
Stages of Servlet Lifecycle
A servlet passes through the following stages in its life.
1
Initialize
2
Service
3
Destroy
As you can conclude from the diagram below, that with the passage of time a servlet passes through these
stages one after another.
1. Initialize
When the servlet is first created, it is in the initialization stage. The webserver invokes he init() method of
the servlet in this stage. It should be noted here that init() is only called once and is not called for each
request. Since there is no constructor available in Servlet so this urges its use for one time initialization
(loading of resources, setting of parameters etc) just as the init() method of applet.
Initialize stage has the following characteristics and usage
Executed once, when the servlet gets loaded for the first time
Not called for each client request
The above two points make it an ideal place to perform the startup tasks which are done in
constructor in a normal class.
2. Service
The service() method is the engine of the servlet, which actually processes the client's request. On every
request from the client, the server spawns a new thread and calls the service() method as shown in the
figure below. This makes it more efficient as compared to the technologies that use single thread to respond
to requests.
204
img
Web Design & Development ­ CS506
VU
The figure below show both versions of the implementation of service cycle. In the upper part of diagram,
we assume that servlet is made by sub-classing from GenericServlet. (Remember, GenericServlet is used
for constructing protocol independent servlets.). To provide the desired functionality, service() method is
overridden. The client sends a request to the web server; a new thread is created to serve this request
followed by calling the service() method. Finally a response is prepared and sent back to the user according
to the request.
The second part of the figure illustrates a situation in which servlet is made using HttpServlet class. Now,
this servlet can only serves the HTTP type requests.
205
img
Web Design & Development ­ CS506
VU
Summary
A Servlet is constructed and initialized. The initialization can be performed inside of init() method.
Servlet services zero or more requests by calling service() method that may decide to call further
methods depending upon the Servlet type (Generic or HTTP specific)
Server shuts down, Servlet is destroyed and garbage is collected
The following figure can help to summarize the life cycle of the Servlet
The web sever creates a servlet instance. After successful creation, the servlet enters into initialization
phase. Here, init() method is invoked for once. In case web server fails in previous two stages, the servlet
instance is unloaded from the server.
After initialization stage, the Servlet becomes available to serve the clients requests and to generate
response accordingly. Finally, the servlet is destroyed and unloaded from web server.
Reading HTML Form Data Using Servlets
In the second part, the required concepts and servlet technology is explored in order to read HTML form
data. To begin with, let's first identify in how many ways a client can send data
HTML & Servlets
Generally HTML is used as a Graphics User Interface for a Servlet. In the figure below, HTML form is
being used as a GUI interface for MyServlet. The data entered by the user in HTML form is transmitted to
the MyServlet that can process this data once it read out. Response may be generated to fulfil the
application requirements.
206
img
Web Design & Development ­ CS506
VU
207
img
Web Design & Development ­ CS506
VU
Example Code: Reading Form Data using Servlet
This example consists of one HTML page (index.html), one servlet (MyServlet.java) and one xml file
(web.xml) file. The HTML page contains two form parameters: firstName and surName. The Servlet
extracts these specific parameters and echoes them back to the browser after appending "Hello".
Note: The example given below and examples later in coming handouts are built using netBeans®4.1. It's
important to note that tomcat server bundled with netBeans® runs on 8084 port by default.
index.html
Let's have a look on the HTML code used to construct the above page.
<html>
<head>
<title> Reading Two Parameters </title>
</head>
<body>
<H2> Please fill out this form: </H2>
<FORM METHOD="GET"
ACTION="http://localhost:8084/paramapp/formservlet"NAME="myform" >
<BR> Firstname:
<INPUT TYPE = "text" NAME="firstName">
<BR> Surname:
<INPUT TYPE = "text" NAME="surName">
<BR> <INPUT TYPE="submit" value="Submit Form"> <INPUT TYPE="reset"
value="Reset">
</FORM>
</body>
</html>
Let's discuss the code of above HTML form. As you can see in the <FORM> tag, the attribute METHODis
set to "GET". The possible values for this attribute can be GET and POST. Now what do these values
208
img
Web Design & Development ­ CS506
VU
mean?
Setting the method attribite to "GET" means that we want to send the HTTP request using the GET
method which will evantually activate the doGet() method of the servlet. In the GET method the
information in the input fields entered by the user, merges with the URL as the query string and are
visible to the user.
Setting METHOD value to "POST" hides the entered information from the user as this information
becomes the part of request body and activates doPost() method of the servlet.
Attribute ACTION of <FROM> tag is set to http://localhost:8084/paramapp/formservlet. The form data
will be transmitted to this URL. paramapp is the name of web application created using netBeans.
formservlet is the value of <url-pattern> defined in the web.xml. The code of web.xml is given at the end.
The NAME attribute is set to "myform" that helps when the same page has more than one forms.
However, here it is used only for demonstration purpose.
To create the text fields where user can enter data, following lines of code come into play
<INPUT TYPE = "text" NAME="firstName">
<INPUT TYPE = "text" NAME="surName">
Each text field is distinguished on the basis of name assigned to them. Later these names also help in
extracting the values entered into these text fields.
MyServlet.java
Now lets take a look at the servlet code to which HTML form data is submitted.
import java.io.*;import javax.servlet.*;import
javax.servlet.http.*;
public class MyServlet extends HttpServlet{
public void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException,
IOException{
// reading first name parameter/textfield
String fName = req.getParameter("firstName");
// reading surname parameter/textfield
String sName = req.getParameter("surName");
// gettting stream from HttpServletResponse objectPrintWriter out = res.getWriter();
out.println("Hello: " + fName + " " +sName ");
out.close();
}
}// end FormServlet
We started the code with importing three packages.
import java.io.*,
import javax.servlet.*;
import javax.servlet.http.*;
These packages are imported to have the access on PrintWriter, HttpServlet, HttpServletRequest,
HttpServletResponse, ServletException and IOException classes.
The class MySevlet extends from HttpServlet to inherit the HTTP specific functionality. If you recall
HTML code (index.html) discussed above, the value of mehtod attribute was set to "GET". So in this case,
we only need to override doGet()Method.
Entering inside doGet() method brings the crux of the code. These are:
String fName = req.getParameter("firstName");
209
img
Web Design & Development ­ CS506
VU
String sName = req.getParameter("surName");
Two String variables fName and sName are declared that receive String values returned by getParameter()
method. As discussed earlier, this method returns Stringcorresponds to the form parameter. Note that the
values of name attributes of input tags used in index.html have same case with the ones passed to
getParameter() methods as parameters. The part of HTML code is reproduced over here again:
<INPUT TYPE = "text" NAME="firstName">
<INPUT TYPE = "text" NAME="surName">
In the last part of the code, we get the object of PrintWriter stream from the object of
HttpServletResponse. This object will be used to send data back the response. Using PrintWriter object
(out), the names are printed with appended "Hello" that becomes visible in the browser.
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name> FormServlet </servlet-name>
<servlet-class> MyServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> FormServlet </servlet-name>
<url-pattern> /formservlet </url-pattern>
</servlet-mapping>
</web-app>
The <servlet-mapping> tag contains two tags <servlet-name> and <urlpatteren> containing name and
pattern of the URL respectively. Recall the value of action attribute of the <form> element in the HTML
page. You can see it is exactly the same as mentioned in <url-pattern> tag.
http://localhost:8084/paramapp/formservlet
References:
JAVA a Lab Course by Umair Javed
Java API documentation
Core Servlets and JSP by Marty Hall
210