Thursday, December 3, 2009

Servlets Interview Question

Which code line must be set before any of the lines that use the PrintWriter?

setContentType() method must be set.

Which protocol will be used by browser and servlet to communicate ?

HTTP

In how many ways we can track the sessions?

Method1) By URL rewriting

Method2) Using Session object

Getting Session form HttpServletRequest object
HttpSession session = request.getSession(true);

Get a Value from the session
session.getValue(session.getId());

Adding values to session
cart = new Cart();
session.putValue(session.getId(), cart);

At the end of the session, we can inactivate the session by using the following command
session.invalidate();

Method 3) Using cookies

Method 4) Using hidden fields

How Can You invoke other web resources (or other servlet / jsp ) ?

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.

Example:
RequestDispatcher dispatcher = request.getRequestDispatcher("/jspsample.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}

How Can you 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.

Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner");
            if (dispatcher != null)
            dispatcher.include(request, response);
}

  1

2

3

No comments:

Post a Comment