Lecture 28 29
Lecture 28 29
Lecture 28 29
Lec 28-29
HANDOUTS
WEB DESIGN AND DEVELOPMENT
- 340 -
Handout 28
Web Design & Development CS-506
Lecture 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
As you can conclude from the diagram below, that with the passage of time a servlet passes
through these stages one after another.
time
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.
♦ Executed once, when the servlet gets loaded for the first time
- 341 -
Handout 28
Web Design & Development CS-506
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.
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.
- 342 -
Handout 28
Web Design & Development CS-506
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. In these
servlets doGet() and doPost() are overridden to provide desired behaviors. When a
request is sent to the web server, the web server after creating a thread, passes on this request
to service() method. The service() method checks the HTTP requests type (GET,
POST etc) and calls the doGet() or doPost() method depending on how the request is
originally sent. After forming the response by doGet() or doPost() method, the
response is sent back to the service() method that is finally sent to the user by the web
server.
3. Destroy
The web server may decide to remove a previously loaded servlet instance, perhaps because
it is explicitly asked to do so by the server administrator, or perhaps servlet container shuts
down or the servlet is idle for a long time, or may be the server is overloaded. Before it does,
however it calls the servlets destroy() method. This makes it a perfect spot for releasing
the acquired resources.
- 343 -
Handout 28
Web Design & Development CS-506
Summary
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.
- 344 -
Handout 28
Web Design & Development CS-506
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.
When a user submits a browser request to a web server, it sends two categories of data:
Form Data
Data, that the user explicitly type into an HTML form. For example: registration
information provided for creating a new email account.
- 345 -
Handout 28
Web Design & Development CS-506
Based on our understanding of HTML, we now know how to create user forms. We also
know how to gather user data via all the form controls: text, password, select, checkbox,
radio buttons, etc. Now, the question arises: if I submit form data to a Servlet, how do I
extract this form data from servlet? Figuring this out, provides the basis for creating
interactive web applications that respond to user requests.
Now let see how we can read data from “HTML form” using Servlet. The
HttpServletRequest object contains three main methods for extracting form data
submitted by the user:
getParameter(String name)
- Used to retrieve a single form parameter and returns String corresponding to name
specified.
- Empty String is returned in the case when user does not enter any thing in the
specified form field.
- If the name specified to retrieve the value does not exist, it returns null.
Note: You should only use this method when you are sure that the parameter has only
one value. If the parameter might have more than one value, use
getParamterValues().
getParameterValues(String name)
- Returns an array of Strings objects containing all of the given values of the given
request parameter.
- If the name specified does not exist, null is returned
getParameterNames()
- If you are unsure about the parameter names, this method will be helpful
- It returns Enumeration of String objects containing the names of the parameters that
come with the request.
- If the request has no parameters, the method returns an empty Enumeration.
Note: All these methods discussed above work the same way regardless of the request
type(GET or POST). Also remember that form elements are case sensitive for example,
“userName” is not the same as the “username.”
- 346 -
Handout 28
Web Design & Development CS-506
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>
- 347 -
Handout 28
Web Design & Development CS-506
<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>
</FORM>
</body>
</html>
Let’s discuss the code of above HTML form. As you can see in the <FORM> tag, the attribute
METHOD is set to “GET”. The possible values for this attribute can be GET and POST. Now
what do these values 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.
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
- 348 -
Handout 28
Web Design & Development CS-506
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.*;
out.close();
import java.io.*,
import javax.servlet.*;
import javax.servlet.http.*;
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.
- 349 -
Handout 28
Web Design & Development CS-506
Entering inside doGet() method brings the crux of the code. These are:
Two String variables fName and sName are declared that receive String values returned
by getParameter() method. As discussed earlier, this method returns String
corresponds 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:
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>
http://localhost:8084/paramapp/formservlet
- 350 -
Handout 28
Web Design & Development CS-506
References:
- 351 -
Handout 29
Web Design & Development CS-506
Lecture 29
More on Servlets
The objective of this handout is to learn about the use and implementation of initialization
parameters for a Servlet. Moreover different ways of redirecting response and forwarding or
including requests also discussed in detail.
Initialization Parameters
Some times at the time of starting up the application we need to provide some initial
information e,g, name of the file where server can store logging information, DSN for
database etc. Initial configuration can be defined for a Servlet by defining some string
parameters in web.xml. This allows a Servlet to have initial parameters from outside. This
is similar to providing command line parameters to a standard console based application.
</init-param>
</init-param>
In the above code, it is shown that for each parameter we need to define separate <init-
param> tag that have two sub tags <param-name> and <param-value>, which
contain the name and values of the parameter respectively.
- 352 -
Handout 29
Web Design & Development CS-506
ServletConfig
Every Servlet has an object called ServletConfig associated with it as shown in the fig.
below. It contains relevant information about the Servlet like initialization parameters
defined in web.xml
Now let’s see, how we can access init parameters inside the Servlet. The method
getInitParameter()of ServletConfig is usually used to access init parameters. It
takes a String as parameter, matches it with <param-name> tag under all
<init-param> tags and returns <param-value> from the web.xml
One way is to override init() method as shown in the code below. The
ServletConfig object can then be used to read initialization parameter.
Another way to read initialization parameters out side the init () method is
- 353 -
Handout 29
Web Design & Development CS-506
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
/*
Both doGet() & doPost() methods are override over here.
processRequest() is called from both these methods. This makes
possible for a servlet to handle both POST and GET requests
identically.
*/
- 354 -
Handout 29
Web Design & Development CS-506
out.close();
}
} // end MyServlet
web.xml
<servlet>
<servlet-name> MyServlet </servlet-name>
<servlet-class> MyServlet </servlet-class>
<init-param>
<param-name> logfilename </param-name>
<param-value> logoutput.txt </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name> MyServlet </servlet-name>
<url-pattern> /myservlet </url-pattern>
</servlet-mapping>
</web-app>
- 355 -
Handout 29
Web Design & Development CS-506
Response Redirection
We can redirect the response of the Servlet to another application resource (another Servlet,
an HTML page or a JSP) but the resource (URL) must be available to the calling Servlet, in
the same Servlet context (discussed later).
- SC_NOT_FOUND (404)
- SC_NO_CONTENT (204)
- SC_REQUEST_TIMEOUT (408)
- 356 -
Handout 29
Web Design & Development CS-506
login.html
This page contains two text fields; one for entering username and another for password. The
data from this page is submitted to MyServlet.java.
<html>
<body>
<h2> Please provide login details</h2>
<FROM METHOD="POST"
ACTION="http://localhost:8084/redirectionex/myservlet"
NAME="myForm" >
<BR> Password:
<INPUT TYPE="password" name="pwd"/>
<BR> <BR>
<input type="submit" value="Submit Form"/>
</form>
</body>
</html>
welcome.html
The user is directed to this page only if user provides correct login / password. This page
only displays a successfully logged-in message to the user.
<html>
<body>
<h2> You have successfully logged in </h2>
</body>
</html>
- 357 -
Handout 29
Web Design & Development CS-506
register.html
The user is redirected to this page in case of providing incorrect login/password information.
The user can enter user id, address and phone number here to register.
Note: The code given below will only show fields to the user. It does not register user as no
such functionality is added into this small example.
<html>
<body>
<h2>Your login is incorrect. Please register yourself</h2>
<BR> Name:
<INPUT TYPE="text" NAME="userid"/>
<BR> Address:
<INPUT TYPE="text" NAME="address"/>
<BR> <BR>
<input type="submit" value="Register"/>
</FORM>
</body>
</html>
MyServlet.java
- 358 -
Handout 29
Web Design & Development CS-506
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
} else {
// redirecting user to register.html
response.sendRedirect("register.html");
response.sendError(
response.SC_PROXY_AUTHENTICATION_REQUIRED,
"Send Error Demo" );
*/
} // end else
}
}
- 359 -
Handout 29
Web Design & Development CS-506
ServletContext
ServletContext belongs to one web application. Therefore it can be used for sharing
resources among servlets in the same web application.
Note:
o Different Sevlets will get the same ServletContext object, when calling
getServletContext() during different sessions
- 360 -
Handout 29
Web Design & Development CS-506
Request Dispatcher
RequestDispatcher: forward
Before forwarding request to another source, headers or status codes can be set, but
output content cannot be added.
To clarify the concepts, lets take the help from following figure. User initates the request to
servlet1. servlet1 forwards the request to servlet2 by calling forward(request,
response). Finally a response is returned back to the user by servlet2.
- 361 -
Handout 29
Web Design & Development CS-506
RequestDispatcher: include
It allows a Servlet to include the results of another resource in its response. The two major
differences from forward are:
It will be more cleared from the following figure. User sends a HTTPRequest to Servlet1.
Serlet2 is called by Servlet1 by using include(request, response) method. The
response generated by Servlet2 sends back to Servlet1. Servlet1 can also add its own
response content and finally send it back to user.
- 362 -
Handout 29
Web Design & Development CS-506
References:
- 363 -