Wednesday, October 3, 2007

Important Questions on Servlets along with Answers!

Q What is a servlet? Explain its lifecyle.

A The Servlets are server side java programs, which are used to generate dynamic web content for a web clients. They reside inside a servlet container on a web server or an application server. The servlet container provides them a runtime environment.

If an instance of servlet is non existent then web container loads the servlet class and creates an instance of the servlet.Once the servlet instantiates, web container calls init() method on it to initialize the servlet.This process of initialization can be customized to allow servlet to read persistent configuration data,initialize resources like database connections etc. by overriding init() method of Servlet interface.If initialization of a servelet fails it throws UnavailableException.

Once initialization is done, web container invokes the service method, passing a request and response object depending upon incoming request.

If the container needs to remove the servlet(e.g.when web container is shutting down), it finalizes the servlet by calling the servlet's destroy method.

The javax.servlet.Servlet interface defines the three life-cycle method:-

public void init(ServletConfig config) throws ServletException

public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException

public void destroy()


Q What is the difference between CGI and servlets?

A In traditional CGI, a new process is started with each client request and this will correspond to initiating a heavy OS level process each time when a client request comes. While in case of servlets JVM handles client requests at a web server end and each client request correspond to thread which consumes less resources as compared with CGI process, thus making CGI inefficient. In Java servlet, there is only a single instance, which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.Java servlets resides in Servlet engine and are executed within sandbox making it more secure and robust.


Q What is a middleware and what is the functionality of Webserver?

A A middleware in a 3-tier architecture sits in the middle of a client's machine and a database server. A middleware is where all the business related logic resides and it is also known as Web Application Server. (e.g. WebLogic from BEA, WebSphere from IBM, Oracle 9iAS from Oracle etc.)In distributed programming divide and rule is the name of the game and in this paradigm a middleware has a good share of responsibilities viz. load balancing, database connection pooling, security, transaction management related services, web and enterprise component deployment services, content management related services etc.


Q Can there be more than one instance of a servlet at one time ?

A It is important to note that there can be more than one instance of a given Servlet class in the servlet container. For example, this can occur where there was more than one servlet definition that utilized a specific servlet class with different initialization parameters. This can also occur when a servlet implements the SingleThreadModel interface and the container creates a pool of servlet instances to use.


Q Why there are no constructors in servlets?

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


Q What is a Servlet Context?

A A ServletContext interface empowers a servlet to view its environment. A servlet can use this interface to get following informations:

- Initial Web Application Parameters
- Application Scope for binding objects
- Virtual Directory Translation
- A common mechanism for Logging information

Each vendor provides specific ServletContext object but they all provide the same functionality defined by the ServletContext interface.


Q What is meant by Session tell me something about HttpSession?

A A web client makes a request to a web server over HTTP. As long as a client interacts with the server through a browser on his or her machine,this interaction is called as session. HTTP is a stateless protocol. A client's each request is treated as a fresh one with no info of client to the server and the moment browser is closed, session is also closed. In an online shopping or web cart kind of application where session related information is critical for successive purchases made by a client, there have been suggested several techniques for session tracking in Java Servlets as mentioned below:

-Hidden form fields
-URL Rewriting
-Cookies
-HttpSession object

HttpSession is an interface, which belongs to javax.servlet.http. * package This provides a facility to identify a user across the several pages' requests by looking up the HttpSession object associated with the current request.
This is done by calling the getSession method of HttpServletRequest. If this returns null, you can create a new session, but this is so commonly done that there is an option to automatically create a new session if there isn't one already. Just pass true to getSession. Thus, your first step usually looks like this:

HttpSession session = request.getSession (true);

To ensure the session is properly maintained, this method must be called at least once before any output is written to the response.

You can add data to an HttpSession object with the putValue() method:

public void HttpSession.putValue(String name, Object value)

This method binds the specified object value under the specified name. Any existing binding with the same name is replaced.

To retrieve an object from a session, use getValue():

public Object HttpSession.getValue(String name)

This methods returns the object bound under the specified name or null if there is no binding.

You can also get the names of all of the objects bound to a session with getValueNames():

public String[] HttpSession.getValueNames()

This method returns an array that contains the names of all objects bound to this session or an empty (zero length) array if there are no bindings.

Finally, you can remove an object from a session with removeValue():

public void HttpSession.removeValue(String name)

This method removes the object bound to the specified name or does nothing if there is no binding. Each of these methods can throw a java.lang.IllegalStateException if the session being accessed is invalid.


Q What is the difference between GenericServlet and HTTPServlet?

A GenericServlet is an abstract class that defines a generic, protocol-independent servlet.Any protocol dependent servlet has to extend this class in order to provide a specific implementaion and override service method.e.g . HTTPServlet class extends GenericServlet class.

GenericServlet has a service(ServletRequest req, ServletResponse res) method which is called by the servlet container to allow the servlet to respond to a request.

HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.


Q What is the difference between doGet and doPost methods of HttpSe?

A A GET or POST request is sent to servlet in order to expedite the request by calling corresponding doGet() and doPost() methods.
doGet is called in response to an HTTP GET request. This happens when users click on a link, or enter a URL into the browser's address bar. It also happens with some HTML FORMs (those with METHOD="GET" specified in the FORM tag).
doPost is called in response to an HTTP POST request. This happens with some HTML FORMs (those with METHOD="POST" specified in the FORM tag).
Both methods are called by the default (superclass) implementation of service in the HttpServlet base class. You should override one or both to perform your servlet's actions. You probably shouldn't override service().
There is a restriction of numbers of parameters to be sent through doGet method around 2k of data can be sent and moreover whole of URL is to be mentioned in case of doGet as mentioned below:
http://www.xyz.com/servlet?param1=value1&param2=value2&...&paramN=valueN
So it is always better to use doPost() when sending parameters from a FORM as it doesn't show off information related with password on the network etc.


Q Why do GenericServlet and HttpServlet class implement Serializable interface?

A In order to support HTTP session states, all servlet session data must be serializable.Moreover, servlets need to communicate over the network to Java objects(e.g. in Applet-Servlet communication),in such scenarios it becomes necessary to enable serialization of objects' states through implementation of Serializable interface.This is the way GenericServlet and HttpServlet classes have been designed by their designers to make them capable of serialization.


No comments: