Thursday, March 20, 2008

Interview Questions On Java Servlets

What is a servlet? Explain its lifecyle.

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

What is the difference between CGI and servlets?

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.

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

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.

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

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.

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.

What is a Servlet Context?

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.

What is meant by Session tell me something about HttpSession?

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.

What is the difference between GenericServlet and HTTPServlet?


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.


What is the difference between doGet and doPost methods of HttpServlet?



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.


Why do GenericServlet and HttpServlet class implement Serializable interface?

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.

How will you pass values from HTML to the servlet?

The values from an HTML page are passed to a servlet either through a GET or POST method. In a servlet, request.getParameter ("strParam") method is called in order to retrieve values from HTML form to a servlet end where String strParam represents the name of the input type OR values can be passed concatenated with URL itself which request the servlets receive.

Can you use System.exit in your servlet end code?

All the best...just kidding.The answer is big 'No'.At best, you'll get a security exception.At worst, you'll make the servlet engine, or maybe the entire web server, quit.


If my browser does not support Cookie and my server sends a Cookie instance what will happen?

In such scenario, browser will not accept incoming cookie. Whenever the browser sends the new request,it will not send the session id to server.As client has not joined to server session through cookie,server will not have any information about client in such a way. However,session tracking could still be preformed by using URL rewriting or hidden form fields.

What is the difference in between encodeRedirectURL and encodeURL

encodeURL is used for all URLs in a servlet's output. It helps session ids to be encoded with the URL. Moreover it rewrites URLs relative to the current document.if the url is not starting with 'http//.' and encodes any parameters added with the request.addQueryParameter or request.addURLParameter methods.As per Servlet API the encodeRedirectURL must ALWAYS be used within response.sendRedirect() commands.It is used for encoding session ids with URL but only while redirecting.

How do you make servlet thread-safe?

SingleThreadModel interface once implemented makes a servlet thread safe,though not in complete sense.It ensures that servlet handles only one request at a time. In this case only one thread will be able to execute service() method at a time.Though it affects the performance of the servlet to a great extent. In STM container creates multiple instances of servlet.This interface is deprecated from Servlet API version 2.4.
It does not resolve all thread safety related issues of a servlet, as most of session attributes and static variables can still be shared across multiple threads at the same time.The other ways to handle such situations can be avoid creating instance variables or synchronizing the block of code accessing those resources.

How do you communicate between applet and servlet?

The communication between an Applet and Servlet can occur through 'Http Tunneling' with Object serialization.It is technique through which an applet can send data to servlet through object serialization bypassing firewall over HTTP.A socket connection is established from client to server and in the process if there is any firewall at client side then that can also be bypassed but does not work in case if there is a firewall on remote host server side.

Q: Explain the life cycle methods of a Servlet.
A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.


Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.

Q: Explain the directory structure of a web application.
A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory


Q: What are the common mechanisms used for session tracking?
A: Cookies
SSL sessions
URL- rewriting

Q: Explain ServletContext.
A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

Q: What is preinitialization of a servlet?
A: A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.


Q: What is the difference between Difference between doGet() and doPost()?
A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.

Q: What is the difference between HttpServlet and GenericServlet?
A: A GenericServlet has a service() method aimed to handle requests. 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 ServletContext and ServletConfig?
A: ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized

ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

http://interviewjava.blogspot.com/2007/04/session-tracking-in-servlets.html

http://interviewjava.blogspot.com/2007/04/more-on-applet-servlet-communication.html

No comments:

Books

  • Hibernate in Action
  • Spring in Action