Tuesday, May 1, 2012

Introduction to Servlets


Introduction to Servlets

Some Example Applications

A few of the many applications for servlets include,
  • Processing data POSTed over HTTPS using an HTML form, including purchase order or credit card data. A servlet like this could be part of an order-entry and processing system, working with product and inventory databases, and perhaps an on-line payment system.
  • Allowing collaboration between people. A servlet can handle multiple requests concurrently; they can synchronize requests to support systems such as on-line conferencing.
  • Forwarding requests. Servlets can forward requests to other servers and servlets. This allows them to be used to balance load among several servers that mirror the same content. It also allows them to be used to partition a single logical service over several servers, according to task type or organizational boundaries.

Servlet Architecture Overview

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet. The inheritance hierarchy looks as follows.
The Servlet interface provides the following methods that manage the servlet and its communications with clients.
  • destroy()
    Cleans up whatever resources are being held and makes sure that any persistent state is synchronized with the servlet's current in-memory state.
  • getServletConfig()
    Returns a servlet config object, which contains any initialization parameters and startup configuration for this servlet.
  • getServletInfo()
    Returns a string containing information about the servlet, such as its author, version, and copyright.
  • init(ServletConfig)
    Initializes the servlet. Run once before any requests can be serviced.
  • service(ServletRequest, ServletResponse)
    Carries out a single request from the client.
Servlet writers provide some or all of these methods when developing a servlet.
When a servlet accepts a service call from a client, it receives two objects, ServletRequest and ServletResponse. The ServletRequest class encapsulates the communication from the client to the server, while the ServletResponse class encapsulates the communication from the servlet back to the client.
The ServletRequest interface allows the servlet access to information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. It also provides the servlet with access to the input stream,ServletInputStream, through which the servlet gets data from clients that are using application protocols such as the HTTP POST and PUT methods. Subclasses of ServletRequest allow the servlet to retrieve more protocol-specific data. For example, HttpServletRequest contains methods for accessing HTTP-specific header information.
The ServletResponse interface gives the servlet methods for replying to the client. It allows the servlet to set the content length and mime type of the reply, and provides an output stream, ServletOutputStream, and a Writer through which the servlet can send the reply data. Subclasses of ServletResponse give the servlet more protocol-specific capabilities. For example, HttpServletResponse contains methods that allow the servlet to manipulate HTTP-specific header information.
The classes and interfaces described above make up a basic Servlet. HTTP servlets have some additional objects that provide session-tracking capabilities. The servlet writer can use these APIs to maintain state between the servlet and the client that persists across multiple connections during some time period.

Servlet Lifecycle

Servers load and run servlets, which then accept zero or more requests from clients and return data to them. They can also remove servlets. These are the steps of a servlets lifecycle. The next paragraphs describe each step in more detail, concentrating on concurrency issues.
When a server loads a servlet, it runs the servlet's init method. Even though most servlets are run in multi-threaded servers, there are no concurrency issues during servlet initialization. This is because the server calls the init method once, when it loads the servlet, and will not call it again unless it is reloading the servlet. The server can not reload a servlet until after it has removed the servlet by calling the destroy method. Initialization is allowed to complete before client requests are handled (that is, before the service method is called) or the servlet is destroyed.
After the server loads and initializes the servlet, the servlet is able to handle client requests. It processes them in its service method. Each client's request has its call to the service method run in its own servlet thread: the method receives the client's request, and sends the client its response.
Servlets can run multiple service methods at a time. It is important, therefore, that service methods be written in a thread-safe manner. If, for some reason, a server should not run multiple service methods concurrently, the servlet should implement the SingleThreadModel interface. This interface guarantees that no two threads will execute the servlet's service methods concurrently.
Servlets run until they are removed from the service. When a server removes a servlet, it runs the servlet's destroy method. The method is run once; the server will not run it again until after it reloads and reinitializes the servlet.
The diagram below shows the basic interactions between clients, a web server, and a servlet registered with the web server.
When the destroy method runs, however, other threads might be running service requests. If, in cleaning up, it is necessary to access shared resources, that access should be synchronized. During a servlet's lifecycle, it is important to write thread-safe code for destroying the servlet and, unless the servlet implements theSingleThreadModel interface, servicing client requests.

Writing the Servlet

Servlets implement the javax.servlet.Servlet interface. While servlet writers can develop servlets by implementing the interface directly, this is usually not required. Because most servlets extend web servers that use the HTTP protocol to interact with clients, the most common way to develop servlets is by specializing the javax.servlet.http.HttpServlet class. This tutorial concentrates on describing this method of writing servlets.
The HttpServlet class implements the Servlet interface by extending the GenericServlet base class, and provides a framework for handling the HTTP protocol. Itsservice method supports standard HTTP/1.1 requests by dispatching each request to a method designed to handle it.
By default, servlets written by specializing the HttpServlet class can have multiple threads concurrently running its service method. If, you would like to have only a single thread running a single service method at a time, then in addition to extending the HttpServlet, your servlet should also implement theSingleThreadModel interface. This does not involve writing any extra methods, merely declaring that the servlet implements the interface.
For example,

public class SurveyServlet extends HttpServlet
                           implements SingleThreadModel {

    /* typical servlet code, with no threading concerns
     * in the service method.  No extra code for the
     * SingleThreadModel interface.  */
    ...

}

Interacting with Clients

Servlet writers who are developing HTTP servlets that specialize the HttpServlet class should override the method or methods designed to handle the HTTP interactions that their servlet will handle. The candidate methods include,
  • doGet, for handling GET, conditional GET and HEAD requests
  • doPost, for handling POST requests
  • doPut, for handling PUT requests
  • doDelete, for handling DELETE requests
