Servlet Interview Questions and Answers for 2024

The main objective of the Servlet technology is to build high-level web applications termed web pages. So, Java web application technology is in high demand. By using web applications that are built on servlet, users can interact by clicking, adding, or manipulating the data. Servlets serves as the server-side application and generate Dynamic Web pages for the user interface. Servlet is built on top of Java, it has features like robustness and scalability. It is good to learn Java Programming and understand the concepts before proceeding to learn about Java and Servlets. The article includes the Servlet interview questions for all experienced levels starting from beginner-level, intermediate and experienced-level interview questions. It is good to have basic knowledge of java and servlets before preparing for the interview questions. Also, it is suggested to understand and practice more on each question which is explained in detail on each topic.

  • 4.7 Rating
  • 65 Question(s)
  • 35 Mins of Read
  • 5640 Reader(s)

Beginner

As we know, the purpose of Servlets is to build interactive server-side web application. It provides dynamic web pages, interactive user interface. Let us understand the advantages of servlets over CGI: 

  • The performance of servlets is significantly better compared to CGI. 
  • In servlets it is not required to create a new server to handle each request. As servers in servlets execute within the webserver. 
  • Servlets are platform-independent because they are built on top of Java. 

Before knowing in depth about cookie, let us understand what it is. Cookie is a piece of information that is present between multiple client requests. A cookie can have a name, a value, optional attributes such as version number, comment, path, and domain qualifiers and many more.

In cookie, each request is considered as a new request, we add cookie with response from the servlet and it will be stored in the cache of the browser. And if the user requests for the same data, the data is sent from the cookie back to the user, considering as an existing user.

It's no surprise that this one pops up often in Servlet Interview Questions. The lifecycle is nothing but the procedural steps to be followed to execute the application. The servlet lifecycle can be defined using the steps below: 

  1. Servlet is loaded 
  2. Servlet is instantiated 
  3. Servlet is initialized 
  4. Servlet service the request 
  5. Servlet is destroyed 

We know constructors provide the default values, we can define a constructor for servlet, but I do not think it is of any use because we will not be having access to the ServletConfig object until and unless servlet is initialized by the container.

To interact with multiple servlets, RequestDispatcher acts as a bridge to interact between servlets. So, we can use RequestDispatcher forward() method to forward the processing of a request to another servlet. If we want to include another servlet output to the response, we can use RequestDispatcher include() method.

A must-know for anyone heading into a Servlet interview, this question is frequently asked in React Interview Questions. As we know, the purpose of Servlets is to build interactive server-side web applications. It provides dynamic web pages and makes an interactive user interface. Servlets are robust and scalable in nature, so it is easier to develop and maintain error-free applications.

The definition of a servlet can be said as a servlet is a Java program that runs within a Web server. Servlets receive the request and respond back to requests using Web clients. Web clients are nothing but HHTP protocols, whereas HTTP stands for Hyper Text Transfer Protocol.

Servlets can access the internal library of HTTP-specific functions, with these HTTP functions servlets can access the features of Java language like portability, robustness, crash protection, reusability and many more. Servlets are provided with rich interaction functionalities within the browser to the end users some of them are like clicking on the link form submission, radio button or checking the check box and many more.

Servlet provides several advantages over the other approaches. It might include portability, robust features, power of integration and flexibility. Here are a few advantages of servlet: 

  • Servlets are convenient and easy in modifying the regular HTML code. 
  • Servlets include the Java multithreading feature, so it saves memory. 
  • We can write the Servlet code into JSP. 
  • Servlets have a specific layer of Business Logic in the application. 
  • Servlets are robust because container takes care of the life cycle of servlet, so we do not need to worry about memory leakage, security, garbage collection  
  • Servlets are platform and system independent, that is web application built using servlet can be run on any web containers like Tomcat, JBoss, Glassfish servers. Also operating systems like Windows, Linux, Unix etc.

Servlet mapping is a process of defining an association between a URL platform and a servlet. The mapping is used to map requests to servlets.  

Here, Servlet Mapping specifies the Web container by informing which Java servlet should be invoked for a URL given by the client application. It maps the URL pattern to servlets. When there is a request from a client, the servlet container decides which application it should forward or send back as a response.

Before knowing about the types of annotations used in Java, let us have a basic understanding of what annotations are.  

An annotation is a form of syntactic metadata, that can be added to Java source code. We can annotate Classes, methods, variables, parameters, and Java packages using annotations. 

So, in Servlet there are 3 important annotations used widely, they are: 

  1. @WebServlet: used for class level Servlet annotation 
  2. @WebListner: used for Listener class 
  3. @WebFilter: used for Filter class

A cookie is a piece of information that is present between multiple client requests. In cookie, each request is considered as a new request, we add cookie with response from the servlet and it will be stored in the cache of the browser. And if the user requests for the same data, the data is sent from the cookie back to the user, considering as an existing user.

There are two types of Cookies in Servlet: 

  • Persistent Cookie 
  • Non-Persistent Cookie 

