Servlets Lifecycle - Web Design and Development - Lecture Handouts, Lecture notes of Web Design and Development

Servlets Lifecycle, Stages of Servlet Lifecycle, Initialize, Service, Destroy, Reading HTML Form Data, HTML and Servlets, Types of Data send to Web Server, HTTP Request Header Data. Virtual University is one of best in Pakistan for distance education in science.

Typology: Lecture notes

2011/2012

Uploaded on 11/10/2012

taariq
taariq 🇵🇰

4.4

(16)

61 documents

1 / 11

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Web Design & Development CS-506
- 340 -
HANDOUTS
WEB DESIGN AND DEVELOPMENT
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Servlets Lifecycle - Web Design and Development - Lecture Handouts and more Lecture notes Web Design and Development in PDF only on Docsity!

Web Design & Development CS-

HANDOUTS

WEB DESIGN AND DEVELOPMENT

Web Design & Development CS-

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.

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

time

Web Design & Development CS-

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.

Web Design & Development CS-

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.

Web Design & Development CS-

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

Web Design & Development CS-

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.

Reading Two Parameters

Please fill out this form:

Web Design & Development CS-

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.

Web Design & Development CS-

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:

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

FormServlet MyServlet

FormServlet /formservlet

The tag contains two tags and containing name and pattern of the URL respectively. Recall the value of action attribute of the element in the HTML page. You can see it is exactly the same as mentioned in < url-pattern> tag.

http://localhost:8084/paramapp /formservlet