Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconTop 24 Servlet Interview Questions and Answers

Top 24 Servlet Interview Questions and Answers

Last updated:
29th Jun, 2023
Views
Read Time
12 Mins
share image icon
In this article
Chevron in toc
View All
Top 24 Servlet Interview Questions and Answers

A servlet is a Java-based software that extends a server’s capabilities. It’s a vital component of any server as they respond to container requests and for hosting web applications. To run the back-end of a website, aka, server-side, you’ll need to be familiar with servlets and how they operate. 

As Java-based servers are vastly popular, learning about servlets is essential if you want to work with web servers. 

If you were preparing for a developer interview, you’ve come to the right place. The following servlet interview questions will give you an idea of what to expect from the interview. 

Check out our free courses to get an edge over the competition

Ads of upGrad blog

List of Top Servlet Interview Questions

  1. What do you mean by a Servlet?

Ans: Servlets are Java technologies, and the container that manages them is called the servlet engine. A servlet produces dynamic content and interacts with the client through Request and Response. They usually run when you click a link or perform any type of action on a website. Servlets are similar to applets, but the difference is they are processed on the server while an applet is processed on the client’s machine. 

  1. What is a servlet container?

Ans: Servlet containers are part of a web server that offers network services. They depend on the MIME-based requests and responses. A servlet container handles servlets. 

Check out upGrad’s Java Bootcamp

  1. Why do we use servlets?

Ans: Usually, we use servlets because they are platform-independent. Moreover, they are compiled into a platform-neutral byte code. You can load Java byte code dynamically into a Java-enabled web server.

  1. What do you mean by a filter?

Ans: Filters are reusable pieces of code that can transform the content of HTTP requests, response, and headers. 

  1. What is the difference between an application server and a web server?

Ans: A web server handles HTTP requests from the client browser and responds with HTML response. It processes the HTTP language and runs on the HTTP protocol. 

On the other hand, an application server provides additional features such as JMS Messaging support, Enterprise JavaBeans support, etc., along with the basic functionalities of a web server.

Explore Our Software Development Free Courses

  1. What do you mean by a session?

Ans: Session means a period of time. In servlet, sessions are objects a servlet uses to track user interaction with the web applications across multiple HTTP requests. 

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN) 

  1. What do you mean by a servlet context?

Ans: Servlet context defines a set of methods a servlet employs to communicate with its servlet container. The servlet container creates this object to share the initial configuration or parameters to the whole application

You can get the ServletContext object by using the getServletContext() method. There is only one servlet context for an application. You can use ServletContext to share information in the whole application. 

Note: This is among the most important servlet interview questions and answers. 

  1. What does servlet-mapping mean?

Ans: Servlet mapping gives you the specific web container of which java servlet should be invoked for a particular URL. It would map the URL patterns to the servlet. When a client sends a request, the servlet container determines which application it would forward it to, and the system matches the context path to perform servlet mapping. 

  1. How do you refresh automatically after entering new data into the database?

Ans: You can use Refresh in Server Push and Client-side to refresh automatically when entering new data into the database. 

Explore our Popular Software Engineering Courses

  1. Explain the life cycle of a servlet.

Ans: The life cycle of a servlet is divided into five steps. First, you load the servlet class then create the servlet instance. After that, you invoke the init() method, then the service method and finally the destroy() method. A servlet has three states: new, ready, and end. 

The servlet would be in the new state when it is created. It goes into the ready state after you invoke the init() method. Finally, it goes into the end state when the destroy() method is invoked. 

  1. What new features were added in Servlet 2.5?

Ans: Servlet 2.5 came with the following new features: 

  • J2SE 5.0 dependency
  • Annotations support
  • Classloading
  • New web.xml
  • Edge case clarifications
  • Restrictions removal
  1. Which interface do all servlets implement (or should implement)?

Ans: All servlets must implement the servlet interface. 

  1. When is a servlet loaded?

Ans: A servlet is loaded when:

  • The first request is made. 
  • Server and autoloading startup.
  • A single instance answers all the requests simultaneously, hence, saving memory. 
  • The Administrator loads manually.
  1. When is a servlet unloaded?

Ans: A servlet is unloaded when the server shuts down or the administrator unloads manually. 

  1. What do you mean by MIME Type?

Ans: MIME stands for Multipurpose Internet Mail Extension. The MIME type is an HTTP header that gives information about what we’re sending to a browser. It helps the client in data rendering. Common MIME types are text (HTML), text (plain), images (jpeg), application (jar), etc. 

To get the correct MIME type of a particular file, you can use the ServletContext getMimeType() method. It comes in handy while downloading a file through servlets from a server. 

In-Demand Software Development Skills

  1. What is the difference between the POST and GET methods?