Persistent Cookie: The Persistent cookie is valid for Multiple sessions. It is not removed each time when user closes the browser. The data is removed only if the user logs out or signs out of an application. 

Non-Persistent Cookie: It is valid for single session. The stored cookie data is removed each time when user closes the browser. 

The main difference between Generic Servlet and Http Servlet is that the Generic Servlet is protocol independent and can be used with any protocol such as HTTP, SMTP, FTP and CGI while HTTP is protocol dependent and can only be used with HTTP protocol. 

Generic servlet is an immediate subclass of Servlet interface whereas HTTP Servlet is immediate subclass of Generic Servlet. 

Also, in Generic Servlet service () method is abstract and is not commonly used whereas in HTTP servlet, service() is non abstract and is commonly used. 

Generic Servlet
HTTP Servlet 

Protocol Independent 

Protocol Specific 

Belongs to javax.servlet package 

Belongs to javax.servlet.http package 

Supports only service() method  
 

supports doGet(), doPost(), doHead() methods 

This is a frequently asked question in Servlet interview questions and answers. The lifecycle is nothing but the procedural steps to be followed to execute the application. There are three life cycle methods of a servlet, they are: 

  • init(): init() is the first servlet life cycle method, it is the first method to be invoked. The web container calls the init method only once after creating the servlet instance. The init() is used to initialize the servlet. 

 public void init(ServletConfig config) throws ServletException  

  • service(): service() is the second method to be invoked. The web container calls the service method each time when request for the servlet is received.  

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException  

  • destroy(): destroy method is the third or last method to be invoked in the servlet life cycle. The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. 

public void destroy()  

The get() and post() methods are called the HTTP methods. Both differ in their own functionality, some of the major difference of get() and post() methods are:

get()
post()

1) get() can hold only a limited amount of data, because the data is passed in header url. 

Post() method can send large amounts of data because data is sent in request body. 

2) get() methods are not secured because data is exposed to header URL 

Post () methods are secured because data is not exposed in header URL. 

3) It can be bookmarked 

Cannot be bookmarked 

4) get() methods Idempotent 

Non-Idempotent 

5) It is more efficient and used than Post 

It is less efficient and used 

The init() method is used to create or load the data used throughout a servlet's life. It is called by the servlet container to indicate to a servlet that the servlet is being placed into service.  

The servlet container calls the init() method exactly once after instantiating the servlet. The init() method must complete successfully before the servlet can receive any request. The init() method lets the classes initialize the objects attributes and serves no other purpose.

Let us know a basic of what JSP’s are, JSP stands for Java Server Pages. Java servlets and Java Server pages are java programs that run on java application server and extend the capabilities of the web server. Java servlets are java classes designed to respond to HTTP requests in the context of a web application. These servlets will call the jsp using RequestDispatcher interface. Also, one can expect this type of question in java jsp and servlet interview questions and answers. 

Example: 

RequestDispatcher requestDispatch = request.getRequestDispatcher("log.jsp"); 
requestDispatch.forward(request, response); 

The RequestDispatcher is an interface, it consumes the request object received from the client and then it dispatches that request to the other resources like JSP, servlets HTML files. The RequestDispatcher can also be used to include the content of other resources. The RequestDispatcher has the following two methods: 

  • public void forward(ServletRequest request, ServletResponse response) 

The forward() method forwards requests from one servlet to other resources like servlet, JSP, HTML etc. 

  • public void include(ServletRequest request, ServletResponse response) 

The include method includes the resource's content, such as a servlet, JSP, and HTML in the response. 

The major difference between the classes PrintWriter and ServletOutputStream are:

  1. PrintWriter is built by character-stream class whereas ServletOutputStreams are built by byte-stream classes.
  2. In case of character-based information we can only go for PrintWriter classes but in case of the requirements for primitive values then we can go for ServletOutputStream.
  3. ServletOutputStream also provides functionalities to process byte-oriented information like image loading.  
  4. To get the instance of ServletOutputStream class we can call getOutputStream() method of ServletResponse interface. To get the instance of PrintWriter class, we must call getWriter() ServletResponse interface method.

Servlets in the application are loaded using the load-on-startup element which will be mentioned in the web.xml file. The load-on-startup element holds the integer values both positive and negative. And it gets called when the servlet init() method is invoked.

If the integer is negative the container loads the servlet based on the requirement and no specific invocation on startup.

But if the integer is zero '0' or positive the servlet invokes the init() method and calls the respective first servlet. Also, if the integer is 1 or 2 or 3 then lower integer servlet are loaded.

HTTPSession is an interface. It provides a way to identify a user across more than one page request or visit to a website and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The main purpose of HTTP session is to approach all data of the user until the user session is active. The HttpSession is not thread safe. In general, inside servlet container can be assumed to be in a multithreaded environment. This is also applicable to the object we store in the session.

The new specification version 2.3 of Java servlet introduced a component called Filter. A filter is an object created during the servlet filter specification which is invoked at the preprocessing and postprocessing of a client request. It is used to perform the task which involves filtering of the object's examples like logging, encryption and decryption, input validation, compression etc. 