By default, these methods return a BAD_REQUEST (400) error. An example HTTP servlet that handles GET and HEAD requests follows; it specializes the doGetmethod. The second example is also provided. It handles POST requests from a form by specializing the doPost method.
The HttpServlet's service method, by default, also calls the doOptions method when it receives an OPTIONS request, and doTrace when it receives a TRACE request. The default implementation of doOptions automatically determines what HTTP options are supported and returns that information. The default implementation of doTrace causes a response with a message containing all of the headers sent in the trace request. These methods are not typically overridden.
Whatever method you override, it will take two arguments. The first encapsulates the data from the client, and is an HttpServletRequest. The second encapsulates the response to the client, and is an HttpServletResponse. The following paragraphs discuss their use.
An HttpServletRequest object provides access to HTTP header data, such as any cookies found in the request and the HTTP method with which the request was made. It, of course, allows the you to obtain the arguments that the client sent as part of the request. How you access the client data might depend on the HTTP method of the request.
  • For any HTTP method, you can use the getParameterValues method, which will return the value of a named parameter. (The methodgetParameterNames provides the names of the parameters.) You can also manually parse the request.
  • For requests using the HTTP GET method, the getQueryString method will return a String to be parsed.
  • For HTTP methods POST, PUT, and DELETE, you have the choice between two methods. If you expect text data, then it can be read using theBufferedReader returned by the getReader method, if you expect binary data, then it should be read with the ServletInputStream returned by thegetInputStream method.
Note that you should use either the getParameterValues method or one of the methods that allow you to parse the data yourself. They can not be used together in a single request.
For responding to the client, an HttpServletResponse object provides two ways of returning the response data to the user. You can use the writer returned by thegetWriter method or the output stream returned by the getOutputStream method. You should use getWriter to return text data to the user, andgetOutputStream for binary data.
Before accessing the Writer or OutputStream, HTTP header data should be set. The HttpServletResponse class provides methods to access the header data, such as the content type and encoding, and content length of the response. After you set the headers, you may obtain the writer or output stream and send the body of the response to the user. Closing the writer or output stream after sending the response to the client allows the server to know when the response is complete.

Example of an HTTP Servlet that handles the GET and HEAD methods

/**
 * This is a simple example of an HTTP Servlet.  It responds to the GET
 * and HEAD methods of the HTTP protocol.
 */
public class SimpleServlet extends HttpServlet { 

    public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
        // set header field first
        res.setContentType("text/html");

        // then get the writer and write the response data
        PrintWriter out = res.getWriter();
        out.println("<HEAD><TITLE> SimpleServlet Output</TITLE></HEAD><BODY>");
        out.println("<h1> SimpleServlet Output </h1>");
        out.println("<P>This is output is from SimpleServlet.");
 out.println("</BODY>");
 out.close();
    }

    public String getServletInfo() {
        return "A simple servlet";
    }

}
The example above shows the code for the entire servlet. The doGet method, because it is returning text to the client, uses the HttpServletResponse'sgetWriter method. It sets the response header field, content type, before writing the body of the response, and closes the writer after writing the response.
In addition to doGet, there is a second method, getServletInfo. More information on the getServletInfo method appears in later section. Because this servlet is an example shipped with the release, it is already compiled. To try the servlet, run it in the servletrunner section.

Example of an HTTP Servlet that handles the POST method

The following example processes data POSTed by a form. The form looks like this:
<html>
  <head><title>JdcSurvey</title></head>
  <body>
    <form action=http://demo:8080/servlet/survey method=POST>
      <input type=hidden name=survey value=Survey01Results>

      <BR><BR>How Many Employees in your Company?<BR>
        <BR>1-100<input type=radio name=employee value=1-100>
        <BR>100-200<input type=radio name=employee value=100-200>
        <BR>200-300<input type=radio name=employee value=200-300>
        <BR>300-400<input type=radio name=employee value=300-400>
        <BR>500-more<input type=radio name=employee value=500-more>

      <BR><BR>General Comments?<BR>
        <BR><input type=text name=comment>

      <BR><BR>What IDEs do you use?<BR>
        <BR>JavaWorkShop<input type=checkbox name=ide value=JavaWorkShop>
        <BR>J++<input type=checkbox name=ide value=J++>
        <BR>Cafe'<input type=checkbox name=ide value=Cafe'>

      <BR><BR><input type=submit><input type=reset>
    </form>
  </body>
</html>
The servlet writes the form data to a file, and responds to the user with a thank you message. The doPost method of the servlet looks like this:
    /**
     * Write survey results to output file in response to the POSTed
     * form.  Write a "thank you" to the client.     
     */
    public void doPost(HttpServletRequest req, HttpServletResponse res)
 throws ServletException, IOException {
 // first, set the "content type" header of the response
 res.setContentType("text/html");

 //Get the response's PrintWriter to return text to the client.
        PrintWriter toClient = res.getWriter();

        try {
            //Open the file for writing the survey results.
            String surveyName = req.getParameterValues("survey")[0];
            FileWriter resultsFile = new FileWriter(resultsDir
         + System.getProperty("file.separator")
         + surveyName + ".txt", true);
            PrintWriter toFile = new PrintWriter(resultsFile);

     // Get client's form data & store it in the file
            toFile.println("<BEGIN>");
            Enumeration values = req.getParameterNames();
            while(values.hasMoreElements()) {
                String name = (String)values.nextElement();
  String value = req.getParameterValues(name)[0];
                if(name.compareTo("submit") != 0) {
                    toFile.println(name + ": " + value);
                }
            }
            toFile.println("<END>");

     //Close the file.
            resultsFile.close();

     // Respond to client with a thank you
     toClient.println("<html>");
     toClient.println("<title>Thank you!</title>");
            toClient.println("Thank you for participating");
     toClient.println("</html>");

        } catch(IOException e) {
            e.printStackTrace();
            toClient.println(
  "A problem occured while recording your answers.  "
  + "Please try again.");
        }

        // Close the writer; the response is done.
 toClient.close();
    }
The doPost method uses the getParameterNames and getParameterValues methods to get the form data. Because it returns text to the client, doPost calls thegetWriter method. It sets the sets the response header field, content type, before writing the body of the response, and closes the writer when the response is complete.

Lifecycle Methods

Servlets that manage resources do so by overriding the lifecycle methods init and destroy. These servlets might need to be given arguments at startup, in order to initialize correctly.

Overriding the Init Method

