Pages

Tuesday, May 15, 2012

Servlet Interview Questions

 1.What is a Servlet?
            Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities to the web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun's write once run anywhere technology java servlets provide excellent framework for server side processing.

 2.What are the types of Servlet?
         There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality linke doGet and doPost methods. 


 3.Why do servlets have an init method? Can't we make use of the servlet constructor for initialization?

 You can't make use of the constructor because the container calls it and therefore you can't pass any parameters to the constructor. Also at the point the constructor is called the class is not really a Servlet because it doesn't have a reference to the ServletConfig, which provides all the initialisation parameters etc.

Because the servlet container manages the servlet lifecycle, one should never call the constructor, the init and destroy methods.

4.Can we use the constructor, instead of init(), to initialize servlet?

Yes , of course you can use the constructor instead of init(). There's nothing to stop you. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext

5.Servlet Life Cycle ?

 The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

If an instance of the servlet does not exist, the Web container
  1. Loads the servlet class.
  2. Creates an instance of the servlet class. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.
  3. Invokes the service method, passing a request and response object. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.
  4. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.

6.What is the difference between HttpServlet and GenericServlet?

HttpServlet
Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

doGet, if the servlet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
doOptions, for HTTP OPTIONS requests
doTrace, for HTTP TRACE requests

init and destroy, to manage resources that are held for the life of the servlet
getServletInfo, which the servlet uses to provide information about itself



GenericServlet
Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.

GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it?s more common to extend a protocol-specific subclass such as HttpServlet.

GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface.

To write a generic servlet, you need only override the abstract service method.

7.What is load-on-startup in servlet ?

On server startup servlet will be called by the server.
the value 1 in  < load-on-startup > 1 < /load-on-startup >  specifies the order in which the servlet must be loaded by the server..

if you have 2 servlet you can specify  < load-on-startup > 2 < /load-on-startup >  for the next servlet

Below is the servlet tag entry in web.xml:

<servlet>
<servlet-name > InitServlet < /servlet-name>
<servlet-class > util.InitServlet < /servlet-class>
<load-on-startup > 1 < /load-on-startup>
</servlet>

8.Can we override init() or init(ServletConfig) method of HttpServlet ? Which is better ?

Before start we have to understand the servlet flow.
For example you have servlet LoginServlet which extends HttpServlet

public class LoginServlet extends HttpServlet{
}

And your HttpServlet internally extends GenericServlet.

public abstract class GenericServlet  implements Servlet, ServletConfig, Serializable
{

public GenericServlet()
{
}
public void init() throws ServletException
{
}
public void init(ServletConfig config)  throws ServletException
{
this.config = config;
init();
}
public ServletConfig getServletConfig()
{
return config;
}

public abstract void service(ServletRequest servletrequest, ServletResponse servletresponse)  throws ServletException, IOException;

private transient ServletConfig config;

}

Now servlet container flow

Step 1. Loads the servlet class and create instance of the servlet class (LoginServlet).
LoginServlet login = new LoginServlet();

Step 2. Then servlet container create ServletConfig object for that servlet and
Call login.init(ServletConfig);

Case 1 :
If you have overridden init(ServletConfig) method in your servlet then call goes to your
init(ServletConfig) method .

public void init(ServletConfig config) throws ServletException {
System.out.println("\n**** Initializing LoginServlet Init Servlet ********** \n");
super.init(config);
}

It will print "Initializing LoginServlet Init Servlet" and call goes to supper class GenericServlet init(ServletConfig) method.

In the GenericServlet init(ServletConfig) method there is code
This.config= config // initialize the Servlet config object and it is available to you.

Case 2 :
If you overridden init() method and not overridden init(ServletConfig) method.

Servlet container call login.init(ServletConfig);

There is no method like init(ServletConfig) in your servlet so call directly goes to super class GenericServlet init(ServletConfig) method.

This.config= config // initialize the Servlet config object and it is available to you.

You can get the Servlet config object using getServletConfig() method.


Conclusion: It is BETTER to use init(). If you use init() you have no such worries as calling super.init().