The servlet filter is predefined, that is the dependency must be defined in the web.xml file. If the dependency is removed from the web.xml file, then automatically the filter will be detached from the servlet. 

There are many interfaces and classes present in javax.servlet package. They are as follows:

Interfaces in javax.servlet package  Classes in javax.servlet package  

1. Servlet 

2. ServletRequest 

3. ServletResponse 

4. RequestDispatcher 

5. ServletConfig 

6. ServletContext 

7. SingleThreadModel 

8. Filter 

9. FilterConfig 

10. FilterChain 

11. ServletRequestListener 

12. ServletRequestAttributeListener 

13. ServletContextListener 

14. ServletContextAttributeListener 

1. GenericServlet 

2. ServletInputStream 

3. ServletOutputStream 

4. ServletRequestWrapper 

5. ServletResponseWrapper 

6. ServletRequestEvent 

7. ServletContextEvent 

8. ServletRequestAttributeEvent 

9. ServletContextAttributeEvent 

10. ServletException 

11. UnavailableException 


As I understood by the question is that the getSession() method should return true as its parameter and it should return previous session object, if I consider it based on the question, the session should be in existing stage because to return the previous object the session should be in the running state. Once the user closes the session it will be considered a new object. Also, we cannot pass the session object to another method to get the previous session.

If we are writing any of the servlet-based applications, then there should be a web.xml file. Web.xml file is also called the application descriptor file. This file contains an xml document where we can define all the dependency and load-on-startup features and many more.  

When the server receives the request from the front-end or from the client side, it first invokes the web.xml file, so it chooses the mapping URL to redirect the request. The web.xml file is present in the web-inf folder of the application. 

Also, the web.xml file will contain information about external dependencies and the structure of web components in the module which was defined at run time. 

The servlet web.xml file is used to configure the dependencies about the application. The web.xml is used during the application deployment. Because it provides deployment information and configuration information. The Java servlet application specification will define the descriptor of the web.xml file and adds the schema to it. The main purpose is to fetch the servlet based on the client call and it also holds the information about load-on-startup information.  

The purpose of web.xml file is to define all the application related packages, defined servlets and the required dependencies, so it can load the dependency which can be useful during the application deployment so we no need to add it manually again. 

Whenever we request for any servlet, the servlet container will initialize the servlet and load it which is defined in our config file called web.xml. By default, it will not initialize any servlet. When our context is loaded defining like <load-on-startup>1</load-on-startup> which is also known as pre-initialization of servlet. And if that servlet contains the above tag, it will be loaded first.

Intermediate

Web Applications are modules that run on the server to provide both static and dynamic content to the client browser. Apache webserver supports PHP, and we can create a web application using PHP.  

Java provides web application support through Servlets and JSPs that can run in a servlet container and provide dynamic content to the client browser. Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure like below image.  

One of the most important features of servlets is the Servlet Life Cycle. The servlet engine handles all the security related concerns of the servlet life cycle. Also, servlet can easily and efficiently share data as they share the same JVM.  

The servlet Web Container maintains the life cycle of a servlet Instance. Let us see step by step process of the life cycle of a servlet. 

  1. The first servlet class will be loaded. 
  2. Servlet instance or object will be created in the second stage 
  3. Invocation of init() method happens in third step 
  4. Then service() method is invoked 
  5. At last, destroy() method is invoked. 

As displayed in the above diagram, there are three states of a servlet. Born or new state, ready state, and an end state. At first, the servlet is in the new state, when the servlet is in the new state, the servlet instance is created. Then the invocation of the init() happens. After invoking the init() method, the servlet comes to the ready state.  

During the ready state period, servlet performs all the tasks required for sending or revving the data. Finally, when the Web container invokes the destroy () method, it shifts to the end state of the servlet lifecycle.  

A web server is defined as software or hardware which uses HTTP [Hyper Text Transfer Protocol] and many other application-level protocols to send and retrieve data from the client application. 

Here, the web server's responsibility is to manage the HTTP requests received from the client application and send the response in HTML format. And the web server only understands HTTP specific protocols. 

For example, Apache Tomcat, JBoss application servers internally provides additional features like JMS Messaging support, Transaction Management etc. So, we can conclude that, an application server is also a web server with more functionalities to support developers with Enterprise level applications. 

An HTTP method is said to be idempotent if it returns the same result every time. There are around 5 idempotent HTTP methods, they are, get (), put (), delete (), head (), and options (). While developing an application we should make sure that our application manages to return the same result every time. 

The HTTP method post () is called the non-idempotent method. Because the data while using the post method changes every time for each request. 

For example, to access any page or static images, we should use get () method, because it should return the same object always. But if we must save any user data or student data in the applications, we should go for the post () method, as it will consider each customer as a new user. 

