Friday, 10 August 2012

More on Servlets

Servlet Life Cycle
When the servlet is first created, it is in the initialization stage. The webserver invokes init() method of servlet in this stage. Here, init() is only called once and is not called for each request.
There is no constructor available in Servlet so this urges its use for one time initialization (loading of resources, setting of parameters etc).

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. This makes it more efficient as compared to the technologies that use single thread to respond to requests.
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. 
But before it does, it calls the servlets destroy() method for releasing the acquired resources.

How to Read HTML Form Data from Servlet ?
We can think HTML as a GUI for a Servlet.
The data that we enter in HTML form is transmitted to Servlet that can process this data. When we submits a browser request to web server, it sends two categories of data:

1) Form Data: Data that we explicitly type into HTML form. For example: registration information provided for creating a new email account.

2) HTTP Request Header Data: Data, which is automatically, appended to the HTTP Request from the client for example - cookies, browser type,  browser IP address...etc

HttpServletRequest object contains three main methods for extracting form data submitted by us:

1) getParameter(String name)

Used to retrieve a single form parameter and returns String corresponding to name specified. 
Empty String is returned in case when user does not enter anything in the specified form field.
If the name specified to retrieve the value does not exist, it returns null.

2) getParameterValues(String name)

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

3) getParameterNames()

If we r unsure about 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.

Example : Reading Form Data Using Servlet

Here i am showing a simple example which consists of one HTML page, one servlet and one web.xml (deployment descriptor). The HTML page contains two form parameters: firstName
and surName. The Servlet extracts these parameters and respond back to the
browser after appending “Hello”.

1) HTML file:

            <title> Reading Two Parameters </title>
            <H2> Please fill out this form: </H2>
            <FORM METHOD="GET"
            NAME="myform" >
            <BR> Firstname:
            <INPUT TYPE = “text” NAME="firstName">
            <BR> Surname:
            <INPUT TYPE = “text” NAME="surName">
            <INPUT TYPE="submit" value="Submit Form">
            <INPUT TYPE="reset" value="Reset">

2) Servlet code:

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
       String fName = req.getParameter(“firstName”);
    // reading surname parameter
       String sName = req.getParameter(“surName”);

    // gettting stream from HttpServletResponse object
       PrintWriter out = res.getWriter();
       out.println("Hello: " + fName + “ “ +sName ");

3) web.xml:

       <?xml version="1.0" encoding="ISO-8859-1"?>

                     <servlet-name> FormServlet </servlet-name>
                     <servlet-class> MyServlet </servlet-class>
                     <servlet-name> FormServlet </servlet-name>
                     <url-pattern> /formservlet </url-pattern>

No comments:

Post a Comment