Saturday, October 1, 2011

Servlet Interview Question and Answers

Q.1)What is the difference between CGI and Servlet?
CGI:-Traditional CGI creates a heavy weight process to handle each http request. N number of copies of the same traditional CGI programs is copied into memory to serve N number of requests.
Servlet:-Its a lightweight Java thread to handle each http request. Single copy of a type of servlet but N number of threads (thread sizes can be configured in an application server).
A Servlet is a Java class that runs within a web container in an application server, servicing multiple client requests concurrently forwarded through the server and the web container. The web browser establishes a socket connection to the host server in the URL , and sends the HTTP request. Servlets can forward requests to other servers and servlets and can also be used to balance load among several servers.

Q.2)Which protocol is used to communicate between a browser and a servlet?
A browser and a servlet communicate using the HTTP protocol (a stateless request/response based protocol).

Q.3) What are the two objects a servlet receives when it accepts a call from its client?
A “ServletRequest”, which encapsulates client request from the client and the “ServletResponse”, which encapsulates the communication from the servlet back to the client.

Q.4) What can you do in your Servlet/JSP code to tell browser not to cache the pages?
response.setHeader(“Cache-Control”,“no-cache”); //document should never be cached. HTTP 1.1
response.setHeader(“Pragma”, “no-cache”); //HTTP 1.0
response.setDateHeader(“Expires”, 0);

Q.5) What is the difference between request parameters and request attributes?
Request parameters:
a)Parameters are form data that are sent in the request from the HTML page. These parameters are generally form fields in an HTML form.
b)You can get them but cannot set them.

Request attributes:
a)Once a servlet gets a request, it can add additional attributes, then forward the request off to other servlets or JSPs for processing. Servlets and JSPs can communicate with each other by setting and getting attributes.
b)You can both set the attribute and get the attribute. You can also get and set the attributes in session and application scopes.

Q.6) What are the different scopes or places where a servlet can save data for its processing?
request
session
application

Q.7)How does a Servlet differ from an Applet?
Applet:
Applets execute on a browser
Applets have a graphical user interface
Servlet:
Servlets execute within a web container in an Application Server.
Servlets do not have a graphical user interface.

Q.8)HTTP is a stateless protocol, so, how do you maintain state? How do you store user data between requests?
HTTP Sessions are the recommended approach. A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable. 

Q.9)What are the types of Session Tracking ?
Sessions need to work with all web browsers and take into account the users security preferences. Therefore there are a variety of ways to send and receive the identifier:
  • URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies.

  • Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.

  • Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie's value can uniquely identify a client.

  • Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL's support via HTTPS for generating a unique session key as part of the encrypted conversation.

Q.10)What is the difference between using getSession(true) and getSession(false) methods?
getSession(true): This method will check whether there is already a session exists for the user. If a session exists, it returns that session object. If a session does not already exist then it creates a new session for the user.
getSession(false): This method will check whether there is already a session exists for the user. If a session exists, it returns that session object. If a session does not already exist then it returns null.retrieve stored state information for the supplied JSESSIONID.Servlet Sessions can be timed out (configured in web.xml) or manually invalidated.

Q.11)How can you set a cookie and delete a cookie from within a Servlet?
To add a cookie
Cookie myCookie = new Cookie(“aName”, “aValue”);
response.addCookie(myCookie);
To delete a cookie
myCookie.setValue(“aName”, null);
myCookie.setMax(0);
myCookie.setPath(“/”);
response.addCookie(myCookie);

Q.12) Explain the life cycle methods of a servlet?
These three method going to be call in servlet life cycle:-
1)public void init(ServletConfig config) throws ServletException 
2)public void service(ServletRequest req,ServletResponse res) throws  
   ServletException,IOException
3)public void destroy()

Q.13)What are the phases of the servlet life cycle?
    The life cycle of a servlet consists of the following phases:
  • Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.

  • Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.

  • Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.

  • Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.

  • Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection
  • The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

Q.14)Explain the directory structure of a Web application?
The directory structure of a Web application consists of two parts:
A public resource directory(document root):The document root is where JSP pages,client-side classes and archives, and static Web resources are stored.
A private directory called WEB-INF:which contains following files and directories:
web.xml:Web application deployment descriptor. application server specific deployment descriptor e.g.jboss-web.xml etc.
*.tld:Tag library descriptor files.
classes:A directory that contains serverside classes like servlets,utility classes,JavaBeans etc.
lib:A directory where JAR(archive files of tag libraries,utility libraries used by the server side classes)
files are stored.

Q.15)What is the difference between doGet () and doPost () or GET and POST?
GET or doGet()
a)The request parameters are transmitted as a query string appended to the request. All the parameters get appended to the URL in the address bar. Allows browser bookmarks but not appropriate for transmitting private or sensitive information.
b)GET was originally intended for static resource retrieval.
c)GET is not appropriate when large amounts of input data are being transferred. Limited to 1024 characters

POST or doPost()
a)The request parameters are passed with the body of the request.
b)POST was intended for form submits where the state of the model and database are expected to change.
c)Since it sends information through a socket back to the server and it won’t show up in the URL address bar, it can send much more information to the server. Unlike doGet(), it is not restricted to sending only textual data. It can also send binary data such as serialized Java objects.

Q.16)What are the ServletContext and ServletConfig objects?
ServletConfig
The ServletConfig parameters are for a particular Servlet. The parameters are specified in the web.xml . It is created after a servlet is instantiated and it is used to pass initialization information to the servlet.
ServletContext :
The ServletContext parameters are specified for the entire Web application. The parameters are specified in the web.xml. Servlet context is common to all Servlets. So all Servlets share information through ServletContext.

Q.17) What is the difference between HttpServlet and GenericServlet?
Both these classes are abstract but:
GenericServlet:
a)A GenericServlet has a service() method to handle requests.
b)Protocol independent. GenericServlet is for servlets that might not use HTTP (for example FTP service).
HttpServlet:
a)The HttpServlet extends GenericServlet and adds support for HTTP protocol based methods like doGet(), doPost(), doHead() etc.HttpServlet also has methods like doHead(), doPut(), doOptions(), doDelete(), and doTrace().
b)Protocol dependent (i.e. HTTP).

Q.18) How do you make a Servlet thread safe?
The shared resources should be appropriately synchronized or should only use variables in a read-only manner. There are situations where synchronizing will not give you the expected results  and to achieve the expected results you should store your values in a user session or store them as a hidden field values. Having large chunks of code in synchronized blocks in your service or doPost() methods can adversely affect performance and makes the code more complex.

Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null interface javax.servlet.SingleThreadedModel. 

Q.19)How do you get your servlet to stop timing out on a really long database query?
 Client-pull or client-refresh: You can use the <META> tag for polling the server. This tag tells the client it must refresh the page after a number of seconds.
<META http-equiv=”Refresh” content=”10; url=”newPage.html” />

Q.20)What is lazy loading of a Servlet?
By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading.

Q.21)What is pre-initialization of a Servlet?
The servlet deployment descriptor (web.xml) defines the <load-on-startup> element, which can be configured 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 pre-loading or pre-initializing a servlet. We can also specify the order in which the servlets are initialized.
<load-on-startup>2</load-on-startup>

Q.22)What is a filter, and how does it work?
A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses but typically do not themselves create responses. Filters can also be used to transform the response from the Servlet or JSP before sending it back to client. Filters improve reusability by placing recurring tasks in the filter as a reusable unit. 

Q.23)What do you understand by servlet mapping?
 Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.

Q.24)Why do we need a constructor in a servlet if we use the init method?
Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven't constructed an object to call it on yet.

Q.25)Can servlet have a constructor ?
One can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose,but this type of approch is not so common. You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.

Q.26)Should I override the service() method?
We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request.For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method. 

Q.27)Should I override the service() method?
We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request.For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.

Q.28)What is a servlet context object?
A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. Each Web application in a container has a single servlet context associated with it.

Q.29)What are the differences between the ServletConfig interface and the ServletContext interface?
ServletConfig ServletContext
The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
There is one ServletConfig parameter per servlet. There is one ServletContext for the entire webapp and all the servlets in a webapp share it.
The param-value pairs for ServletConfig object are specified in the <init-param> within the <servlet> tags in the web.xml file The param-value pairs for ServletContext object are specified in the <context-param> tags in the web.xml file.


Q.30)What's the difference between forward() and sendRedirect() methods?

forward() sendRedirect()
A forward is performed internally by the servlet. A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
The  browser is completely unaware that it has taken place, so its original URL remains intact. The browser, in this case, is doing the work and knows that it's making a new request.
Any browser reload of the resulting page will simple repeat the original request, with the original URL A browser reloads of the second URL ,will not repeat the original request, but will rather fetch the second URL.
Both resources must be part of the same context (Some containers make provisions for cross-context communication but this tends not to be very portable) This method can be used to redirect users to resources that are not part of the current context, or even in the same domain.
Since both resources are part of same context, the original request context is retained Because this involves a new request, the previous request scope objects, with all of its parameters and attributes are no longer available after a redirect.
(Variables will need to be passed by via the session object).
Forward is marginally faster than redirect. redirect is marginally slower than a forward, since it requires two browser requests, not one.


Q.31)What is the difference between the include() and forward() methods?
include() forward()
The RequestDispatcher include() method inserts the the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet. The RequestDispatcher forward() method is used to show a different resource in place of the servlet that was originally called.
If you include a servlet or JSP document, the included resource must not attempt to change the response status code or HTTP headers, any such request will be ignored. The forwarded resource may be another servlet, JSP or static HTML document, but the response is issued under the same URL that was originally requested. In other words, it is not the same as a redirection.
The include() method is often used to include common "boilerplate" text or template markup that may be included by many servlets. The forward() method is often used where a servlet is taking a controller role; processing some input and deciding the outcome by returning a particular response page.


Q.32)What's the use of the servlet wrapper classes??
The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.

Q.33)What is Session Tracking?
Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

Q.34)How can an existing session be invalidated?
An existing session can be invalidated in the following two ways:

Setting timeout in the deployment descriptor: This can be done by specifying timeout between the <session-timeout>tags as follows:
<session-config>
       <session-timeout>10</session-timeout>
</session-config>
 
This will set the time for session timeout to be ten minutes.

Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
public void setMaxInactiveInterval(int interval)
The seMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.

Q.35)What is Servlet Chaining?
Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

Q.36)What are the functions of the Servlet container?
The functions of the Servlet container are as follows:
  • Lifecycle management : It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
  • Communication support : It handles the communication between the servlet and the Web server.
  • Multithreading support : It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
  • Declarative security : It manages the security inside the XML deployment descriptor file.
  • JSP support : The container is responsible for converting JSPs to servlets and for maintaining them.

No comments:

Post a Comment