MVC stands for Model View and Controller. Model View and Controller or MVC is a design pattern used to separate the Business logic, Presentation logic, and backend data.

  • Model: Model deals with the behavior and represents the state of the application. It contains data and Business logic of the application.  
  • View: It fetches the information to the user, so that it makes the presentation layer more attractive and appealing. It renders information from the Model using which it generates the output data. 
  • Controller: Controller acts as an interface between Model and the View. It takes input from the user and sends that data to the Model or View. Also, it manages the flow of the execution of the application. 

Servlet filter is an object invoked at the preprocessing and postprocessing of a request. We need servlet filters for the following reason:

  • Logging: Servlet filters are used to Log the request parameter to Log files. 
  • Authentication: Servlet filters are used to authenticate the request received and for the response data. 
  • Authorization: Authorization and Authentication works the same way with Servlet filters. 
  • Formatting: Formatting of the request body/header before sending it to the servlet is handled by Servlet filters. 
  • Compressing: Servlet filters compress the data which needs to be sent as a response to the client. 
  • It also helps in changing the response by adding header information as well as cookies  
<load-on-startup>1</load-on-startup>

The load-on-startup xml tag will be written in the web.xml file. Whenever we send a request for a servlet, the servlet gets placed, then the servlet container will initialize the servlet and load it.  

This process is defined in our config file called web.xml. But, by default, container will not initialize the servlet, when the context is loaded. This can be achieved by defining the servlet in a pre-initialization procedure syntax <load-on-startup>1</load-on-startup>. Then, the servlet that we have defined in the above tag will be initialized at the start when the context gets loaded before even getting the request. 

The code to write a Hello World Program using Servlets is as follows:

import java.io. *; 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class HelloWorld extends HttpServlet { 
      private String message; 
      public void init() throws ServletException { 
             message = "Hello World"; 
      } 
      public void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
             response.setContentType("text/html"); 
             PrintWriter out = response.getWriter(); 
             out.println("<h1>" + message + "</h1>");  
      }  
      public void destroy () {  
      }  
} 

MIME type stands for Multipurpose Internet Mail Extensions, the main purpose of MIME type is to tell the user which type of response content we will be using. It gives information to the client that what type of data it is sending, it can be HTML form or XML form, or text type. So, it will be easier for the receiver to manipulate based on the type of data they are receiving. Some of the most used MIME types are text/HTML, text/ML, and application/XML and many more. 

We can use ServletContext getMimeType() method to get the correct MIME type of the file and use it to set the response content type. It is especially useful in downloading a file through servlet from the server. 

Servlet containers are also known as web containers, for example: JBoss, Tomcat etc. 

Some of the important tasks of servlet container are: 

  • Communication Support: The containers of the servlets provide a flexible way of interaction between the application browser that is the client side and with JSP and servlets. As servlet provides built-in containers we do not have to manage or build socket listeners for handling the web requests from the client application.  
  • Lifecycle and Resource Management: Servlet containers also play a key role in the life cycle of a servlet by managing all the input request and output responses. It controls the application from loading of servlet to memory, initializing the servlet using init (), invoking the service () and finally invocation of destroy () it will manage. The servlet container also provides Java Naming Directory Interface i.e., JNDI support for functionality management and resource pooling.  
  • Miscellaneous Task: The resource pool of the servlet application, memory optimizations, handling garbage collection, security management and its configurations, hot deployment all these tasks can be handled alone by the servlet container.  

When servlet container receives client request, it invokes the service () method which in turn invokes the doGet(), doPost() methods based on the HTTP method of request. The whole purpose of service () method is to forward the request to corresponding HTTP method for implementation. In case, if we want to do some pre-processing of request, we can go for servlet filters and listeners.

HttpServlet init() method and destroy() method are called only once in the servlet life cycle, so we do not need to worry about their synchronization. But the service methods such as doGet() or doPost() will be called for every client request. Since servlet uses multithreading concept, we should provide thread safety in these methods.  

If there are any local variables in service methods, we do not need to worry about their thread-safety because they are specific to each thread but if we have a shared resource then we can use synchronization to achieve thread-safety in servlets when working with shared resources. The thread safety mechanisms are like thread safety in standalone java application.  

These types of questions one can also expect in java servlet interview questions and answers for experienced level because it holds the concepts of both Java and servlet. 

An abstract class is nothing but hiding the implementation details and providing only the functionality to the end user. 

In case of HttpServlet, HttpServlet class provides a HTTP protocol implementation of servlet, but it is defined as an abstract class because there is no implementation logic in vice() methods such as doGet() and doPost() and we should override at least one of the service methods. That is why there is no point in having an instance of HttpServlet and it is declared an abstract class.  

A staple in Java Servlet interview questions be prepared to answer this one. Consider a scenario where we must initialize some resources before our servlet processes client requests. Then we should override the init() method.  

If we override init(ServletConfig config) method, then the first statement should be super(config) to make sure the superclass init(ServletConfig config) method is invoked first.  