During initialization, the servlet should prepare the resources it manages, to ready the servlet for accepting service requests. It can do this without regard for multi-threading concerns, since there is only a single thread running on behalf of the servlet during initialization. As soon as the init method returns, the servlet can receive client requests. If, for some reason, the servlet's required resources can not be made available (for example, a required network connection can not be established), or some other initialization error occurs that would make it impossible for the servlet to handle requests, the init method should throw an UnavailableExceptionexception.
The init method takes a ServletConfig object as a parameter. The method should save this object, so that it can be returned by the getServletConfigmethod. The simplest way to do this is to have the new init method call super.init. If you do not do this, you should store the ServletConfig object yourself, and override the getServletConfig method so that it can obtain the object from its new location.
An example init method follows. It is the init method from the Survey Servlet, which accepts input from a form and stores it in a file. In order store the survey information, it needs a directory. It receives the directory as an initialization parameter; initialization parameters are discussed in the next section.
    public void init(ServletConfig config)
 throws ServletException
    {
 super.init(config);

        //Store the directory that will hold the survey-results files
        resultsDir = getInitParameter("resultsDir");

        //If no directory was provided, can't handle clients
 if (resultsDir == null) {
     throw new UnavailableException (this,
  "Not given a directory to write survey results!");
 }

As you can see, this init method calls the super.init method to manage the ServletConfig object. The init method also sets a field, resultsDir, with the directory name that is provided as an initialization parameter. If no directory name was provided, the servlet throws an unavailable exception. If the init method completes successfully, the servlet can then handle client requests.

Initialization Parameters

The specification of initialization parameters is server-specific. For example, they are specified with a property when a servlet is run with the servlet runner. This tutorial contains a general explanation of properties, and how to create them.
However the initialization parameters are specified, they are always obtained the same way: with the getInitParameter method. This method takes the parameter name as an argument. The example init method calls getInitParameter. If, for some reason, you need to get the parameter names, you can get them with thegetParameterNames method.

Overriding the Destroy Method

When a server unloads a servlet, it calls the servlet's destroy method. The destroy method should undo any initialization work and synchronize persistent state with the current in-memory state. This section begins with a description of how to write a simple destroy method, then describes how to structure a servlet if threads running its service method might still be running when the destroy method is called.
Though it is often the case that a servlet that overrides the init method must also override the destroy method to undo that initialization, this is not required. Because initialization involves reading a file and using its contents to initialize a shared data structure, there is no work to undo when the server is finished with the servlet.
For many servlets, however, there is initialization work that must be undone. For example, assume there is a servlet that opens a database connection during initialization. Its destroy method, shown as an example below, would close that connection.
    /**
     * Cleans up database connection
     */
    public void destroy() {
        try {
            con.close();
        } catch (SQLException e) {
            while(e != null) {
  log("SQLException: " + e.getSQLState() + '\t' +
      e.getMessage() + '\t' +
      e.getErrorCode() + '\t');
  e = e.getNextException();
            }
        } catch (Exception e) {
     e.printStackTrace();
 }
    }
Coping with Service Threads at Servlet Termination
When a server removes a servlet, it typically calls destroy after all service calls have been completed, or a server-specific number of seconds have passed, whichever comes first. If your servlet has operations that take a long time to run (that is, they may run longer than the server's grace period), then threads could still be running when destroy is called. The servlet writer is responsible for making sure that any threads still handling client requests complete. The remainder of this section describes a technique for doing this.
A servlet with potentially long-running service requests should keep track of how many service methods are currently running. Its long-running methods should periodically poll to make sure that they should continue to run. If the servlet is being destroyed, then the long-running method should stop working, clean up if necessary, and return.
For example, the instance variable that counts the number of service methods running could be called serviceCounter, and the indicator of whether the servlet is being destroyed could be an instance variable called shuttingDown. Each variable should have its own set of access methods:
public ShutdownExample extends HttpServlet {
private int serviceCounter = 0; private Boolean shuttingDown; ... //Access methods for serviceCounter protected synchronized void enteringServiceMethod() { serviceCounter++; } protected synchronized void leavingServiceMethod() { serviceCounter--; } protected synchronized int numServices() { return serviceCounter; } //Access methods for shuttingDown protected setShuttingDown(Boolean flag) { shuttingDown = flag; } protected Boolean isShuttingDown() { return shuttingDown; } }
The service method should increment the service counter each time it is entered and decrement it each time it returns:
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
 enteringServiceMethod();
 try {
            super.service(req, resp);
        } finally {
            leavingServiceMethod();
        }
    }
The destroy method should check the serviceCounter, and if there are any long-running methods, set the shuttingDown variable. This variable will let the threads still handling client requests know that it is time to shut down. The destroy method should then wait for the service methods to complete, in order to provide a clean shutdown.
    public void destroy() {
        /* Check to see whether there are still service methods running,
  * and if there are, tell them to stop. */
 if (numServices() > 0) {
     setShuttingDown(true);
        }

 /* Wait for the service methods to stop.  */
 while(numService() > 0) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e) {
            }
        }
    }

Providing Information about the Servlet

Some applets and applications, for example, the Java Web Server Administration Tool, display information about a servlet. This information can include a short description of the purpose of the servlet, its author, and perhaps its version number. The Servlet API provides a method to return this information,getServletInfo. By default, this method returns null. While servlet writers are not required to override this method, it is strongly recommended. The simple servlet, shown as an example earlier, overrides this method:
/**
 * This is a simple example of an HTTP Servlet.  It responds to the GET
 * and HEAD methods of the HTTP protocol.
 */
public class SimpleServlet extends HttpServlet { 

   ...

    public String getServletInfo() {
        return "A simple servlet";
    }
}

How to use servletrunner to Run a Servlet

Once you have written your servlet, you can run it in many web servers, or in the servletrunner. Where ever you decide to run your servlet, there are certain pieces of data that you might want or need to specify. When you are using servletrunner you do this with properties. The next section describes a servlet's properties, and how to store them. Following that, there is a section on how to run servlets in servletrunner.

Properties

