Servlet Interview Questions and Answers
In this article, I am going to discuss the most frequently asked 100 Servlet Interview Questions and Answers. Once you go through these Servlet Interview Questions and Answers, I am sure you will crack the Server Interview easily.
What is Servlet?
A servlet is a Java programming language class that’s wont to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can answer any sort of request, they’re commonly want to extend the appliance hosted by web servers. Java Servlet technology defines HTTP-specific servlet classes for such applications.
By using which 2 packages we can implement Servlet?
Servlets are created using the javax.servlet and javax.servlet.http packages. These packages are a standard part of Java’s enterprise edition and an expanded version of the Java class library that supports large-scale development projects.
javax.servlet.*: It contains a number of classes and interfaces. It describes and defines the contracts between a servlet class and the runtime environment.
javax.servlet.HTTP.*: It contains a number of classes and interfaces. It describes and defines the contracts between a servlet class running under the HTTP protocol and the runtime environment.
What are the new features added to Servlet 2.5?
Following are the changes introduced in servlet 2.5:
- A new dependency on J2SE 5.0
- Support for annotations
- Several web.xml conveniences
- A handful of removed restrictions
- Some edge case clarifications
What are the uses of Servlet?
This is one of the frequently asked Servlet Interview Questions and Answers. Typical uses for HTTP Servlets include:
- Receives client request in the form of the HTTP request
- Extract some information from the request received
- Do content generation or business logic processes by accessing the database, invoking EJBs, etc
- Create and send a response to the client in the form of an HTTP response or forward the request to another servlet or JSP page.
What are the advantages of Servlet over CGI?
This is one of the frequently asked Servlet Interview Questions and Answers. Servlets have several advantages over CGI:
- Portability: Servlets are highly portable across operating systems and server implementations because servers are written in java and follow well-known standardized APIs so they are.
- Powerful: It is possible to do several things with the servlets which were difficult or even impossible to do with CGI.
- Efficiency: As compared to CGI the invocation of the servlet is highly efficient. When the servlet gets loaded in the server, it remains in the server’s memory as a single object instance.
- Safety: As servlets are written in java, servlets inherit the strong type-safety of java language. Servlets are generally safe from memory management problems because of Java’s automatic garbage collection and a lack of pointers.
- Integration: Servlets are tightly integrated with the server. Servlet basically uses the server to translate the file paths, perform logging, check authorization, and MIME type mapping, etc.
- Extensibility: The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API supports HTTP Servlets, but later it can be extended for another type of servlets.
- Inexpensive: There are a number of free web servers available for personal use or for commercial purposes. Web servers are relatively expensive. So by using the available web servers you can add servlet support to it.
What are the phases of the Servlet life cycle?
This is one of the frequently asked Servlet Interview Questions and Answers. The life cycle of a Servlet consists of the following phases:
Loading and Instantiation
The servlet container loads the servlet during startup or when the primary request is formed. Loading of the servlet depends on the attribute of the web.xml file. If the attribute has a positive value then the servlet is loaded with the loading of the container otherwise it loads when the first request comes for service. The container creates the instances of the servlet after loading the servlet.
After creating the instances, the servlet container calls the init() method and passes the servlet container before the servlet can service any request. The initialization parameters persist until the servlet is destroyed. The init() method is named just one occasion throughout the life cycle of the servlet. The servlet is going to be available for service if it’s loaded successfully otherwise the servlet container unloads the servlet.
Servicing the Request
After successfully completing the initialization process, the servlet is going to be available for service. Servlet creates separate threads for each request. The servlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends the response to the client using the methods of the response object.
Destroying the Servlet
If the servlet is not any longer needed for servicing any request, the servlet container calls the destroy() method. Like the init() method this method is additionally called just one occasion throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container to not sent any request for service and therefore the servlet releases all the resources related to it. Java virtual Machine claims for the memory related to the resources for garbage pickup.
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.
What are the various life cycle methods of Servlet?
Servlets has three lifecycle methods and they are defined in Servlet Interface. The three lifecycle methods of servlet are:
init(): init() method would be executed by the container automatically as soon as an object of the servlet is created, the object of the servlet would be created only once. Thus init() method would be executed only once i.e. when the object of the servlet is created for the first time.
service(): service() method would be executed by the container automatically as and when the request is coming to as servlet. A container always calls service() method by passing the data (i.e. coming from the client) in the form of ServletRequest object and address of the client (from where the request is received) in the form of servletResponse object as arguments.
destroy(): destroy() method would be executed before the object of the servlet is deleted. The container maintains every servlet object for a certain period of time even if no request is coming to that servlet. After a certain period of time container deletes the object of the servlet before deleting or destroying the servlet object. The container automatically calls destroy() method and executes destroy() method completely and after the execution of the destroy() method, the servlet object would be completely deleted.
What are various types of Container?
As per the technology which we used to design server-side components. There are some containers:
- Servlet Container – To execute Servlets
- JSP Container – To execute JSP’s
- EJB Container – To execute EJB’s
Note: All the above-specified containers can be used to execute the respective components because the above containers have implemented the respective technology API.
As per the containers physical existence, there are three types of containers:
- Standalone Container – It is an integration of the main server and container as a single program.
- In-process Container – It is a container that existed inside the main server.
- Out of Process container – It is a container that existed inside the main server.
Why do we need a constructor in a servlet if we use the init method?
The init() method is by which a servlet Container will run to configure the Servlet. It provides a servletConfig object which gives the Servlet instance access to the ServletContext and other configuration elements from the deployment descriptor.
Explain about Single Thread Model
It ensures that the servlet can handle only one request at a time. It has no methods. If a servlet implements this interface it is guaranteed that no two threads will execute concurrently in the servlet’s service method. The servlet container guaranteed it by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet. SingleThreadModel interface does not prevent synchronization problems that result from servlets accessing shared resources such as static class variables or classes outside the scope of the servlet.
What is the purpose of Request Dispatcher?
It provides the power of dispatching the request to a different resource it’s going to be HTML, servlet, or JSP. In web applications, we are ready to achieve web-component communication within the following 2 ways:
- Include Mechanism
- Forward Mechanism
If we would like to perform the above mechanisms internally we must use the RequestDispatcher object. So that both include and forward mechanisms are commonly called Request Dispatching Mechanisms.
What methods we can call on the Request Dispatcher object?
It provides two methods. They are:
Include: Include Request Dispatching mechanism can be used to include the target resource response into the present resource response. In the case of the Include mechanism, when we send a request to the first resource then the container will prepare the request and response objects, by executing some parts in the first resource container may generate some response in the response object.
public void include(ServletRequest req, ServletResponse res) throws ServletException, IOException
Forward: In web applications, the main purpose of the forward mechanism is to forward requests from the present resource to the target resource. In the case of the forward mechanism, when we send a request to the first resource then the container will create request and response objects, by executing some part in the first resource container may generate some response in the response object.
public void forward(ServletRequest req, ServletResponse res) throws ServletException, IOException
How the servlet is loaded and unloaded?
A servlet is loaded by making a request first then the server starts up. There is only a single instance that answers all requests concurrently. Then administrator manually loads.
A servlet is unloaded when the server shuts down or the administrator manually unloads.
What is the Servlet interface?
The servlet interface is for developing servlets. A servlet may be a body of Java code that’s loaded into and runs inside a servlet engine, as an internet server. It receives and responds to requests from clients. For example, a client may have information from a database; a servlet is often written that receives the request, gets and processes the info as required by the client, and then returns it to the client.
Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.httpServlet.
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 a generic servlet since it is not specific to any protocol.
What’s the difference between GenericServlet and HttpServlet?
- The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods.
- The GenericServlet does not include protocol-specified methods for handling request parameters, cookies, sessions, and setting response headers.
- GenericServlet is not specific to any protocol.
- An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides a framework for handling the HTTP protocol.
- The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method.
- HttpServlet only supports HTTP and HTTPS protocol.
Why is HttpServlet declared abstract?
This is one of the frequently asked Servlet Interview Questions and Answers. The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenient implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests, for example, there is no need to write a doPost() method too. required to handle doGet() requests, for example, there is no need to write a dpPost() method too.
Can servlet have a constructor?
Yes, Servlets can have a constructor but it is not the right way to initialize the Servlet and you should use the init() method provided by the Servlet.
What are the types of protocols supported by HttpServlets?
It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So HttpServlet only HTTP and HTTPS protocol.
What is the difference between doGet() and doPost()?
The doGet() method is called by the server via the service method to allow a servlet to handle a GET request whereas the doPost() method is called by the server to allow a servlet to handle a PUT request.
- In doGet() the parameters are appended to the URL and sent along with header information.
- The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.
- doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent)
- Parameters are not encrypted
- doGet() is faster if we set the response content length since the same connection is used. Thus, increasing the performance
- doGet() should be idempotent. i.e. doGet should be able to be repeated safely many times
- doGet() should be safe without any side effects for which the user is held responsible
- It allows bookmarks.
- 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.
- 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!
- doPost() provides information (such as placing an order for merchandise) that the server is expected to remember.
- Parameters are encrypted
- 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
- This method doesn’t need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
- This method does not need to be either safe
- It disallows bookmarks.
When to use doGet() and when doPost()?
It is always preferred to use the get method because the get method is faster than the post method. Use post method only id data is sensitive if data is greater than 1024 characters and if your application doesn’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, IQException
Should I override the service() method?
This is one of the frequently asked Servlet Interview Questions and Answers. It is not required to override the service method since the HTTP Servlets have already taken care of it. HTTP service method checks the request method and calls the appropriate handler method so it is not necessary to override the service method itself.
What is a servlet context object?
ServletContext is an object, it will manage all the context details of a particular web application, where the context details include the logical name of the web application and context parameters, and so on. ServletConetxt is an object, it will provide the complete view of the particular web application.
What are the differences between the ServletConfig interface and the ServletContext interface?
ServletConfig is implemented by the servlet container in order to pass configuration information to a servlet whereas the servletContext defines a set of methods that a servlet uses to communicate with its servlet container.
What’s the difference between forward() and sendRedirect() methods?
In the case of forward(), redirect happens at the server end and is not visible to the client, whereas in the case of sendRedirect(), redirection happens at the client’s end and it’s visible to the client.
What is the difference between the include() and forward() methods?
The main difference is forward() method closes the output stream after it has been invoked, whereas the include() method leaves the output stream open.
What’s the use of the servlet wrapper classes?
This is one of the frequently asked Servlet Interview Questions and Answers. The main purpose of Servlet Wrappers in web applications is to simplify the customization of request and response objects. In general in web application execution when we send a request from the client to server for a particular servlet then the container will pick up the request, identify the requested servlet, perform servlet life cycle stages like servlet loading, servlet instantiation, servlet initialization, request processing, and servlet de-instantiation.
What is a deployment descriptor?
This is one of the frequently asked Servlet Interview Questions and Answers. It refers to the configuration file for an artifact that is deployed to some container/engine. It describes the classes, resources, and configuration of the application and how the web server uses them to serve web requests.
What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
- ServletRequest.getRequestDispatcher(String path): The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts the parameter the path to the resources to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.
- ServletContext.getRequestDispatcher(String path): The getRequestedDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept relative paths. All paths must start with a “/” and are interpreted as relative to the current context root.
What is pre initialization of a servlet?
Preinitialization is the process of loading a java servlet before receiving any request. Servlet is loaded in the order of number (non-zero integer) specified. It is also known as load-on-startup.
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:
Note: The container loads the servlets in the order specified in the <load-on-startup> element.
What is a session?
The session is a time duration, it will start from the starting point of client conversation with the server and will terminate at the ending point of client conversation with the server. The data which we transferred from client to server through multiple numbers of requests during a particular session then that data is called State of the Session.
What is Session Tracking?
In general in web applications, a container will prepare a request object similarly to represent a particular user we have to prepare a separate session. In this context, to keep track of all the session objects at the server machine we need to set explicit mechanisms called Session Tracking Mechanisms.
What is the need for session Tracking in the web application?
Session Tracking is used to recognize the particular user. It is a way to maintain the state (data) of the user about a series of requests from the same user (that is, requests originating from the same browser) across the same period of time. Each time the user requests to the server, the server always treats the request as the new request.
What are the types of Session Tracking?
This is one of the frequently asked Servlet Interview Questions and Answers. In web applications, there are 4 types of Session Tracking Mechanisms:
- HttpSession Session Tracking Mechanism: In HttpSession Session Tracking Mechanism, we will create a separate HttpSession object for each and every user at each and every request we will pick up the request parameters from the request object and we will store them in the respective HttpSession object for the sale of future reusability.
- Cookies Session Tracking Mechanism: A cookie is a small object, it can be used to represent a single name-value pair and which will be maintained permanently at the client machine.
- URL-Rewriting Session Tracking Mechanism: In URL-Rewriting Session Tracking Mechanism we will not depend on a Cookie to maintain Session-Id value, we will manage SessionId value as an appended to URL in the next generated form.
- Hidden Form Fields Session Tracking Mechanism: In Hidden Form Field Session Tracking Mechanism, at each and every request we will pick up all the request parameters, generate the dynamic form, in dynamic form generation we have to maintain the present request parameters data in the form of hidden fields.
To set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies may be set for the same request, and a single cookie name may have multiple values.
To get all of the cookies associated with a single HTTP request, use the getCookies() method of class HttpServletRequest
What are some advantages of storing session states in cookies?
- Cookies allocate memory at clientside which means, they do not give a burden to the server.
- Cookies work with all serverside technologies and all servers.
- Persistent cookies can remember client data even after the session having expiry time.
What are some disadvantages of storing session state in cookies?
- To work with cookies our servlet type must be HttpServlet (cookies do not work with GenericServlet).
- Cookies can be deleted through browser settings. This may fail session tracking.
- In Internet Explorer: Tools menu -> internet options -> delete cookies option
- In Netscape : Tools menu -> cookie manager -> manage stored cookies -> remove all cookies option
- Cookies can be restricted from coming to clients from the server through browser settings. This may fail session tracking.
- In Internet Explorer:
- Tools menu -> internet options -> privacy tab (to block cookies)
- In Netscape:
- Tools menu -> cookie manager -> block cookies from this site to block the cookies.
- The values placed in cookies can be viewed through browser settings that means there is not data secrecy.
- There is a restriction on the number of cookies that can be there that is per browser window, per domain maximum of 20 cookies, and all domains together per browser window maximum of 300 cookies (may vary browser to browser).
What is URL rewriting?
URL-Rewriting Session Tracking Mechanism is almost all same as HttpSession Tracking Mechanism, in URL-Rewriting Session Tracking Mechanism we will not depending on a Cookie to maintain Session-Id value, we will manage SessionId value as an appended to URL in the next generated form. In this context, if we send a request from the next generated form automatically the appended Session-Id value will be transferred to the server along with the request. In this case, even though if we disable Cookies at the client browser, but still we are able to get SessionId value at the server machine and we are able to manage the client’s previous request data at the time of processing the later request.
Advantages of URL rewriting
- 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 of URL rewriting
- 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.
How can an existing session be invalidated?
We can invalidate the existing session by using invalidate() method. It invalidates the current session and unbinds any objects that were previously bound to it.
How can the session in Servlet be destroyed?
To destroy a session either call session.invalidate() method or session.setMaxInactiveInterval(0).
What is servlet lazy loading?
A container initializes a servlet when it receives a request for the servlet first time as it does not initialize the servlets as soon as it starts up. This is called lazy loading.
What is Servlet Chaining?
Taking the request from a browser window and processing that request by using multiple servlets as a chain is called servlet chaining. In servlet chaining, we perform communication between servlet programs to process the request given by a client.
What are the filters?
This is one of the frequently asked Servlet Interview Questions and Answers. Intercepting filter is a special web resource program of a web application that can trap all the requests and responses of other web resource programs. Intercepting filter contains common and global pre-request logic and post-response generation logic. In servlet programming, we can use servlet filter as the “Interceptor” filter of the web application. Without disturbing the existing web resource of a web application if you want to add additional functionality to web application then use servlet filter support.
What are the various listener available in Servlet?
- javax.servlet.ServletContextListener: It is a Lifecycle change event category. It is used for servlet context creation, at which point the first request can be serviced.
- javax.servlet.ServletContextAttributeListener: It is attribute changes event categories. It is used for the addition, removal, and replacement of servlet context attributes.
- javax.servlet.http.HttpSessionListener: It is also lifecycle changes even categories. It is used for session creation, invalidation, and timeout.
- javax.servlet.http.HttpSessionAttributeListener : It is attributes changes event categories. It is used for the addition, removal, and replacement of session attributes.
What are the various Event classes present in Servlet?
- The ServletContextEvent is notified when the web application is deployed on the server.
- ServletContextAttributeEvent is the event class for notifications about changes to the attributes of the servlet context of a web application.
- HttpSessionEvent is notified when the session object is changed.
- HttpSessionBindingEvent is either sent to an object that implements HttpSessionBindingListener when it is bound or unbound from a session, or to a HttpSessionAttributeListener that has been configured in the deployment descriptor when any attribute is bound, unbound, or replaced in a session.
Which interface we can implement Filter?
There are three interfaces of Servlet API:
- Filter Interface: It is an object that performs filtering tasks on either the request to a resource or on the response from a resource or both. It performs filtering in the doFilter method. It is configured in the deployment descriptor of a web application. Each Filter has access to a FilterConfig object by which it can obtain its initialization parameters which is a reference to the ServletContext which it can use
- FilterChain Interface: It is an object provided by the servlet container to the developer giving a view into the invocation chain of a filtered request for a resource. Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain to invoke the resource at the end of the chain.
- FilterConfig Interface: It is used by a servlet container to pass information to a filter during initialization.
What are the functions of an intercepting filter?
The filter intercepts incoming requests and outgoing responses, also allowing preprocessing and post-processing. Also, these can be added or removed without changing existing codes.
What are the functions of the servlet container?
This is one of the frequently asked Servlet Interview Questions and Answers. The functions of the servlet container are as follows:
- Lifecycle management: It manages the life and death of a servlet, instantiation initialization, service, and making servlet instances eligible for garbage collection.
- Communication support: It handles the communication between the servlet and the webserver.
- Multithreading support: It automatically creates a new thread for every servlet request received.
- Declarative security: It manages the security inside the XML deployment descriptor file.
- JSP support: It is responsible for converting JSPs to servlets and for maintaining them.
Here, in this article, I discussed the most frequently asked 100 Servlet Interview Questions and Answers. I hope you enjoy this Servlet Interview Questions and Answers article. If you have any questions that we have not added here, then please comment on your question in the comment box and as soon as possible we will give an answer to that question. Further, if you want to add any Servlet Interview Questions with Answers, then please add the same in the comment box which will be beneficial to others.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.