That is why GenericServlet provides another helper init() method without argument that gets called at the end of init(ServletConfig config) method. We should always utilize this method for the overriding init() method to avoid any issues as we may forget to add super() call in overriding init() method with ServletConfig argument. 

 The GET and the POST methods are known as the HTTP methods of web applications. The major difference between these Get and post methods are:  

  1. GET i.e., get () is safe and are idempotent. Whereas POST i.e., post () are non-idempotent methods and considered not safe. 
  2. Using get () method we can send only limited data and these data are sent in the header request URL, but in terms of post (), we can send large amount of data and the data is sent as a part of request body. 
  3. In terms of security, get () method is not secure, as the data is exposed in the header URL so user can easily bookmark the request and can send the same request back-to-back, when it comes to post (), it is more secure because the data is sent as a part of request body, and it is not possible to bookmark post () request. 
  4. The default HTTP method is gotten (), whereas for post () we need to specify. 

Example forget () is the hyperlinks used in the application pages. 

The ServletConfig which is present in javax.servlet.ServletConfig package, is used to pass configuration information to the servlet. Every servlet has its own ServletConfig object. For instantiation of ServletConfig object is handled by servlet container. We can specify the parameters in web.xml file or we can also mention using annotation that is @webInitParam(). Also, ServletConfig provides getServletConfig() method to get the object of ServletConfig from the servlet.

The ServletContext is present in javax.servlet.ServletContext package. This package provides access to the parameters of servlet application. The ServletContext is known to be the unique object which can be accessible by all the servlet based, web applications.  

Consider a case, where we want to call init() to all our servlet application or it could be a multiple init() method call scenario, in such cases we can go for ServletContext object then we can define respected parameters in the web.xml file using the xml element <context-param>. 

To access ServletContext object we can call getServletContext() method of ServletConfig. It also provides context objects which are unique for handling group of servlets and are tied to the specific part of the URL. 

ServletContext also provides some utility functions some of them are getMimeType() method, getResourceAsStream() method etc. Also, it has been enhanced with its features in Specs 3, so we can add servlet listeners, servlet filters programmatically to the application. 

Let us understand the differences between ServletConfig and ServletContext: 

  1. ServletConfig creates a unique object per servlet whereas ServletContext is a unique object for the entire application. 
  2. ServletConfig is used to provide the init() configuration and parameters to the servlet, whereas ServletContext is used to provide application level init() method parameters, so these parameters can be accessed by all other servlets used in the application. 
  3. In terms of ServletConfig we cannot set attributes externally, but in ServletContext we can set attributes so the existing or new servlets can be used for their implementation.  

Servlet Wrapper classes are nothing but HTTP API's. They provide two wrapper classes they are, HttpServletRequestWrapper and HttpServletResponseWrapper. These wrapper classes are used to provide support to the developers in writing custom implementation of the servlet request and response types. We can also extend these classes and override specific methods needed to implement custom request object and response object. Also, these Servlet wrapper classes are not used in general servlet programming.

Advanced

Here, URL Encoding is the process of converting data into common extensible form so that it can travel across the network without any issues. URL Encoding strikes out the white spaces and replaces special characters with escape characters. We can use java.net.URLEncoder.encode(String str, String Unicode) to encode a String.  

URL Decoding is the reverse process of encoding, and we can use java.net.URLDecoder.decode(String str, String Unicode) to decode the encoded string. For example, "Elon’s Data" is encoded to "Elon%27s+Data".

One of the most frequently posed Servlet Interview Questions, be ready for it. The technique behind RequestDispatcher interface is to dispatch or send requests to another resource like Servlet, JSP or HTML. It acts as a bridge layer to communicate and interact between two resources. The RequestDispatcher interface can also be used to include the content of another resource.  

There are two main methods used in RequestDispatcher interface, they are: 

public void forward(ServletRequest request, Servlet Response response) throws ServletException,java.io.IOException 
public void include(ServletRequest request, ServletResponse response) throws ServletException,java.io.IOException  

As we know, war files mean, Web Archives (war) file, which contains all the contents of a Web application. The War file can be created using jar tool, which can be found in jdk/bin directory. We can also create war files using IDEs like Eclipse, STS, NetBeans by exporting the application as war files, this option can be seen in the IDEs. 

Below command is used to create war files from console: 

jar -cvf projectName.war*  

Servlets are built using Java, so it is known as a Java tool, which is used to create Java Web Applications. The main purpose of these server-side Servlets is to create Dynamic Web Applications. The servlet acts as a mediator between the HTTP request and the database. As servlets are built on top of Java so it holds the java properties like Robus and Scalable features. So, it is called a server-side programming language.

When the request is received from the client side of the application, the servlets redirect these requests into appropriate servlet class or JSP pages and then send back the response as a result in the form of a JSP or HTML pages.

Usually, servlet container loads a servlet on the first client request. In some cases, the servlet is heavy, and it takes time to load the servlet, but the requirement for us to load it on application startup. We can use a load-on-startup element with servlet configuration in the web.xml file or use Web Servlet annotation on loadOnStartup variable to tell the container to load the servlet on system startup.