Properties are key-value pairs, used for the configuration, creation, and initialization of a servlet. For example, servlet.Assignment.code=AssignmentServletis a property whose key is servlet.Assignment.code and whose value is AssignmentServlet.
There are two properties for servlets. One is servlet.name.code, whose value is the servlet's class name. The other property is servlet.name.initargs, whose value holds the initialization parameters for the servlet. Both properties, servlet.name.code and servlet.name.initargs, are discussed in more detail below.
The servlet.name.code property names your servlet by associating its name with its class. If your servlet uses initialization parameters, this property is required. It allows the server to associate the servlet object with its initialization arguments: they both have the same name. Even if your servlet does not use initialization parameters, it is recommended that it have this property, so that clients can access the servlet using its name.
The value of the servlet.name.initArgs property holds the servlet's initialization parameters. The syntax of a single parameter is parameterName=parameterValue. The entire property (the entire key-value pair) must be a single logical line. For readability, you can use the backquote syntax to allow the property to span multiple lines in the file. For example, the argument to the Assignment servlet looks like this:
servlet.Assignment.initArgs=\
        AssignmentParameter=ParameterValue
The Property File
Properties are stored in a file that is, by default, called "servlet.properties", though you can specify another name when servletrunner is started. The file should hold the properties for all the servlets that servletrunner will run. It should be plain text. You can create it in an editor.

Using Servlet Runner

If you would like to run your servlet in a web server, please see that server's documentation for instructions. This section explains how to run the servlet in theservletrunner utility that comes with this release.
The servletrunner is a small utility, intended for testing. It is multithreaded, so it can run more than one servlet. It can be used, therefore, to run multiple servlets simultaneously, or to test one servlet that calls other servlets in order to satisfy client requests. Unlike some web servers, it does not automatically reload servlets when they are updated. Because it is small, however, there is very little overhead associated with stopping and restarting it in order to use a new version of a servlet.
The servletrunner is in the <JDK>/bin directory. Invoking it with the -help flag shows a usage message without running it:
% ./bin/servletrunner -help
Usage: servletrunner [options] Options: -p port the port number to listen on -b backlog the listen backlog -m max maximum number of connection handlers -t timeout connection timeout in milliseconds -d dir servlet directory -r root document root directory -s filename servlet property file name -v verbose output %
In order to see the default values of these options, you can call servletrunner with the -v switch. This will, however, start the servlet runner. Just stop it after you have obtained the information, if you are not ready to run it yet, or want it to run with something other than the default values.
Suppose we choose port 5050. Then we can start servletrunner as follows.
./bin/servletrunner -p 5050 -d . -r . &
Once the servletrunner is executing, you run servlets by calling them directly in your browser, or as the forms example shows, by using a form that calls a servlet to process its data. The URL for a servlet has the following general form:
http://machine-name:port/servlet/servlet-name
where servlet-name corresponds to the name you have given your servlet. For example, to run the Assignment Servlet, which has the propertyservlet.Assignment.code=AssignmentServlet, you would use the following URL. (It assumes that servletrunner is running on machine(info.cse.iitb.ac.in), at port 5050, and that the Assignment servlet is located in the servlet directory provided to servletrunner at startup:
http://info.cse.iitb.ac.in:5050/servlet/Assignment


                                                                     
                                                                     
                                                                     
                                             
http://www.istutorials.com/java.htm
http://www.interview-questions-java.com/
http://www.javaprogrammingworld.com/
http://www.daniweb.com/
http://kickjava.com/
http://www.java-samples.com
http://videoworld-rong.blogspot.com
http://www.itjungle.com
http://klavanya.wordpress.com
http://www.sitepoint.com/forums
http://articles.sitepoint.com
http://www.johntopley.com/
http://bitmeta.org/
http://www.java201.com
http://www.corej2eepatterns.com
http://www.cs.wcupa.edu/rkline/Java/jstl-examples.html
http://www.experts-exchange.com
http://www.developer.com/
http://www.devsphere.com/
http://www.ngri.org.in/alkacon-documentation/examples_jstl/
http://www.kodejava.org
http://technosatish.blogspot.com/
http://www.exampledepot.com
http://www.datadirect.com
http://jobz9.com/
http://www.mainframegurukul.com/
http://www.alexwestconsulting.com
http://www.orafaq.com/
http://www.objecttraininggroup.com/
www.seekjava.info
www.freewebschools.com
http://javapapers.com
http://java-j2ee-interview-questions.blogspot.com/
http://www.java-questions.com/
http://java-interview-questions-bank.blogspot.com
http://www.codeproject.com/
http://www.codegravity.com/
http://www.javadb.com/
http://www.devdaily.com/java/
http://www.devdaily.com/java/java-developer-jobs-programming-jobs
http://pronetbeans.com/
http://demo.raibledesigns.com/struts-menu/index.jsp
http://www.devarticles.com
http://passion4java.blogspot.com

Servlet Overview and Architecture

  • client sends an HTTP request to the server . The server receives the request and directs it to be processed by the appropriateservletThe servlet does its processing, which may include interacting with a database or other server-side components such as other servlets, JSPs or Enterprise Java-Beans. The servlet returns its results to the client—normally in the form of an HTML, XHTML or XML document to display in a browser, but other data formats, such as images and binary data, can be returned.
Servlet Life Cycle
  • All servlets must implement the Servlet interface. As with many key applet methods, the methods of interface Servlet are invokedautomatically by the server. This interface defines five methods :
void init( ServletConfig config )
This method is automatically called once during a servlet’s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet.
ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet’s configuration information such as servlet initialization parameters and the servlet’s ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes).
String getServletInfo()
This method is defined by a servlet programmer to return a String containing servlet information such as the servlet’s author and version.
void service( ServletRequest request, ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet.
void destroy()
This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as an open file or an open database connection, should be deallocated here.
  • A servlet’s life cycle begins when the servlet container loads the servlet into memory—normally, in response to the first request that the servlet receives.
  • Before the servlet can handle that request, the servlet container invokes the servlet’s init method.
  • After init completes execution, the servlet can respond to its first request.
  • All requests are handled by a servlet’s service method, which receives the request, processes the request and sends a response to the client.
  • During a servlet’s life cycle, method service is called once per request. Each new request typically results in a new thread of execution (created by the servlet container) in which method service executes.
  • Starting a new thread for each request is more efficient than starting an entirely new process,
  • When the servlet container terminates the servlet, the servlet’s destroy method is called to release servlet resources.
  • The servlet packages define two abstract classes that implement the interface Servlet—class GenericServlet (from the packagejavax.servlet) and class HttpServlet (from the package javax.servlet.http). These classes provide default implementations of all theServlet methods. Most servlets extend either GenericServlet or HttpServlet and override some or all of their methods.
  • The key method in every servlet is service, which receives both a ServletRequest object and a ServletResponse object. These objects provide access to input and output streams that allow the servlet to read data from the client and send data to the client. These streams can be either byte based or character based. If problems occur during the execution of a servlet, either ServletExceptions or IOExceptionsare thrown to indicate the problem.
  • Servlets can implement tagging interface javax.servlet.SingleThreadModel to indicate that only one thread of execution may enter method service on a particular servlet
    instance at a time. When a servlet implements SingleThreadModel, the servlet container can create multiple instances of the servlet to handle multiple requests to the servlet
    in parallel. In this case, you may need to provide synchronized access to shared resources used by method service.
HttpServlet Class
  • public abstract class HttpServlet extends GenericServlet
  • GenericServlet implements interface javax.servlet.Servlet.
  • Class HttpServlet overrides method service to distinguish between the typical requests received from a client Web browser.
HTTP request types
 description
 Common uses
getA get request gets (or retrieves) information from a server.retrieve content of a specified URL such as HTML , XHTML document (i.e., a Web page) or an image.
postA post request posts (or sends) data to a server.send information, such as authentication information or data from a form that obtains user input, to a server.
  • Class HttpServlet defines methods doGet and doPost to respond to get and post requests from a client, respectively.
  • These methods are called by the service method, which is called when a request arrives at the server.
  • Method service first determines the request type, then calls the appropriate method for handling such a request.
public void service(ServletRequest req,ServletResponse res)
Dispatches client requests to the protected service method. There's no need to override this method.
protected void service(HttpServletRequest req,
HttpServletResponse resp)
Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP-specific version of the Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) method. There's no need to override this method.
Do not override method service in an HttpServlet subclass. Doing so prevents the servlet from distinguishing between request types.
  • Methods of class HttpServlet that respond to the other request types are shown in the next figure. They all receive parameters of typeHttpServletRequest and HttpServletResponse and return void.
  • Methods doGet and doPost receive as arguments an HttpServletRequest object and an HttpServletResponse object that enable interaction between the client and the server.
    • The methods of HttpServletRequest make it easy to access the data supplied as part of the request.
    • The HttpServletResponse methods make it easy to return the servlet’s results to the Web client.
