Difficult Servlet Interview Questions

a) How do you get the count of how many times the Servlet was accessed?
Ans: Use Filters and in the doFilter() method, mantain a counter which gets stored in the servletContext.

b) How do you get the no. of users who accessed your application?
Ans: Use HttpSessionListener and increment/decrement the userCount variable which gets stored in the servletContext on the sessionCreated() and sessionDestroyed() method.

c) What is the life cycle of ServletContextListener?
Ans: contextInitialized() and contextDestroyed()

d) What is the life cycle of Filter?
Ans: init, doFilter, destroy

e) What is the difference between Page and PageContext?(Courtesy:Suman)
Ans: page and pageContext are implicit variables.
page : page is of class java.lang.Object,and it refers to instance of generated servlet.It is declared as
Object page=this;
// this refers to the instance of this servlet page cannot be used to directly call the servlet methods.
Usages of Page:
1) Error bcoz page is Object type
2) <%=((servlet)page).getServletInfo()%> <—-OK:typecast
3) <%=this.getServletInfo()%> <——-OK

pageContext :
pageContext is of type javax.servlet.jsp.PageContext.
pageContext class is an abstract class.
Usages of PageContext:
1) provide convenience methods to get and set attributes in diff scopes.
2) provide convenience methods for transfering requests to other resources in the web application
void include(String relativeURL) & void forward(String relativeURL)
e.g. pageContext.forward(“suman.jsp”);
3)store the references to implicit objects

e) How do you ensure that a user session is closed , when actually the user has closed the browser window without logging out explicity?
Ans: In HttpSession, you have a method by the name getLastAccessedTime() which can be used to identify the in-active period and invalidate the session by calling session.inValidate()

f) What are the attributes of a ConnectionPool?
Ans: Click here

g) How do you download a file from a Servlet?
Ans: Click here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s