Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture 28 29

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Web Design & Development CS-506

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

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.

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.

Initialize stage has the following characteristics and usage

♦ Executed once, when the servlet gets loaded for the first time

- 341 -
Handout 28
Web Design & Development CS-506

♦ 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.

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

• 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.

- 344 -
Handout 28
Web Design & Development CS-506

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.

Types of Data send to Web Server

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.

ƒ HTTP Request Header Data


Data, which is automatically, appended to the HTTP Request from the client for example,
cookies, browser type, and browser IP address.

- 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.

Reading HTML Form Data from Servlet

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

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>

- 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>

<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
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.

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">

- 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.*;

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 object


PrintWriter 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.

- 349 -
Handout 28
Web Design & Development CS-506

Entering inside doGet() method brings the crux of the code. These are:

String fName = req.getParameter(“firstName”);


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 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:

<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 <url-


patteren> 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

- 350 -
Handout 28
Web Design & Development CS-506

References:

ƒ JAVA a Lab Course by Umair Javed

ƒ Java API documentation

ƒ Core Servlets and JSP by Marty Hall

- 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.

Example: setting init parameters in web.xml

Let’s have a look on the way of defining these parameters in web.xml

<init-param> //defining param 1

<param-name> param1 </param-name>


<param-value> value1 </param-value>

</init-param>

<init-param> //defining param 2

<param-name> param2 </param-name>


<param-value> value2 </param-value>

</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

Reading Initialization Parameters

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.

public void init(ServletConfig config) throws ServletException {


String name = config.getInitParameter(“paramName”);
}

Another way to read initialization parameters out side the init () method is

• Call getServletConfig() to obtain the ServletConfig object


• Use getInitParameter() of ServletConfig to read initialization
parameters

public void anyMethod() // defined inside servlet


{
ServletConfig config = getServletConfig();
String name = config.getInitParameter(“param_name");
}

- 353 -
Handout 29
Web Design & Development CS-506

Example Code: Reading init parameters


MyServlet.java will read the init parameter (log file name) defined inside web.xml.
The code is given below:

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

public class MyServlet extends HttpServlet {

// attribute used to store init-parameter value


String fileName;

// overriding init() method


public void init(ServletConfig config) throws ServletException{
super.init(config);

// reading init-parameter “logfilename” stored in web.xml


fileName = config.getInitParameter("logfilename");
}

/*
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.
*/

// Handles the HTTP GET request type


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}

// Handles the HTTP POST request type


protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}

- 354 -
Handout 29
Web Design & Development CS-506

// called from doGet() & doPost()


protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();

// writing init-parameter value that is store in fileName


out.println(fileName);

out.close();
}

} // end MyServlet

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app>

<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).

There are two forms of response redirection that can be possible:

ƒ Sending a standard redirect


ƒ Sending a redirect to an error page

Sending a standard Redirect

ƒ Using response.sendRedirect(“myHtml.html”) method, a new request


is generated which redirects the user to the specified URL.
ƒ If the URL is of another Servlet, that second Servlet will not have access to the
original request object. For example, if the request is redirected from servlet1 to
servlet2, then servlet2 would not be able to access the request object of servlet1.
ƒ To have access to the original request object, you must use the request dispatching
technique (discussed later) instead of redirect.

Sending a redirect to an error page

Instead of using response.sendRedirect(), we can use


response.sendEorror() to show user an error page. This methods takes two
parameters, first the error number that is a predefined constant of the response class (listed
below) and second the appropriate error message. The steps to redirect the user to an error
page are:

ƒ An error code is sent as a parameter of response.sendError(int, msg)


method
ƒ The error page is displayed with the msg passed to method
ƒ The error numbers are predefined constants of the HttpServletResponse class.
For example:

- SC_NOT_FOUND (404)
- SC_NO_CONTENT (204)
- SC_REQUEST_TIMEOUT (408)

- 356 -
Handout 29
Web Design & Development CS-506

Example Code: Response Redirection


The example given below demonstrates a typical sign on example in which a user is asked to
provide login/password, providing correct information leads to welcome page or otherwise to
a registration page. This example consists of login.html, welcome.html, register.html and
MyServlet.java files. Let’s examine these one after another.

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> User Id:


<INPUT TYPE="text" name="userid"/>

<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>

<FORM METHOD="POST" ACTION="" NAME="myForm">

<BR> Name:
<INPUT TYPE="text" NAME="userid"/>

<BR> Address:
<INPUT TYPE="text" NAME="address"/>

<BR> Phone No:


<INPUT TYPE="text" NAME="phoneno"/>

<BR> <BR>
<input type="submit" value="Register"/>

</FORM>
</body>
</html>

MyServlet.java

MyServlet.java accepts requests from login.html and redirects the user to


welcome.html or register.html based on the verification of username & password
provided. Username & password are compared with fix values in this example, however you
can verify these from database or from a text file etc.

- 358 -
Handout 29
Web Design & Development CS-506

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

public class MyServlet extends HttpServlet {

// Handles the HTTP GET request type


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
// Handles the HTTP POST request type
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
String id = request.getParameter("userid");
String pwd = request.getParameter("pwd");

// comparing id & password with fix values


if(id.equals("ali") && pwd.equals("vu")) {

// redirectign user to welcome.html


response.sendRedirect("welcome.html");

} else {
// redirecting user to register.html
response.sendRedirect("register.html");

/* if you want to display an error message to the


user, you can use the following method

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.

As initialization parameters, for a single servlet are stored in ServletConfig, ServetContext


can store initialization parameters for the entire web application. These parameters are also
called context attributes and exist for the lifetime of the application. The following figure
illustrates the sharing of context attributes among all the servlets of a web application.

Note:

o There is a single ServletContext per web application

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 provides a way to forward or include data from another source.


The method getRequestDispatcher(String path) of ServletContext
returns a RequestDispatcher object associated with the resource at the given path
passed as a parameter.

Two important methods of RequestDispatcher are:

ƒ forward(ServletRequest req, ServletResponse resp)

ƒ include(ServletRequest req, ServletResponse resp)

RequestDispatcher: forward

Characteristics of forward methods are:

ƒ It allows a Servlet to forward the request to another resource (Servlet, JSP or


HTML file) in the same Servlet context.

ƒ Forwarding remains transparent to the client unlike


res.sendRedirect(String location). You can not see the changes in
the URL.

ƒ Request Object is available to the called resource. In other words, it remains in


scope.

ƒ 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:

ƒ Data can be written to the response before an include


ƒ The first Servlet which receive the request, is the one which finishes the response

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:

ƒ Java A Lab Course by Umair Javed


ƒ Core Servlets and JSP by Marty Hall
ƒ Java API documentation

- 363 -

You might also like