MethodDescription
doDeleteCalled in response to an HTTP delete request. Such a request is normally used to delete a file from a server. This may not be available on some servers, because of its inherent security risks (i.e., the client could delete a file that is critical to the execution of the server or an application).
doOptionsCalled in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such as the
version of HTTP (1.0 or 1.1) and the request methods the server supports.
doPutCalled in response to an HTTP put request. Such a request is normally used to store a file on the server. This may not be available on some servers,
because of its inherent security risks (i.e., the client could place an executable application on the server, which, if executed, could damage the server—
perhaps by deleting critical files or occupying resources).
doTrace
Called in response to an HTTP trace request. Such a request is normally used for debugging. The implementation of this method automatically
returns an HTML document to the client containing the request header information (data sent by the browser as part of the request).


HttpServletRequest Interface
  • Every call to doGet or doPost for an HttpServlet receives an object that implements interface HttpServletRequest.
  • The Web server that executes the servlet creates an HttpServletRequest object and passes this to the servlet’s service method (which, in turn, passes it to doGet or doPost)
  • This object contains the request from the client. A variety of methods are provided to enable the servlet to process the client’s request. Some of these methods are from interface ServletRequest—the interface that HttpServletRequest extends.
MethodDescription
String getParameter( String name )Obtains the value of a parameter sent to the servlet as part of a get or post request. The name argument represents the parameter name.
Enumeration getParameterNames()Returns the names of all the parameters sent to the servlet as part of a post request.
String[] getParameterValues( String name )For a parameter with multiple values, this method returns an array of Strings containing the values for a specified servlet parameter.
Cookie[] getCookies()Returns an array of Cookie objects stored on the client by the server. Cookies can be used to uniquely identify clients to the servlet.
HttpSession getSession( boolean create )Returns an HttpSession object associated with the client’s current browsing session. An HttpSession object can be created by this method (true argument) if an HttpSession object does not already exist for the client. HttpSession objects can be used in similar ways to Cookies for uniquely identifying clients.

 
HttpServletResponse Interface
  • This object contains the response from the server.
void addCookie( Cookie cookie )Used to add a Cookie to the header of the response to the client. The Cookie’s maximum age and whether Cookies are enabled on the client determine if Cookies are stored on the client.
ServletOutputStream getOutputStream()Obtains a byte-based output stream for sending binary data to the client.
PrintWriter getWriter()Obtains a character-based output stream for sending text data to the client.
void setContentType( String type )Specifies the MIME type of the response to the browser. The MIME type helps the browser determine how to display the data (or possibly what other application to execute to process the data). For example, MIME type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page. For more information on

Thread Life Cycle


Thread is a lightweight process, the smallest unit of scheduled execution. Instance of the Thread class in Java 6 could be in one of the following states:
  • new,
  • runnable,
  • timed waiting,
  • waiting,
  • blocked,
  • terminated.
These states are Java Virtual Machine (JVM) states reported by JVM to Java programs. At any given point in time thread could be in only one state.
Protocol state machine example - Thread States and Life Cycle in Java 6.
Protocol State Machine Example - Thread States and Life Cycle in Java 6
New is the thread state for a thread which was created but has not yet started.
At the lower operating system (OS) level, JVM’s runnable state could be considered as a composite state with two substates. When a thread transitions to the runnable JVM state, the thread first goes into the ready substate. Thread scheduling decides when the thread could actually start, proceed or be suspended. Thread.yield() is explicit recommendation to thread scheduler to pause the currently executing thread to allow some other thread to execute.
A thread in the runnable state is executing from the JVM point of view but in fact it may be waiting for some resources from the operating system.
Timed waiting is a thread state for a thread waiting with a specified waiting time. A thread is in the timed waiting state due to calling one of the following methods with a specified positive waiting time:
  • Thread.sleep(sleeptime)
  • Object.wait(timeout)
  • Thread.join(timeout)
  • LockSupport.parkNanos(timeout)
  • LockSupport.parkUntil(timeout)
A thread is in the waiting state due to the calling one of the following methods without timeout:
  • Object.wait()
  • Thread.join()
  • LockSupport.park()