<servlet> 
<servlet-name>foo</servlet-name> 
<servlet-class>com.foo.servlets.Foo</servlet-class> 
<load-on-startup>5</load-on-startup> 
</servlet> 

The value of load-on-startup should always be in an Integer that is an int value. If the in value is negative, then the servlet container will load the servlet based on the client requests or the requirement.  

But if the integer value is positive or zero (0), then the container will load the application on startup. If there are multiple servlets with integer values like 0, 1, 2, 3 in such cases the servlet will load the requirement which has lower integer value. 

Servlet Chaining is a way where the output of one servlet is piped to the input of another servlet, and the output of that servlet can be piped to the input of yet another servlet and so on. Each servlet in the pipeline can either change or extend the incoming request. The response is returned to the browser from the last servlet within the servlet chain.  

In the middle, the output out of each servlet is passed as the input to the next servlet, so every servlet within the chain has an option to either change or extend the content. The figure below represents this. Servlets can help in creating content via servlet chaining. 

This question is a regular feature in Servlet Interview Questions, be ready to tackle it. It is standard to have a single servlet instance for each registered name of the servlet. However, instead of this, it is also possible for a servlet to choose to have a pool of instances created for each of its names that all share the task of handling requests. These servlets indicate this action by implementing the javax.servlet.SingleThreadModel interface. 

According to the Servlet API documentation, a server loading the SingleThreadModel servlet should guarantee, “that no two threads will execute concurrently the service method of that servlet.” Each thread uses a free servlet instance from the pool to achieve this. Therefore, any servlet using the SingleThreadModel isn’t needed to synchronize usage to its instance variables and is considered thread-safe. 

Let us know the major differences between ServletConfig and ServletContext below: 

ServletConfigServletContext

ServletConfig is a unique object per servlet. 

ServletContext is a unique object for a complete application. 

ServletConfig is used to provide the init parameters to the servlet. 

ServletContext is used to provide the application-level init parameters that all other servlets can use. 

Attributes in the ServletConfig object cannot be set. 

Attributes in ServletContext can be set so that the other external servlets can be reused. 

Syntax for ServletConfig: 

public ServletConfig getServletConfig();  
Example of ServletConfig: ServletConfig config=getServletConfig(); 

Syntax for ServletContext: 

public ServletContext getServletContext(); 
Example for ServletContext: ServletContext application=getServletContext(); 
<web-app>     
<servlet>   
<servlet-name>soorajChand</servlet-name>   
<servlet-class>DemoServlet</servlet-class>   
</servlet>   
<servlet-mapping>   
<servlet-name>soorajChand</servlet-name>   
<url-pattern>/welcome</url-pattern>   
</servlet-mapping>   
</web-app>   

The public service method converts the ServletRequest object into the HttpServletRequest type and ServletResponse object into the HttpServletResponse type. Then, call the service method passing these objects. The internal code is as below:

publicvoid service (ServletRequest req, ServletResponse res) throws ServletException, IOException  {   
           HttpServletRequest request;   
HttpServletResponse response;   
            try   
    {   
            request = (HttpServletRequest)req;   
            response = (HttpServletResponse)res;   
        }   
        catch(ClassCastException e)   
        {   
            thrownew ServletException("non-HTTP request or response");   
        }   
        service (request, response);   
    }   

Exception Handling is mechanism, where it disturbs the normal flow of the application. In case of servlets, it internally calls the doGet() and doPost() methods and these methods will throw ServletException and IOException. But the exceptions can only be handled in the backend code and the browser does not understand these exceptions.  

So, when an exception is thrown by the application, then the servlet container processes the exception internally and generates the HTML pages by sending HTTP code like 404, 500 based on the exception. 

In servlets, to handle the programming exceptions, servlets API supports customized exceptions and error handling servlets which we can configure in the deployment descriptor. This deployment descriptor helps in sending the response in the form HTML pages with appropriate error page so user can understand what went wrong. 

The Web.XML configuration is as follows: 

<error-page> 
    <error-code>404</error-code> 
    <location>/AppExceptionHandler</location> 
</error-page> 
<error-page> 
    <exception-type>javax.servlet.ServletException</exception-type> 
    <location>/AppExceptionHandler</location> 
</error-page> 

Java application runs from the main () method, but in terms of servlet, it does not have a main () method instead of that is has servlet web containers. The web container receives the request from the client and then sends back the response using the appropriate servlet.

Yes, we can refresh a servlet automatically in a few ways. One such way is to add "Refresh” response header, which contains the number of seconds after which the refresh should occur. Below example shows how refresh can be triggered:

import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.Date; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
  
public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { 
      private static final long serialVersionUID = 1L; 
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
            performTask(request, response); 
      } 
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, 
      IOException { 
            performTask(request, response); 
      } 
      private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, 
      IOException { 
            response.setContentType("text/html"); 
            response.addHeader("Refresh", "5"); 
            PrintWriter out = response.getWriter(); 
            out.println("TestServlet says hi at " + new Date()); 
      } 
} 

 Let us understand the differences between sendRedirect() and forward()  

  • sendRedirect(): sendRedirect() method is defined in HttpServletResponse Interface. 

