servlet interview questions and answers.Contains frequently asked interview questions on servlet for freshers and experienced.
A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications. All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods.
Suppose user made the request for the URL www.google.com/intl/en/privacy.html then:
1. web browser establishes a connection with www.google.com server by locating its IP address from a DNS server.
2. The web browser then sends a request to the server to retrieve the intl/en/privcy.html file.
3. The server respond with the info about the the requested HTML page and the contents of privacy.html file.
This process of sending a request and receiving a response from the server is known as transaction.An HTTP session remains open till a single transaction is completed.
Performance of servlets is better than CGI scripts because CGI scripts need to be loaded in various process for every request. On the other hand, a servlet , once loaded in the memory, can be run multiple times on a single lightweight thread.
1. Web server converts the request into an HTTPServletRequest object.
2. The HTTPServletRequest object is sent to a web compnent to establish a communication with javabeans components.
3. The HTTPServletResponse object is generated by the web component and finally the HTTPServletResponse object displys the data to the client as the resonse generated by the web server.
The main functions of Servlet container are:
1. Lifecycle management : Managing the lifecycle events of a servlet lik class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
2. Communication support : Handling the communication between servlet and Web server.
3. Multithreading support : Automatically creating a new thread for every servlet request and finishing it when the Servlet service() method is over.
4. Declarative security : Managing the security inside the XML deployment descriptor file.
5. JSP support : Converting JSPs to servlets and maintaining them.
When a client request is received by a web container , firstly the container maps the request with an appropriate servlet according to deployment descriptor. After the servlet is idenified, the web container loads the servlet class and creates an instance of the servlet. The servlet is then initialized by calling init() method. After calling the init() method, the service() ethod passess the request and response object to the web conatainer. The web container invokes the destroy() method to remove the servlet, if the servlet is not required.
Yes, Servlet implementation classes can have constructor but there is no point in creating a constructor in servlet because Servlet require ServletConfig object for initialization which is created by container itself.
javax.servlet.Servlet is interface, it defines methods for all the implementations - that's what interfaces usually do.
javax.servlet.GenericServlet is protocol independent. It is abstract, so it is not to be directly instantiated. It is usable class to extend if you some day have to write servlet for protocol other than HTTP.
javax.servlet.http.HttpServlet is abstract class to be extended if you want to communicate over HTTP protocol. Most likely you only have to care about this one.
Deployment descriptor is a configuration file for the web application and it’s name is web.xml and it resides in WEB-INF directory. Servlet container use this file to configure web application servlets, servlet config params, context init params, filters, listeners, welcome pages and error handlers.
With servlet 3.0 annotations, we can remove a lot of clutter from web.xml by configuring servlets, filters and listeners using annotations.
Based on the bussiness, we can have multiple servlets for specific business scenario. In that case it is required to have inter-servlet communication. We can achieve this in Servlet by using RequestDispatcher forward() and include() methods and provide additional attributes in request for other servlet use.
1. The first aim for a servlet is to achieve thread safety by virtue of no shared state. Any shared state will fail to be that when the servlet is deployed into a load-balancing cluster.
2. Any local variables in service methods are thread safe because they are specific to each thread but for shared resource we can use synchronization to achieve thread safety in servlets.
1. RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request. The request sent is a completely new request.
2. forward() is handled internally by the container whereas sendRedirect() is handled by browser.
3. We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.
4. In forward() browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect() URL in address bar change to the forwarded resource.
5. forward() can’t be used to invoke a servlet in another context, we can only use sendRedirect() in this case.
To have any useful behaviour, it is expected that you will have to override the methods. HttpServlet does not have useful functionality on its own.Making its constructors private would limit the ability for subclasses to be created.
The design of HttpServlet was probably not ideal -- as on many pages, forms especially, GET and POST logic should proceed at least partly along a common path. The design idea of HttpServlet however was to offer doGet(), doPost() etc implementations answering a 'not supported' error depending on HTTP version. These stubs would be useful to inherit if you needed to return such an answer.
In summary, the API/ interface is complete -- but the functionality is definitively not. Thus it is declared as abstract.
The javax.servlet.Servlet interface defines the life cycle methods of servlet such as init(), service() and destroy(). The Web container invokes the init(), service() and destroy() methods of a servlet during its life cycle.
1. GET 2. POST 3. PUT 4. DELETE 5. OPTIONS 6. HEAD 7. TRACE
A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.
The Content-Type response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.
Web Applications are modules that requires to run on server to handle the request and return the response. Java provides web application support through Servlets and JSPs that can run in a servlet container and provide dynamic content to client browser.
Java Web Applications are packaged as Web Archive (WAR) and it has following folders in it.
WEB-INF : contains the lib directory(application dependencies), classes(contains java servlet files) and web.xml(Deployment Descriptor)
META-INF: contains MANIFEST.MF
webapp: contains all the static pages like .html , .js etc
It is a method in which the output of one servlet is piped into the next servlet.
It is the last servlet in the chain that provides the output to the Web browser.
javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object by calling servlet's init() method.A servlet is initialized only once in its life cycle and hence the init() method is called only once per servlet by a web server.
This will be the first statement if we are overriding the init(config) method by this way we will store the config object for future reference and we can use by getServletConfig() to get information about config object if will not do this config object will be lost and we have only one way to get config object because servlet pass config object only in init method . Without doing this if we call the ServletConfig method will get NullPointerException.
javax.servlet.ServletContext interface provides access to web application parameters to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml using
ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.
ServletConfig is used to provide init parameters to the servlet whereas ServletContext is used to provide application level init parameters that all other servlets can use.
We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.
Yes we can call like this but if we have not overridden this method container will call the default method and nothing will happen.after calling this if any we have overridden the method then the code written inside is executed.
include() Includes the response of another servlet into the calling servlet. This method can be invoked from calling servlet while servicing the request. It includes contents of resource such as Servlet, JSP page or HTML page in response.
forward() mehod is used to forward requests to resource such as Servlet, JSP file or HTML page on the server. I implies that after invoking forward() method, the servlet can not add any response content.
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.
There are two methods defined in this interface:
void forward(ServletRequest request, ServletResponse response) – forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
void include(ServletRequest request, ServletResponse response) – includes the content of a resource (servlet, JSP page, HTML file) in the response.
1.PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class.
2.We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.
3.We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.
Http is a stateless, client-side pull only protocol.To implement a stateful conversation over it, Java EE Web Server need to hide some information (which is sessionid) in client-side and the mechanism it can use should follow HTTP and HTML spec.
There are three ways to accomplish this goal:
Cookies - Server will ask browser to maintain a cookie.
Hidden Form Field - server will add an additional parameter at every form in HTML
URL Rewriting - Server will add an additional parameter at the end of URL link
Using cookies is the simplest and easiest way to track a session.A unique session id (stored in the form of a cookie) is sent by the server to the client as a part of the response and the same session id saved with the client is sent to the server as a part of the request which helps the server to recognize the unique client session.
encodeURL() is used for all URLs in a servlet's output. It helps session ids to be encoded with the URL.
encodeRedirectURL() is used with res.sendRedirect only. It is also used for encoding session ids with URL but only while redirecting.
Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
We can configure them in web.xml like below:
Usually servlet container loads a servlet on the first client request but sometimes when the servlet is heavy and takes time to loads, we might want to load it on application startup. We can use load-on-startup element with servlet configuration in web.xml file or use WebServlet annotation loadOnStartup variable to tell container to load the servlet on system startup.
The load-on-startup value should be int, if it’s negative integer then servlet container will load the servlet based on client requests and requirement but if it’s 0 or positive, then container will load it on application startup.
If there are multiple servlets with load-on-startup value such as 0,1,2,3 then lower integer value servlet will be loaded first.
one simple way to call doPost() method inside doGet() and doGet()method inside doPost() it will create deadlock situation for a servlet.
Servlet creates only one instance either request is 100 or 200.
Wrappers are sandwiched between servlet classes and servlet environments by wrapping servlet APIs. Wrappers allow to add additional functionalities to the request and response object given by the servlet container.
Filters can also use wrappers to wrap request or response.Servlet 3.0 provide following 4 wrapper classes.
Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.