Note, that thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate. It means that waiting state could be made a composite state with states corresponding to these specific conditions.
Thread is in the blocked state while waiting for the monitor lock to enter a synchronized block or method or to reenter a synchronized block or method after calling Object.wait().
A synchronized statement or method acquires a mutual-exclusion lock on behalf of the executing thread, executes a block or method, and then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock and is blocked waiting for the lock.
After thread has completed execution of run() method, it is moved into terminated state.

Monday, April 30, 2012

Servlets Interview Questions


1) Is it the “servlets” directory or the “servlet” directory?

For Java Web Server:
    • on the file system, it’s “servlets”
c:\JavaWebServer1.1\servlets\DateServlet.class
    • in a URL path, it’s “servlet”
http://www.stinky.com/servlet/DateServlet

2) How do I support both GET and POST protocol from the same Servlet?

The easy way is, just support POST, then have your doGet method call your doPost method:
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } 

3) How do I ensure that my servlet is thread-safe?

This is actually a very complex issue. A few guidelines:
    1. The init() method is guaranteed to be called once per servlet instance, when the servlet is loaded. You don’t have to worry about thread safety inside this method, since it is only called by a single thread, and the web server will wait until that thread exits before sending any more threads into your service() method.
    2. Every new client request generates (or allocates) a new thread; that thread calls the service() method of your servlet (which may in turn call doPost(), doGet() and so forth).
    3. Under most circumstances, there is only one instance of your servlet, no matter how many client requests are in process. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other’s toes. This means that you should be careful to synchronize access to shared data (instance variables) using the synchronized keyword.
(Note that the server will also allocate a new instance if you register the servlet with a new name and, e.g., new init parameters.)
    1. Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn’t synchronize the service() method! (Or doPost(), doGet() et al.)
    2. A simple solution to synchronizing is to always synchronize on the servlet instance itself using &quot;synchronized (this) { … }&quot;. However, this can lead to performance bottlenecks; you’re usually better off synchronizing on the data objects themselves.
    3. If you absolutely can’t deal with synchronizing, you can declare that your servlet &quot;implements SingleThreadModel&quot;. This empty interface tells the web server to only send one client request at a time into your servlet. From the JavaDoc: &quot;If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe.&quot; Note that this is not an ideal solution, since performance may suffer (depending on the size of the instance pool), plus it’s more difficult to share data across instances than within a single instance.
  1. To share data across successive or concurrent requests, you can use either instance variables or class-static variables, or use Session Tracking.
  2. The destroy() method is not necessarily as clean as the init() method. The server calls destroy either after all service calls have been completed, or after a certain number of seconds have passed, whichever comes first. This means that other threads might be running service requests at the same time as your destroy() method is called! So be sure to synchronize, and/or wait for the other requests to quit. Sun’s Servlet Tutorial has an example of how to do this with reference counting.
  3. destroy() can not throw an exception, so if something bad happens, call log() with a helpful message (like the exception). See the &quot;closing a JDBC connection&quot; example in Sun’s Tutorial.

4) What is the difference between URL encoding, URL rewriting, HTML escaping, and entity encoding?

URL Encoding is a process of transforming user input to a CGI form so it is fit for travel across the network — basically, stripping spaces and punctuation and replacing with escape characters. URL Decoding is the reverse process. To perform these operations, call java.net.URLEncoder.encode() and java.net.URLDecoder.decode() (the latter was (finally!) added to JDK 1.2, aka Java 2).
Example: changing “We’re #1!” into “We%27re+%231%21″
URL Rewriting is a technique for saving state information on the user’s browser between page hits. It’s sort of like cookies, only the information gets stored inside the URL, as an additional parameter. The HttpSession API, which is part of the Servlet API, sometimes uses URL Rewriting when cookies are unavailable.
Example: changing <A HREF=”nextpage.html”> into
<A HREF=”nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE”> (or whatever the actual syntax is; I forget offhand)
(Unfortunately, the method in the Servlet API for doing URL rewriting for session management is called encodeURL(). Sigh…)
There’s also a feature of the Apache web server called URL Rewriting; it is enabled by the mod_rewrite module. It rewrites URLs on their way in to the server, allowing you to do things like automatically add a trailing slash to a directory name, or to map old file names to new file names. This has nothing to do with servlets. For more information, see the Apache FAQ (http://www.apache.org/docs/misc/FAQ.html#rewrite-more-config) .

5) How do I upload a file to my servlet or JSP?

On the client side, the client’s browser must support form-based upload. Most modern browsers do, but there’s no guarantee. For example,
 <FORM ENCTYPE='multipart/form-data' method='POST' action='/myservlet'> <INPUT TYPE='file' NAME='mptest'> <INPUT TYPE='submit' VALUE='upload'> </FORM> 
The input type &quot;file&quot; brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse.
When the user clicks the “Upload” button, the client browser locates the local file and sends it using HTTP POST, encoded using the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in RFC 1867.
Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream.
Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See How can I access or create a file or folder in the current directory from inside a servlet? and other questions in the Servlets:Files Topic for information on writing files from a Servlet.
Please note that you can’t access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that.

6) How does a servlet communicate with a JSP page?

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
 public void doPost (HttpServletRequest request, HttpServletResponse response) { try { govi.FormBean f = new govi.FormBean(); String id = request.getParameter("id"); f.setName(request.getParameter("name")); f.setAddr(request.getParameter("addr")); f.setAge(request.getParameter("age")); //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . . f.setPersonalizationInfo(info); request.setAttribute("fBean",f); getServletConfig().getServletContext().getRequestDispatcher ("/jsp/Bean1.jsp").forward(request, response); } catch (Exception ex) { . . . } } 
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.
 <jsp:useBean id="fBean" class="govi.FormBean" scope="request"/> <jsp:getProperty name="fBean" property="name" /> <jsp:getProperty name="fBean" property="addr" /> <jsp:getProperty name="fBean" property="age" /> <jsp:getProperty name="fBean" property="personalizationInfo" /> 

7) What’s a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?

Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server’s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free – which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

8) Can a servlet maintain a JTA UserTransaction object across multiple servlet invocations?