Ans: The primary difference between the POST and GET methods is that the POST method carries the response parameters in the message body while the GET method carries the response parameters appended in the URL string. 

  1. What do you mean by a web application? 

Ans: A web application is a module that runs on the server to provide dynamic and static content to the client browser. The Apache web server supports PHP, and you can create a web application using the same. 

Java supports web applications through JSPs, and servlets that run in a servlet container offer dynamic content to the client browser. 

  1. What advantages does a servlet offer over CGI?

Ans: The CGI technology had many shortcomings. Servlets were introduced to overcome the same. 

Servlets offer better performance than CGI in terms of utilising memory and processing time. They use the benefits of multithreading, where they create a new thread for every request, enhancing their speed greatly. In contrast, CGI creates a new Object for every request, which is relatively slower than the servlets’ process. 

Servlets are system and platform-independent. You can run a servlet-based web application on any standard web container (Glassfish, Tomcat, and JBoss) and operating systems (Unix, Windows, Mac, etc.). 

The learning curve for servlets is pretty small as you only need to handle the business logic for the application. Moreover, their container handles the servlet’s life cycle, so there’s no risk of memory leaks, garbage collection, and security.

  1. What do you know about the ServletConfig object?

Ans: You use the ServletConfig object to give configuration information to a specific servlet. Each servlet has a unique ServletConfig object and the servlet container instantiates it. You can give servlet init parameters through the WebInitParam annotation. To get the ServletConfig object of a servlet, you’d have to use the getServletConfig() method. 

  1. What tasks does a servlet container perform usually?

Ans: A servlet container performs the following tasks:

  • It facilitates communication between the servlets, JSPs and the web client. You don’t have to build a server socket to receive requests, parse them and generate responses because of the container. The container takes care of these tasks, allowing you to focus on the business logic. 
  • The servlet container handles the life cycle of servlets. It loads the servlets into memory, initialises them, invokes the necessary methods and destroys them. Servlet containers also simplify resource management by offering utilities such as JNDI. 
  • Servlet containers create new threads for every request and give servlets request and response objects. This way, you don’t have to initialise the servlets for every request, saving a lot of memory and time. 
  • Servlets compile JSPs and convert them to servlets to manage them like servlets, simplifying your task. 
  1. What do you mean by the request dispatcher?

Ans: You use the RequestDispatcher interface to forward requests to another resource. This resource could be another servlet in the application, HTML or JSP. You can use the RequestDispatcher interface to add the content of another resource to your response. It is an excellent solution for inter-servlet communication. 

Read our Popular Articles related to Software Development

You can define two methods in the RequestDispatcher interface: 

  • The void forward method. It forwards the request from one servlet to a different resource. 
  • The void include method. It adds the content of another resource to your response. 
  1. What is the difference between ServletContext and ServletConfig?

Ans: The ServletContext is a unique object for the entire application, while ServletConfig is a unique object for a servlet. You can use the ServletContext to give init parameters across the complete application, which all servlets can utilise. On the other hand, you can use the ServletConfig to provide init parameters only to a specific servlet. 

You can set attributes in ServletContext, which other servlets can use, but you can’t choose attributes in ServletConfig.

Note: This is among the most crucial servlet interview questions and answers. You should prepare it carefully. 

  1. What do you know about servlet attributes?

Ans: Servlet attributes help you in inter-servlet communication. You can set, get and remove attributes in the application. Servlet attributes have three scopes, request scope, session scope, and application scope, namely. They are different from init parameters. 


upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

  1. How would you call a servlet from another servlet? 

Ans: You can use the RequestDispatcher forward() to forward the request processing to a different servlet. If you want to add another servlet output to a response, you can use the RequestDispatcher include() method. 

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

What are the various methods for session management in servlets?

It is one of the most detailed servlet interview questions and answers that you should be prepared with. The different methods in servlets session management are as follows:

HTML Hidden Field

The <input type=” hidden”> refers to a hidden input field. A hidden field enables web developers to incorporate data that cannot be seen or modified by users once a form is submitted. A hidden field also contains database records that must be updated while the form is submitted. 

User Authentication

A user often needs to access a protected resource, like a JSP page. Once the user is authenticated, the servlet container makes the resource available. Otherwise, the user will be required to enter a username and password. 

Session Management API

Session management API is built over the request-response methods for session tracking. Session tracking or management in servlet helps in maintaining the state or data of a user. 

URL Rewriting

URL rewriting refers to automatically altering a program used to manipulate the URL parameters. URL manipulation is usually leveraged for the convenience of a web server administrator. However, hackers also focus on URL manipulation for various nefarious purposes. 

How can an application exception handling be done with the help of a servlet?

It is one of those JSP servlet interview questions where you need to talk about the doGet() and doPost() methods. These two methods are known for throwing the ServletException and IOException. Remember that the browser only understands HTML. 