The syntax for the sendRedirect() method is as follows: 

void sendRedirect(String URL) 

This method redirects the request received from the client and sends it to different servers or context. These scenarios are handled by web containers. The web containers transfer the request using the browser as a new request. The process is called client-side redirect. 

  • forward (): forward () method is defined in the RequestDispatcher Interface. 

The syntax for the forward() method is as follows: 

forward(ServletRequest request, ServletResponse response) 

The forward() method processes the request within the same server and then passes it to servlets or jsp files. It is handled by Web container. When the forward() method is called, the request is sent to other resource and the information related to client is mentioned in the requestDispatcher object either using ServletContext or request. 

The service() method is said to be the starting point of the servlet application as how we have main() method in java. The service() method is called by the servlet container to handle the requests coming from the client/browsers and it sends the required response based on the request.  

For every request, the server creates a new thread and then calls the service() method. Then the service() checks the HTTP request type and sends it to the respective method. 

Example:

public void service(ServletRequest request, ServletResponse response) 
throws ServletException, IOException{ 
} 

The container calls the service() method and service method invokes doGet(), doPost(), doPut(), doDelete(), methods as needed. And we must override either doGet(s) or doPost() depending on the client-side request.  

Cookie can be created using the following steps: 

Step 1: Creating a Cookie object 

First, call the Cookie constructor using cookie name and cookie value of datatype String. The symbols ([] () =,” /? @: ;) should be taken care of while declaring name and values. 

Cookie cookie = new Cookie ("key", "value"); 

Step 2: Setting the maximum age 

We can use setMaxAge to specify how long the cookie should be valid. Example the following code is to set up a cookie for 24 hours. 

cookie.setMaxAge(60*60*24); 

Step 3: Sending the Cookie into the HTTP response headers 

We can also send cookie in the response header using response.addCookie  

Example:  response.addCookie(cookie); 

Servlet reloading may appear to be a simple feature, but it is quite a trick and requires quite a hack. The objects in ClassLoader are developed to load a class just once. To solve this limitation and to load servlets multiple times, servers use custom class loaders. These custom class loaders load servlets from the default servlets directory. 

When a server dispatches a request to a servlet, it first checks if the servlet’s class file has changed on disk. If the change appears, then the server abandons the class that the loader used to load the old version and then creates a new instance of the custom class loader to load the new version. Old servlet versions can stay in memory indefinitely, but the old versions are not used to handle any more requests.

In the below example, we are storing the username in the cookie object and then referring it using another servlet. As we know each session differs for each user. So, if we try to access the user data from other browsers using different values, we will get a different output.  

Index.html 

<form action="servlet1" method="post">   
         Name:<input type="text" name="userName"/><br/>   
        <input type="submit" value="go"/>   
</form>

FirstServlet.java

import java.io.*;   
import javax.servlet.*;   
import javax.servlet.http.*;   
public class FirstServlet extends HttpServlet {   
  public void doPost(HttpServletRequest request, HttpServletResponse response){   
    try {   
    response.setContentType("text/html");   
    PrintWriter out = response.getWriter();            
    String n=request.getParameter("userName");   
    out.print("Welcome "+n);   
    Cookie ck=new Cookie("uname",n);//creating cookie object   
    response.addCookie(ck);//adding cookie in the response   
    //creating submit button   
    out.print("<form action='servlet2'>");   
    out.print("<input type='submit' value='go'>");   
    out.print("</form>");          
    out.close();  
        }catch(Exception e){System.out.println(e);}   
  }   
} 

SecondServlet.java 

import java.io.*;   
import javax.servlet.*;   
import javax.servlet.http.*;   
public class SecondServlet extends HttpServlet {   
public void doPost(HttpServletRequest request, HttpServletResponse response){   
    try{   
    response.setContentType("text/html");   
    PrintWriter out = response.getWriter();   
    Cookie ck[]=request.getCookies();   
    out.print("Hello "+ck[0].getValue());   
    out.close();   
         }catch(Exception e){System.out.println(e);}   
    }     
} 

Web.xml

<web-app>   
<servlet>   
<servlet-name>s1</servlet-name>   
<servlet-class>FirstServlet</servlet-class>   
</servlet>    
<servlet-mapping>   
<servlet-name>s1</servlet-name>   
<url-pattern>/servlet1</url-pattern>   
</servlet-mapping>   
<servlet>   
<servlet-name>s2</servlet-name>   
<servlet-class>SecondServlet</servlet-class>   
</servlet>     
<servlet-mapping>   
<servlet-name>s2</servlet-name>   
<url-pattern>/servlet2</url-pattern>   
</servlet-mapping>   
</web-app>   

We can define a constructor for servlet, but I don't think it is of any use because we won't be having access to the ServletConfig object until unless servlet is initialized by the container. Ideally, if we must initialize any resource for the servlet, we should override init() method where we can access servlet init parameters using ServletConfig object.

