Tricky Servlet Interview Questions and Answers - 1

Question: 1

What are the different scopes an object can have in a JSP page?

There are four scope which an object can have in a JSP page.

Page Scope:

Objects with page scope are accessible only within the page. Data is only valid for the current response. Once the response is sent back to the browser after that data is no more valid. Even if request is passed from one page to other the data is lost.

Request Scope:

Objects with request scope are accessible from pages processing the same request in which they were created. Once the container has processed the request data is invalid. Even if the request is forwarded to another page, the data is still available.

Session Scope:

Objects with session scope are accessible in same session.

Session is the time users spend using the application, which ends when they close their browser or when they go another website.

Application Scope:

Application scope objects are basically global object and accessible to all JSP pages which lie in the same application. This creates a global object that’s available to all pages.

Application scope variables are typically created and populated when an application starts and then used as read only for the rest of the application.

Question: 2

How to track a user session in servlets?

The interface HTTPSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HTTPSession session = req.getSession(true).

Question: 3

What are the advantages of cookies over url rewriting?

Sessions tracking using Cookies are more secure and fast.

Session tracking using Cookies can also be used with other mechanisms of Session Tracking like url rewriting.

Cookies are stored at client side, so some clients may disable cookies, so we may not be sure whether the cookies will work or not.

In url rewriting large data transfer is required and to the server. So, it leads to network traffic and access may be becomes slow.

Question: 4

How you can destroy the session in servlet?

You can call invalidate() method on the session object to destroy the session. E.g. session.invalidate().

Question: 5

What is a session?

A session refers to all the requests that a single client makes to a server.

A session is specific to the user and for each user a new session is created to track all the requests from that user.

Every user has a separate session and a separate session variable is associated with that session.

In case of Web applications the default time out value for session variable is 20 minutes, which can be changed as per the requirement.

Related Questions