No. A JTA transaction must start and finish within a single invocation (of the service() method). Note that this question does not address servlets that maintain and manipulate JDBC connections, including a connection’s transaction handling.

9) How does the performance of JSP pages compare with that of servlets? How does it compare with Perl scripts?

The performance of JSP pages is very close to that of servlets. However, users may experience a perceptible delay when a JSP page is accessed for the very first time. This is because the JSP page undergoes a “translation phase” wherein it is converted into a servlet by the JSP engine. Once this servlet is dynamically compiled and loaded into memory, it follows the servlet life cycle for request processing. Here, the jspInit() method is automatically invoked by the JSP engine upon loading the servlet, followed by the _jspService() method, which is responsible for request processing and replying to the client. Do note that the lifetime of this servlet is non-deterministic – it may be removed from memory at any time by the JSP engine for resource-related reasons. When this happens, the JSP engine automatically invokes the jspDestroy() method allowing the servlet to free any previously allocated resources.
Subsequent client requests to the JSP page do not result in a repeat of the translation phase as long as the servlet is cached in memory, and are directly handled by the servlet’s service() method in a concurrent fashion (i.e. the service() method handles each client request within a seperate thread concurrently.)
There have been some recent studies contrasting the performance of servlets with Perl scripts running in a “real-life” environment. The results are favorable to servlets, especially when they are running in a clustered environment.

10) How do I call one servlet from another servlet?

[ Short answer: there are several ways to do this, including
  • use a RequestDispatcher
  • use a URLConnection or HTTPClient
  • send a redirect
  • call getServletContext().getServlet(name) (deprecated, doesn't work in 2.1+)
- Alex ]
It depends on what you mean by “call” and what it is you seek to do and why you seek to do it.
If the end result needed is to invoke the methods then the simplest mechanism would be to treat the servlet like any java object , create an instance and call the mehods.
If the idea is to call the service method from the service method of another servlet, AKA forwarding the request, you could use the RequestDispatcher object.
If, however, you want to gain access to the instance of the servlet that has been loaded into memory by the servlet engine, you have to know the alias of the servlet. (How it is defined depends on the engine.) For example, to invoke a servlet in JSDK a servlet can be named by the property
 myname.code=com.sameer.servlets.MyServlet 
The code below shows how this named servlet can be accessed in the service method of another servlet
 public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... MyServlet ms=(MyServlet) getServletConfig().getServletContext().getServlet("myname"); ... } 
That said, This whole apporach of accessing servlets in another servlets has been deprecated in the 2.1 version of the servlet API due to the security issues. The cleaner and better apporach is to just avoid accessing other servlets directly and use the RequestDispatcher instead.

11) What are all the different kinds of servers? (Such as Web Servers, Application Servers, etc)

The servers involved in handling and processing a user’s request break down into a few basic types, each of which may have one or more tasks it solves. This flexibility gives developers a great deal of power over how applications will be created and deployed, but also leads to confusion over what server is able to, or should, perform a specific task.
Starting at the basic level, a user is typically submitting a request to a system through a web browser. (We are conveniently ignoring all other types of clients (RMI, CORBA, COM/DCOM, Custom, etc..) for the time being for purposes of clarity.) The web request must be received by a Web Server (otherwise known as an HTTP Server) of some sort. This web server must handle standard HTTP requests and responses, typically returning HTML to the calling user. Code that executes within the server environment may be CGI driven, Servlets, ASP, or some other server-side programming language, but the end result is that the web server will pass back HTML to the user.
The web server may need to execute an application in response to the users request. It may be generating a list of news items, or handling a form submission to a guest book. If the server application is written as a Java Servlet, it will need a place to execute, and this place is typically called a Servlet Engine. Depending on the web server, this engine may be internal, external, or a completely different product. This engine is continually running, unlike a traditional CGI environment where a CGI script is started upon each request to the server. This persistance gives a servlet connection and thread pooling, as well as an easy way to maintain state between each HTTP request. JSP pages are usually tied in with the servlet engine, and would execute within the same space/application as the servlets.
There are many products that handle the web serving and the servlet engine in different manners. Netscape/iPlanet Enterprise Server builds the servlet engine directly into the web server and runs within the same process space. Apache requires that a servlet engine run in an external process, and will communicate to the engine via TCP/IP sockets. Other servers, such as MS IIS don’t officially support servlets, and require add-on products to add that capability.
When you move on to Enterprise JavaBeans (and other J2EE components like JMS and CORBA) you move into the application server space. An Application Server is any server that supplies additional functionality related to enterprise computing — for instance, load balancing, database access classes, transaction processing, messaging, and so on.
EJB Application Servers provide an EJB container, which is the environment that beans will execute in, and this container will manage transactions, thread pools, and other issues as necessary. These application servers are usually stand-alone products, and developers would tie their servlets/JSP pages to the EJB components via remote object access APIs. Depending on the application server, programmers may use CORBA or RMI to talk to their beans, but the baseline standard is to use JNDI to locate and create EJB references as necessary.
Now, one thing that confuses the issue is that many application server providers include some or all of these components in their product. If you look at WebLogic (http://www.beasys.com/) you will find that WebLogic contains a web server, servlet engine, JSP processor, JMS facility, as well as an EJB container. Theoretically a product like this could be used to handle all aspects of site development. In practice, you would most likely use this type of product to manage/serve EJB instances, while dedicated web servers handle the specific HTTP requests.

12) Should I override the service() method?

No. It provides a fair bit of housekeeping that you’d just have to do yourself. If you need to do something regardless of whether the request is e.g., a POST or a GET, create a helper method and call that at the beginning of e.g., doPost() and doGet().

13) How can my application get to know when a HttpSession is removed (when it time-outs)?

Define a class, say SessionTimeoutNotifier, that implements javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutNotifier object and add it to the user session. When the session is removed, SessionTimeoutNotifier.valueUnbound() will be called by the servlet engine. You can implement valueUnbound() to do whatever you want.

14) Why use JSP when we can do the same thing with servlets?