So when such an exception is thrown by an application, the servlet container will process the exception to generate an HTML response. The same thing happens due to other errors like error 404. 

In this JSP and Servlet interview question, you will also have to talk about the servlet API. It can support customized Exception and Error Handler servlets that can be configured within the deployment descriptor. Apart from generating an HTML response valuable to the user, the API can also send a link to the application home page or shed light on what went wrong. 

The Web.XML configuration can be explained as the following:

<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>

How can you refresh the servlet on the client and server-side automatically?

Ads of upGrad blog

You will find a couple of ways to refresh the servlet on the client and server-side automatically. The first way is to include a “Refresh” response header with the number of seconds after which a refresh should take place. An example of this is as follows:

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());
      }
}
]

Conclusion

The above servlet interview questions and answers should have helped you understand what kind of questions an interview would ask you. We recommend bookmarking this page so you can come back to it later and revise the questions several times. 

Try to remain calm and composed during the interview. It would help you listen closely to the questions and answer them accordingly. You can check out our Executive PG Programme in Software Development with Specialisation in Full Stack Development to learn more advanced concepts about Java and its related subjects.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What are servlets in Java?

A servlet is a Java class which can be invoked by an HTTP server. Servlets are typically used in the development of web applications. The main purpose of a servlet is to handle requests from an HTTP client and to return a suitable response. There are many types of servlets but the most popular one is the Java Server Pages(JSP) as they can be used to create dynamic web content.

2How does the request-response in a Java servlet works?

Servers use servlets to respond to the requests from the user. A servlet can be used to download information from a database, send an e-mail, or display information. It is a small program that performs a particular task for the server. Servlets are written in Java and compiled into a single class file. Then, they are deployed to the web server. Once deployed, the servlets are ready to accept requests from users. A request can be anything from a user clicking on a link to a user filling a form. The request is sent to the server where it is routed to the appropriate servlet. The servlet then processes the request and sends back a response. This response can differ depending on the type of request. For example, if the user was requesting information, the servlet could return that information to the user. If the servlet is responding to a form request, it could send a confirmation e-mail to the user or a notification about the submission.

3What is the lifecycle of a servlet?

A servlet can be said to have three stages in its lifecycle: 1. Loading 2. Execution 3. Destroying. During loading, the servlet receives some initialization parameters. These parameters are defined in the deployment descriptor. Once loading is complete, the servlet can be called by the servlet container in a number of ways - by calling its init() method, by ajax calls or by lifecycle events. The next, and final stage, is destruction, i.e. when the servlet is removed from the container. There are several ways in which a servlet is removed from the servlet container, for example, when the container is stopped, or when the web application is stopped.

Explore Free Courses

Suggested Blogs

Full Stack Developer Salary in India in 2024 [For Freshers &#038; Experienced]
907173
Wondering what is the range of Full Stack Developer salary in India? Choosing a career in the tech sector can be tricky. You wouldn’t want to choose
Read More

by Rohan Vats

15 Jul 2024

SQL Developer Salary in India 2024 [For Freshers &#038; Experienced]
902296
They use high-traffic websites for banks and IRCTC without realizing that thousands of queries raised simultaneously from different locations are hand
Read More

by Rohan Vats

15 Jul 2024

Library Management System Project in Java [Comprehensive Guide]
46958
Library Management Systems are a great way to monitor books, add them, update information in it, search for the suitable one, issue it, and return it
Read More

by Rohan Vats

15 Jul 2024

Bitwise Operators in C [With Coding Examples]
51783
Introduction Operators are essential components of every programming language. They are the symbols that are used to achieve certain logical, mathema
Read More

by Rohan Vats

15 Jul 2024

ReactJS Developer Salary in India in 2024 [For Freshers &#038; Experienced]
902674
Hey! So you want to become a React.JS Developer?  The world has seen an enormous rise in the growth of frontend web technologies, which includes web a
Read More

by Rohan Vats

15 Jul 2024

Password Validation in JavaScript [Step by Step Setup Explained]
48976
Any website that supports authentication and authorization always asks for a username and password through login. If not so, the user needs to registe
Read More

by Rohan Vats

13 Jul 2024

Memory Allocation in Java: Everything You Need To Know in 2024-25
74112
Starting with Java development, it’s essential to understand memory allocation in Java for optimizing application performance and ensuring effic
Read More

by Rohan Vats

12 Jul 2024

Selenium Projects with Eclipse Samples in 2024
43493
Selenium is among the prominent technologies in the automation section of web testing. By using Selenium properly, you can make your testing process q
Read More

by Rohan Vats

10 Jul 2024

Top 10 Skills to Become a Full-Stack Developer in 2024
229998
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

10 Jul 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon