Servlets


Servlet Interview Questions


What is the Servlet?
A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request- response programming model.

What are the uses of Servlet?
Typical uses for HTTP Servlets include:
  • Processing and/or storing data submitted by an HTML form.
  • Providing dynamic content, e.g. returning the results of a database query to the client.
  • A Servlet can handle multiple request concurrently and be used to develop high performance system
  • Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.
What are the advantages of Servlet over CGI?
Servlets have several advantages over CGI:
  • A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
  • A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications
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.

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.

What is the GenericServlet class?
GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface. 
Note: This class is known as generic servlet, since it is not specific to any protocol.

What are the types of protocols supported by HttpServlet ?
It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

What is the difference between doGet() and doPost()?
#
doGet()
doPost()
1
In doGet() the parameters are appended to the URL and sent along with header information.
In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar.
2
The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.
You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
3
doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent)
doPost() provides information (such as placing an order for merchandise) that the server is expected to remember
4
Parameters are not encrypted
Parameters are encrypted
5
doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance
doPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length
6
doGet() should be idempotent. i.e. doget should be able to be repeated safely many times
This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
7
doGet() should be safe without any side effects for which user is held responsible
This method does not need to be either safe
8
It allows bookmarks.
It disallows bookmarks.


When to use doGet() and when doPost()?
Always prefer to use GET (As because GET is faster than POST), except mentioned in the following reason:
  • If data is sensitive
  • Data is greater than 1024 characters
  • If your application don't need bookmarks.

How do I support both GET and POST from the same Servlet?
The easy way is, just support POST, then have your doGet method call your doPost method:


 public void doGet(HttpServletRequest request, HttpServletResponse response)
                      
 throws ServletException, IOException
{
    doPost(
request, response); 
}

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.

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.

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.

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.


What is the <load-on-startup> element?
The <load-on-startup> element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The <load-on-startup> element is written in the deployment descriptor as follows: 
<servlet>
   <servlet-name>ServletName</servlet-name>
   <servlet-class>ClassName</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

What is session?
A session refers to all the requests that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables.
Session
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.

What is the need of Session Tracking in web application?
HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information which is part of the application is reffered as "state". To keep track of this state we need session tracking. 
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.
What is URL rewriting?
URL rewriting is a method of session tracking in which some extra data 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.
Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.
E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
Advantages
  • URL rewriting works just about everywhere, especially when cookies are turned off.
  • Multiple simultaneous sessions are possible for a single user. Session information is local to each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't foolproof, though, since users can start a new browser instance using a URL for an active session, and confuse the server by interacting with the same session through two instances.
  • Entirely static pages cannot be used with URL rewriting, since every link must be dynamically written with the session state. It is possible to combine static and dynamic content, using (for example) templating or server-side includes. This limitation is also a barrier to integrating legacy web pages with newer, servlet-based pages.


DisAdvantages
  • Every URL on a page which needs the session information must be rewritten each time a page is served. Not only is this expensive computationally, but it can greatly increase communication overhead.
  • URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in awkward restrictions on the page.
  • URL rewriting does not work well with JSP technology.
  • If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are lost.

No comments:

Post a Comment