If you use init(servletconfig) and forgot to call super.init(config) then servletconfig object will not set and you will not get the servletconfig object.

9.How can I use servlets with protocols other than HTTP, e.g. FTP?

The javadocs for javax.servlet.Servlet and GenericServlet make it sound as if protocols other than HTTP can be used simply by extending GenericServlet, and implementing the methods that deal with the protocol, much like HttpServlet does for HTTP. That is not the case. The protocol needs to be supported by the servlet engine (which does all the network handling for the servlet), and no servlet engine exists that supports anything other than HTTP(S). Adding a different protocol would be a big project, especially since other protocols don't have the same request/response nature of HTTP. If you find yourself contemplating such a project, post your requirements to the Servlet forum, and a better solution will probably be suggested.

For JSPs, the specification says "Most JSP pages use the HTTP protocol, but other protocols are allowed by this specification.". Since a non-HTTP JSP implementation would depend on a non-HTTP servlet implementation, that too is just a theoretical possibility.

(Note that all of this has nothing to do with a servlet's ability to be a client for other protocols. E.g., by using the JavaMail or Jakarta Commons Net APIs a servlet can access SMTP and FTP servers without problems.)


10.What is servlet container?

The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.

11.When a client request is sent to the servlet container, how does the container choose which servlet to invoke?

The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
For Example---

<servlet>
<servlet-name > admin < /servlet-name>
<servlet-class > com.servlet.LoginServlet < /servlet-class>
</servlet>

<servlet-mapping>
     < servlet-name >  admin  < /servlet-name>
     < url-pattern > /artadmin < /url-pattern>
</servlet-mapping>

if the url in browser is
http://localhost:8080/artadmin

then server will call LoginServlet. Based on the above mapping.

12. What is the difference between ServletContext and ServletConfig?

ServletConfig is a servlet configuration object used by a servlet container used to pass information to a servlet during initialization. All of its initialization parameters can ONLY be set in deployment descriptor.

The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. You can specify param-value pairs for ServletContext object in  < context-param >  tags in web.xml file.

The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.

The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application.

13.What is the difference between Difference between doGet() and doPost()?

Difference between Difference between doGet() and doPost() --
1) by default httpservlet will call doGet method
if you mention method=post then only doPost() method will be called.

2) doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation

3) if your action is
http://localhost:8080/adminservlet  and method = get then action will be like
http:// localhost:8080/adminservlet?cmd=test&name=satya .all the form data you can see on address bar.

In case of doPost you can't see the data.

14.Explain the directory structure of a web application

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


15.What is a Session?

A Session refers to all the request 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 request from that user. Every user has a separate session and 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.

16.What is Session ID?

A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages. 




17.What is Session Tracking?

HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time. 


18.What are the common mechanisms used for session tracking?

  1. Cookies - Must be cookie on to your browser
  2. http session object - it used jsession id internally
  3. URL- rewriting - append variables to url
  4. Hidden variable - you can use hidden variable to track

All methods just send some value to server every time and check it is same or not. if it is same then session maintains.


19.What is HTTPSession Class?

HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user. 



20.Why do u use Session Tracking in HttpServlet?

 In HttpServlet you can use Session Tracking to track the user state. Session is required if you are developing shopping cart application or in any e-commerce application.



21.What are the advantage of Cookies over URL rewriting?

Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.


        Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not. 


        In url  rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.

22.What's the difference between response.sendRedirect() and requestDispatcher.forward() ?

response.sendRedirect() :
This is complete new request to browser.
Request is not maintained so data stored in request object not avilable to redirect page.
You have to store data in session to get in the reditect jsp.
You can pass data like response.sendRedirect("/login.jsp?name=satya). then in the login.jsp you have to get name using request.getParameter("name");

This is fresh call to server.

For example .. you forwarded from /login to login.jsp
in the browser you can see /login.jsp....

requestDispatcher.forward() : This not new request. Just transfer the content to forwarded jsp.
You can store data in request and able to get in redirect jsp.

For example .. you forwarded from /login to login.jsp
in the browser you can see /login ....

Disadvantage - browser refresh call to /login again, may be duplicate data submit.

No comments:

Post a Comment