Servlet attributes are used for inter-servlet communication, we can set, get, and remove attributes in web application. There are three scopes for servlet attributes – request scope, session scope and application scope. ServletRequest, HttpSession, and ServletContext interfaces provide methods to get/set/remove attributes from request, session, and application scope, respectively. Servlet attributes are different from init parameters defined in web.xml for ServletConfig or ServletContext.

 Below are the steps to be followed while creating JDBC connection: 

First, import JDBC packages, Register the JDBC driver class: After importing the packages, we must register the driver class, so the JVM loads the desired Driver implementation into memory. We can use java's forName() method to register the driver class into memory. And this method invokes and registers the driver automatically.

try { 
     Class.forName("oracle.jdbc.driver.OracleDriver"); 
} 
catch(ClassNotFoundException ex) 
       System.out.println("Error: unable to load driver class!"); 
       System.exit(1); 
} 

The second approach to register a driver is to use the static registerDriver()method.  

try { 
      Driver userDriver= new oracle.jdbc.driver.OracleDriver(); 
      DriverManager.registerDriver( userDriver); 
} 
catch(ClassNotFoundException ex){ 
      System.out.println("Error: unable to load driver class!"); 
      System.exit(1); 
} 

After loading the driver, we can establish connection to the Driver Manager using DriverManager.getConnection() method −  

  • getConnection(String url) 
  • getConnection(String url, Properties prop) 
  • getConnection(String url, String user, String password) 

Create a connection object 

Now we can create a connection using the database URL, username, and password and, we can use properties object. 

Close Connection: 

Finally, to end the database session, we must close all the database connections. If closing the connection is not handled by the development team, Java’s garbage collector will close the connection. 

conn.close();  

Description

Servlet Interview Preparation - Tips and Tricks

In this section let us see some of the best practices for java servlet interview questions and effective tips to qualify the servlet interview questions and answers. 

  • The first thing one should know before learning servlets is to understand the MVC design pattern. Because the Servlets are meant for building web applications, where web applications include Model View and the Controller part. 
  • It is suggested not to use Java code in HTML pages while creating servlet applications. 
  • Choose the right include mechanism: which says that, keeping the static data pages in a separate directory or folder does not get affected while manipulating the dynamic web pages. 
  • Understand each tag used in the web.xml file. Because servlet applications are built based on the configuration done in the web.xml file. 
  • Do not try to mix business logic with the presentation layer of the application. 
  • Understand and read about JSTL tags and try to use that in the JSP pages to call java objects.

How to Prepare for a Servlet Interview? 

Servlets are an important topic of Java EE and all web application frameworks such as Spring and Struts are built on top of servlets. This makes servlet interview questions a hot topic in interviews. Here is the provided list of servlet interview questions and answers for freshers to servlet interview questions for experienced to help you tackle topics related to servlets and web applications in java. Also, you can check the best Programming course to understand more about Java and its versions.  

A promising career as a Servlet developer can begin by being well-informed and once certified, there are various job profiles available including: 

  • Web developer 
  • Software engineer 
  • Software architect 
  • Enterprise Java developer 
  • Servlet developer 
  • Web application developer 
  • Java servlet developer 
  • Software developer, Servlets and JSP 
  • Servlets and JSP developer 

Below are some of the top companies using Servlet Technology to build dynamic server-side applications. Since Servlet is built using Java, most of the big tech companies use a servlet as their core technology. A few of them are like: 

  • Slack 
  • Flipkart 
  • Pinterest 
  • Intel 
  • VMware and many more 

What to Expect in a Servlet Interview?

JSP Servlet interview questions can be based on understanding the Model View Controller Design patterns, Servlet methods and sessions, cookies and many more. These are the hot topics to be known before standing for the Servlet interviews. We can conclude that the above interview questions and answers are useful if you are looking for JSP Servlet interview questions and answers for experienced and beginner level. 

Also, the expectation also stands the same for all the levels, and it might differ only in terms of the coding round of writing the complete Servlet Web application as a demo to the interviewer. 

Summary

Unlike CGI and other programming languages, servlets are handled by separate threads within the webserver process. So, it is said that servlets are efficient and scalable to handle huge applications. Also, we know servlets run within the web server, they can interact closely with the server to do things that are not been handled by CGI or other legacy programming languages.  

The major advantage of servlets is they are portable, as they are built on top of Java, so they can be cross-platform of the different operating systems. All the major web servers like tomcat, JBoss, WebSphere, Jetty, and Oracle WebLogic. Support servlets. To understand and get a good knowledge of any of the languages, practice must require, we can read the questions and understand the concepts but when it comes to an actual interview, we may feel missing the concepts which we have read, so it is always the best practice to code more to understand more.  

The main concept to be focused on servlet is to understand how web.xml is configured, how the sending the receiving data flow works, also how to interact with a frontend like HTML, and JSP pages. If you understand this logic, then it will be easier to understand any frameworks which are built using Java and servlets. To understand more in-depth concepts and their different aspects, join our best programming courses and build a strong fundamental base. 

Read More
Levels