[Original question: Why should I use JSP when there is already servlet technology available for serving dynamic content?]
While JSP may be great for serving up dynamic Web content and separating content from presentation, some may still wonder why servlets should be cast aside for JSP. The utility of servlets is not in question. They are excellent for server-side processing, and, with their significant installed base, are here to stay. In fact, architecturally speaking, you can view JSP as a high-level abstraction of servlets that is implemented as an extension of the Servlet 2.1 API. Still, you shouldn’t use servlets indiscriminately; they may not be appropriate for everyone. For instance, while page designers can easily write a JSP page using conventional HTML or XML tools, servlets are more suited for back-end developers because they are often written using an IDE — a process that generally requires a higher level of programming expertise.
When deploying servlets, even developers have to be careful and ensure that there is no tight coupling between presentation and content. You can usually do this by adding a third-party HTML wrapper package like htmlKona to the mix. But even this approach, though providing some flexibility with simple screen changes, still does not shield you from a change in the presentation format itself. For example, if your presentation changed from HTML to DHTML, you would still need to ensure that wrapper packages were compliant with the new format. In a worst-case scenario, if a wrapper package is not available, you may end up hardcoding the presentation within the dynamic content. So, what is the solution? One approach would be to use both JSP and servlet technologies for building application systems.

15) How do I send information and data back and forth between applet and servlet using the HTTP protocol?

Use the standard java.net.URL class, or “roll your own” using java.net.Socket. See the HTTP spec at W3C for more detail.
Note: The servlet cannot initiate this connection! If the servlet needs to asynchronously send a message to the applet, then you must open up a persistent socket using java.net.Socket (on the applet side), and java.net.ServerSocket and Threads (on the server side).

16) Can I get the path of the current servlet where it lives on the file system (not its URL)?

Try using:
 request.getRealPath(request.getServletPath()) 
An example may be:
 out.println(request.getRealPath(request.getServletPath())); 

17) How can I daisy chain servlets together such that the output of one servlet serves as the input to the next?

There are two common methods for chaining the output of one servlet to another servlet :
  1. the first method is the aliasing which describes a series of servlets to be executed
  2. the second one is to define a new MIME-Type and associate a servlet as handlers As I don’t really use the second one, I’ll focus on the aliasing.
To chain servlets together, you have to specify a sequential list of servlets and associate it to an alias. When a request is made to this alias, the first servlet in the list is invoked, processed its task and sent the ouptut to the next servlet in the list as the request object. The output can be sent again to another servlets.
To accomplish this method, you need to configure your servlet engine (JRun, JavaWeb server, JServ …).
For example to configure JRun for servlet chaining, you select the JSE service (JRun servlet engine) to access to the JSE Service Config panel. You have just to define a new mapping rule where you define your chaining servlet.
Let say /servlets/chainServlet for the virtual path and a comma separated list of servlets as srvA,srvB.
So when you invoke a request like http://localhost/servlets/chainServlet, internally the servlet srvA will be invoked first and its results will be piped into the servlet srvB.
The srvA servlet code should look like :
 public class srvA extends HttpServlet { ... public void doGet (...) { PrintWriter out =res.getWriter(); rest.setContentType("text/html"); ... out.println("Hello Chaining servlet"); } } 
All the servlet srvB has to do is to open an input stream to the request object and read the data into a BufferedReader object as for example :
 BufferedReader b = new BufferedReader( new InputStreamReader(req.getInputStream() ) ); String data = b.readLine(); b.close(); 
After that you can format your output with the data.
It should work straigthforward with Java Web Server or Jserv too. Just look at in their documentation to define an alias name. Hope that it’ll help.

18) Why there are no constructors in servlets?

A servlet is just like an applet in the respect that it has an init() method that acts as a constrcutor. Since the servlet environment takes care of instantiating the servlet, an explicit constructor is not needed. Any initialization code you need to run should be placed in the init() method since it gets called when the servlet is first loaded by the servlet container.

19) How to handle multiple concurrent database requests/updates when using JDBC with servlets?

All the dbms provide the facility of locks whenever the data is being modified. There can be two scenarios:
  1. Multiple database updates on different rows, if you are using servlets the servlets will open multiple connections for different users. In this case there is no need to do additional programming.
  2. If database updates are on the same row then the rows are locked automatically by the dbms, hence we have to send requests to the dbms repeatatively until the lock is released by dbms.
This issue is dealt with in the JDBC documentation; look up “Transactions” and “auto-commit”. It can get pretty confusing.

20) What is the difference between GenericServlet and HttpServlet?

GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets. Of course, it turns out that there’s no such thing as FTP servlets, but they were trying to plan for future growth when they designed the spec. Maybe some day there will be another subclass, but for now, always use HttpServlet.

21) How do you share session objects between servlets and JSP?

Sharing sessions between a servlet and a JSP page is straight forward. JSP makes it a little easy by creating a session object and making it availabe already. In a servlet you would have to do it yourself. This is how:
 //create a session if one is not created already now HttpSession session = request.getSession(true); //assign the session variable to a value. session.putValue("variable","value"); 
in the jsp page this is how you get the session value:
 <% session.getValue("varible"); %> 

22) What is a servlet?

A servlet is a way of extending your web server with a Java program to perform tasks previously dealt with by CGI scripts or proprietary server extension frameworks.

23) Is there any method to unload a servlet from Web Server memory without restarting the server?

There is no standard method/mechanism to unload a servlet from memory. Some servers, like JWS, provide the means to load and unload servlets from their administration module. Others, like Tomcat, require you to just replace the WAR file.

24) What distinguishes a JavaBean from a Servlet?

JavaBeans are a set of rules to follow to create reusable software components, or beans. This contains properties and events. At the end you have a component which could be examined by a program (like an IDE) to allow the user of your JavaBean component to configure it and to run in its Java programs.
Servlets are Java classes running in a Servlet engine implementing a particular interface: Servlet, forcing you to implement some methods (service()). The servlet is an extension of your web server where this servlet is running on and only lets you know when a user requests a GET or POST calls from a web page to your servlet.
So, both have nothing in common except Java.

25) How much data we can store in a session object?

Any amount of data can be stored there because the session is kept on the server side.
The only limitation is sessionId length, which shouldn’t exceed ~4000 bytes – this limitation is implied by HTTP header length limitation to 4Kb since sessionId may be stored in the cookie or encoded in URL (using “URL rewriting“) and the cookie specification says the size of cookie as well as HTTP request (e.g. GET /document.html\n) cannot be longer then 4kb.