Servlet interview questions

Explain the mechanishm by which we can generate PDF’S dynamically in servlets?

This can be achieved using iText. A open source library for java. You can refer sourceforge site for sample servlet examples.

Explain the difference between the getRequestDispatcher(String path) ServletRequest interface and ServletContext interface?

The getRequestDispatcher(String path) method of 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 ServletContext interface cannot accepts relative paths. All path must sart with a “/” and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.

Explain the way by which you can include other Resources in the Response.?

Using include method of a RequestDispatcher object.
Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response.
Eg :

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(”/banner”);
if (dispatcher != null)
dispatcher.include(request, response);

Is there a way you can invoke other web resources (or other servelt / jsp ) ?

Yes, there is a mechanism. Servelt can invoke other Web resources in two ways: indirect and direct.
Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)
Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.
You can get this object using getRequestDispatcher(”URL”) method. You can get this object from either a request or a Context.
Eg :

RequestDispatcher dispatcher = request.getRequestDispatcher(”/jspsample.jsp”);
if (dispatcher != null)
dispatcher.forward(request, response);

What do you mean by preinitialization of a Servlet?

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 <load-on-startup> 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  .