Home  >  Blog  >   General  > 

Top Servlet Interview Question And Answers

The ease with which high-end web applications may be developed nowadays is largely due to Java Servlets. As a result, Java Web Application Technology is becoming more popular in the industry nowadays. This blog will go over the most often asked Servlet Interview Questions from the top companies.

Rating: 4.6
  
 
327
  1. Share:
General Articles

A servlet is an extension of a server. It's a Java class that's been loaded to boost the server's performance. It improves web server functionality by allowing for dynamic responses and data durability. A servlet is safe and portable since it runs on the server inside a Java Virtual Machine (JVM). Servlets can only work within the server's domain. These do not necessitate the use of Java in the web browser.

We have divided this Interview questions blog into three sections for your easy understanding,

Servlet Interview Questions for Freshers

If you're looking for a Fresher role, you'll need to know the answers to these servlet interview questions given below.

1. What is a Servlet?

Ans: A servlet is a Web server that executes a short Java programme. Servlets accept and reply to requests from Web clients, most commonly via HTTP (HyperText Transfer Protocol). Servlets can also use a library of HTTP-specific calls and benefit from all of the mature Java language's features, such as portability, performance, reusability, and crash protection. Servlets are frequently utilised in browsers to provide rich interaction functionality for users (clicking links, form submissions, etc.).

2. How do you write a servlet part of a web application?

Ans: To create a servlet for a web application, follow these steps:

  • Create a Java class that extends the base class javax.servlet.http.HttpServlet.
  • Import the classes from servlet.jar (or servlet-api.jar). These will be needed to compile the servlet.

3. What are some of the advantages of Servlets?

Ans: In comparison to alternative approaches, servlets offer a lot of benefits. Power, integration, efficiency, safety, portability, endurance, elegance, extensibility, and adaptability are just a few of them. Servlets have the following advantages:

  • We can write the servlet code within the JSP, useful for changing ordinary HTML.
  • Java multithreading is included in servlets.
  • Exception handling can be utilised.
  • A layer of servlets separates the application's business logic.
  • Developers will find it simple to display and process data.
  • Servlets make editing HTML pages a breeze.
  • The application's business logic is separated from the servlet layer.
  • Servlets have all of the benefits of Java, such as multithreading, exception handling, and so on.

4. What is a Cookie?

Ans: A cookie is a little bit of data passed from one client request to the next. A cookie has a name, a single value, and optional properties including comments, link and domain identifiers, a max-age, and a sequence number.

5. What is the life-cycle of a servlet?

  • Servlet is loaded.
  • Servlet is initialised
  • Service the requested
  • Servlet is destroyed

MindMajix YouTube Channel

6. How can we refresh automatically when new data has entered the database?

Ans: Client-side refresh and server-side push can automatically refresh the database as new data is entered.
The following code section can be used to update the database automatically.

response.setHeader("Refresh",5);
After every 5 seconds, the browser will be updated.
response.setHeader("Refresh","5", URL="http://localhost:8080/myServlet/Request.do0);

After 5 seconds, the Request will be refreshed.

7. What are the features added in Servlet 2.5?

Ans: The following are some of the new features in Servlet 2.5:

  • Dependency on J2SE 5.0
  • Support for annotations
  • Loading the class
  • Several web.xml
  • Removed restrictions
  • Edge case clarifications

8. How does a servlet get access to its init parameters?

Ans: The servlet uses the getInitParameter() function to gain access to its init parameters:

public String ServletConfig.getInitParameter(String name)

The named init parameters value is returned by the above procedure, or null if the specified init parameter does not exist. A single string is always returned as the result. The value is subsequently interpreted by the servlet.

9. How does a servlet examine all its init parameters?

Ans: We can make use of getInitParameterNames() to review all of its initialization parameters

public Enumeration ServletConfig.getInitParameterNames()

If the servlet has no starting arguments, it produces an Enumeration of String objects with the servlet's initialisation parameters or an empty Enumeration. This is a common debugging technique.

10. What is Session Tracking?

Ans: The term "session" merely refers to a certain period.
Session tracking is a method of keeping track of a user's current status. The HTTP protocol is a stateless communication mechanism. Every time a user sends a request to the server, it treats it as a new request. As a result, we must keep track of a user's current state to identify that user.

Servlet Advanced Interview Questions

Now it's time to ramp up the difficulty, In the below questions, we've covered the Servlet interview questions for advanced candidates

11. What is the difference between a Generic Servlet and HTTP Servlet?

Ans: The fundamental distinction between GenericServlet and HttpServlet is that GenericServlet is protocol independent and may be used with any protocol, including HTTP, SMTP, FTP, and CGI, whereas HttpServlet is protocol dependent and can only be used with the HTTP protocol.

The below-given image provides the various difference between Generic Servlet and HTTP Servlet.

12. What is the workflow of a servlet?

Ans: A Servlet is a Java utility for developing Java Web Applications. It is a server-side component that aids in generating dynamic web pages by acting as a conduit between the incoming HTTP request from the browser and the database. Servlet is a server-side programming language that is resilient.

The workflow of a Servlet is depicted in the diagram below.

The servlet receives a request from a webpage. The servlet forwards the request to the relevant JSP page, which then provides the response as a client-visible result page.

13. What is the difference between ServletConfig and ServletContext?

Ans: In ServletAPI, the import interfaces ServletConfig and ServletContext are both used. The main difference between ServletConfig and ServletContext is that ServletConfig has been used by just one servlet to retrieve info, whereas ServletContext is utilised by numerous objects.
ServletConfig vs ServletContext Comparison Chart

ServletConfig ServletContext
Each servlet class has its own ServletConfig object. The ServletContext object is used throughout the web application.
The ServletConfig object will be created during the servlet's initialization phase. To build the ServletConfig object for the first time, we must explicitly supply the request. Servlet's Object Context will be built during the deployment of the web application. Even before making the initial request, the ServletContext object may be available.
The ServletConfig object will be available as long as a servlet is running, but it will be removed once the servlet is finished. The ServletContext object will be available as long as a web application is running on the server, and it will be deleted whenever the application is withdrawn.
When only one servlet requires information shared by it, the ServletConfig object is utilised. When an application requires information to be exchanged, the ServletContext object is used.
To obtain a Servletconfig object, use the getServletConfig() function. To retrieve a ServletContext object, use the getServletContext() function.
The init-param> tag will appear under the servlet-class> tag in web.xml. The context-param> tag will appear under the web-app> tag in web.xml.

14. How is application exception handling is done using a Servlet?

Ans: The ServletException and IOException are thrown by the doGet() and doPost() methods, respectively. Only HTML is understood by the browser. As a result, when an application throws an exception, the servlet container processes it and generates an HTML response. Other errors, such as 404, are the same way.

Servlet API provides customizable Exception and Error Handler servlets that can be set in the deployment descriptor. These servlets' function is to handle Exceptions thrown by applications and send HTML responses that are beneficial to the user. We can provide a link to the application's main page or information about what went wrong.

The following is the Web.XML configuration:

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

15. How do you create a cookie using servlet?

Ans: The steps for creating and setting cookies with a servlet are as follows:

Step 1: Creating a Cookie object
Call the Cookie function Object() { [native code] } with a String Datatype cookie name and a String Datatype cookie value. When declaring names and values, it's important to make sure that certain symbols ([] () =, " /? @: ;) aren't used.

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

Step 2: Setting the maximum age
To specify how long the cookie should be valid, we'll use setMaxAge. A cookie would be set for 24 hours if the code-segment was followed.

-> cookie.setMaxAge(60*60*24);

Step 3: Sending the Cookie into the HTTP response headers
We can make use of reaction. To add cookies to the HTTP response header, use add Cookie as follows:

-> response.addCookie(cookie);

16. Explain the Servlet API.

Ans: Unlike a typical Java application, a servlet, like an applet, does not contain a main() function. It has some servlet methods that are used by the server to handle requests. Every time the server makes a request to a servlet, it calls the servlet's service() method.

To handle requests that are acceptable for the servlet, the service() method of a common servlet must be altered. The service() function accepts two parameters: the request object and the response object. The request object notifies the servlet of the request, and the response object responds to the request.

The service() method is rarely overridden by an HTTP servlet. For GET requests, it overrides doGet(), while for POST requests, it overrides doPost(). Depending on the type of requests an HTTP servlet needs to handle, it can override any or both of these methods.

17. What do you mean by server-side include (SSI) functionality in Servlets?

Ans: The server-side inclusion (SSI) functionality allows you to embed servlets in HTML pages. In servers that support servlets, a page can be preprocessed by the server to include servlet output at various points on the page.

<SERVLET CODE=ServletName CODEBASE=http://server:port/dir
           initParam1=initValue1 
           initParam2=initValue2>
<PARAM NAME=param1 VALUE=val1>
<PARAM NAME=param2 VALUE=val2>
   Text appearing here indicates that the web server which provides this page does not support the SERVLET tag.
</SERVLET>

18. How can a servlet get information about the client machine?

Ans: A servlet can use getRemoteAddr() and getRemoteHost() to get the client machine's IP address and hostname, respectively:

public String ServletRequest.getRemoteAddr()
public String ServletRequest.getRemoteHost()

Both values are returned as String objects.

19. Explain the server-side include expansion.

Ans: The functionality of a server that returns a placeholder SERVLET> tag is known as server-side inclusion (SSI). After that, the relevant servlet code replaces the SERVLET> tag.
The server only parses and analyses the pages that have been specially labelled. By default, the Java Web Server only parses.shtml files. Unlike the APPLET tag, the SERVLET tag shows nothing between SERVLET and /SERVLET unless the server does not accept SSI.

20. What do you mean by ‘filtering’ in servlets?

Ans: A series of servlets for an associated incoming request can normally be triggered in two ways. In the first case, the server bound to the URLs should be handled with the accompanying defined chain. The other method is to tell the server to route all specified content's output through a certain servlet before returning it to the client. On the fly, a series is effectively created. This process is called filtering when a servlet changes one type of content into another.

Servlet Interview Questions for Experienced

This section contains information to help experienced candidates demonstrate their breadth of expertise to the servlet interviewer.

21. Define ‘init’ and ‘destroy’ methods in servlets.

Ans: To initialise a Servlet, utilise the Servlets Init method.
The web container initialises the servlet after it loads and instantiates the servlet class, but before it sends client requests. Overriding the init method of the Servlet interface allows you to tailor this process so that the servlet can read permanent configuration data, initialise resources, and conduct any other one-time tasks.

Example:

public class CatalogServlet extends HttpServlet {
private ArticleDBAO articleDB;
public void init() throws ServletException {
articleDB = (ArticleDBAO)getServletContext().
getAttribute("articleDB");
if (articleDB == null) throw new
UnavailableException("Database not loaded");
}
}

When a servlet container deems that a servlet should be withdrawn from service (for example, when reclaiming memory resources or shutting down), it invokes the destruct method of the Servlet interface.

The database object created in the init method is released in the destruct method.

public void destroy() {
bookDB = null;
}

22. How is retrieving information different in Servlets as compared to CGI?

Ans: Servlets can provide access to information in a variety of ways. Every method, for the most part, returns a defined result. When compared to CGI scripts, the servlet technique has a number of advantages, including the use of provided environment variables.

  • Stronger type checking:
    Stronger type checking means the compiler has better support for detecting syntax and type errors. A CGI programme uses one function to get its environment variables, and some problems are not caught at compile-time and are only discovered at runtime, therefore they cannot be caught until a runtime problem occurs.
  • Delayed calculation:
    When a server begins a CGI programme, the value for each environment variable must be precalculated and given, whether or not the programme utilises it. Server-launched servlets, on the other hand, can improve speed on the fly by deferring calculations until the code is actually utilised.
  • Interactives with the server:
    Once the execution of a CGI programme begins, it is no longer bound to the server. The program's standard output is then the program's only communication avenue. A servlet, on the other hand, can interact with the server. A servlet can be used in the server or as a connected sidecar process running outside of the server.

23. Compare CGI Environment Variables and the HTTP Servlet Methods.

CGI Environment Variable HTTP Servlet Method
SERVER_NAME req.getServerName()
SERVER_SOFTWARE getServletContext().getServerInfo()
SERVER_PROTOCOL req.getProtocol()
SERVER_PORT req.getServerPort()
REQUEST_METHOD req.getMethod()
PATH_INFO req.getPathInfo()
PATH_TRANSLATED req.getPathTranslated()
SCRIPT_NAME req.getServletPath()
DOCUMENT_ROOT req.getRealPath("/")
QUERY_STRING req.getQueryString()
REMOTE_HOST req.getRemoteHost()
REMOTE_ADDR req.getRemoteAddr()
AUTH_TYPE req.getAuthType()
REMOTE_USER req.getRemoteUser()
CONTENT_TYPE req.getContentType()
CONTENT_LENGTH req.getContentLength()
HTTP_ACCEPT req.getHeader("Accept")
HTTP_USER_AGENT req.getHeader("User-Agent")
HTTP_REFERER req.getHeader("Referer")

24. What do you mean by Servlet chaining?

Ans: Servlet chaining is when one servlet's output is fed into the input of another servlet, and that servlet's output is piped into the input of yet another servlet, and so on. Each servlet in the pipeline can change or extend the incoming request. The last servlet in the servlet chain returns the response to the browser. The output of each servlet is sent as the input to the next servlet in the middle, allowing each servlet in the chain to update or extend the content. This is depicted in the diagram below. Servlets can assist in creating content through the use of servlet chaining.

25. What are the uses of Servlet chaining?

Ans: Some of the applications of Servlet chaining are listed below:

  • Change how a group of pages, a single page, or a type of content appears quickly.
    By dynamically translating the website text into a language that the client can read, one can communicate with folks who do not speak a specific language. You don't want people to read certain words that can be kept hidden.
  • Display in special formats a kernel of content.
    For example, custom tags can be added to a page and subsequently replaced with HTML content by a servlet.
  • Support for the esoteric data types.
    For example, one may create a filter that converts nonstandard picture types to GIF or JPEG.

26. What are the advantages of Servlet chains?

Ans: The following are some of the benefits of servlet chains:

  • Servlet chains can be readily undone. This aids in the rapid reversal of the transformation.
  • Servlet chains dynamically handle newly produced material. As a result, you can be confident that all of our limitations are respected, unique tags are substituted, and all dynamically converted PostScript pictures are correctly displayed even in servlet output.
  • Servlet chains save the material for later, so the script isn't executed every time it's added.

27. Explain the Servlet Life Cycle.

Ans: The Servlet container employs the javax.servlet package manages the entire life cycle of a Servlet. Servlet interface for managing and understanding Servlet objects. So, when you create a Servlet object, you should first learn about the Servlet object's life cycle or how the Servlet container controls the Servlet object.

Servlet Life Cycle Stages: The servlet life cycle is divided into four stages.

Let's take a closer look at each of these stages:

  • Loading a Servlet: The Servlet container loads and initialises the Servlet at the first stage of the Servlet lifecycle. The Servlet can be loaded in one of two steps by the Web container or Servlet Container: 
    • On configuring the Servlet with a positive or zero integer value, the context is initialised.
    • If the Servlet isn't in the preceding stage, the loading process may be delayed until the Web container deems that this Servlet is required to handle a request.

During this stage, the Servlet container performs two tasks:

Loading: The Servlet class is loaded during loading.

Instantiation: This method creates a Servlet instance. The container utilises the no-argument function Object() { [native code] } to build a new Servlet instance.

  • Initializing a Servlet: The Servlet container initialises the instantiated Servlet object after it is successfully instantiated. The container invokes the Servlet.init(ServletConfig) function, receiving a ServletConfig object reference as an argument. The Servlet container only calls the Servlet.init(ServletConfig) method once, after the Servlet.init(ServletConfig) object has been successfully instant resources, such as the JDBC datasource, are initialised using this method.
    If the Servlet fails to initialise, it now throws the ServletException or UnavailableException to notify the Servlet container.
  • Handling request: The Servlet instance is now ready to serve client requests after initialisation. When a Servlet instance is located to service a request, the Servlet container executes the following operations:
    • The ServletRequest and ServletResponse objects are created. If the request is HTTP, the Web container will produce HttpServletRequest and HttpServletResponse objects, subtypes of the ServletRequest and ServletResponse objects.
    • After constructing the request and response objects, the request and response objects are passed to the Servlet.service(ServletRequest, ServletResponse) function.

ServletException, UnavailableException, or IOException may be thrown by the service() method during processing the request.

  • Destroying a Servlet: If a Servlet container wants to kill a Servlet, it conducts the following actions: 
    • It allows all threads currently operating in the Servlet instance's service function to finish their tasks and be freed.
    • The Servlet container invokes the destruct() method on the Servlet instance after all presently active threads have completed their tasks.
    • The Servlet container drops all references to this Servlet instance after the destruct() method is called, allowing it to be garbage collected.

28. What do you mean by Servlet Reloading?

Ans: Although servlet reloading appears to be a simple function, it is actually quite a trick—and it necessitates quite a hack. ClassLoader objects were designed to only load a class once. Servers utilise custom class loaders to get around this limitation and load servlets numerous times. The default servlets directory is used by these custom class loaders to load servlets.
When a server sends a request to a servlet, it first checks to see if the class file for the servlet has changed on disc. If a change occurs, the server discards the class that the loader was used to load the previous version and makes a new instance of the customized class loaders to download the new edition. Older servlet editions can remain in storage indefinitely, but they are no longer used to handle requests.

29. What are the different methods involved in the process of session management in servlets?

Ans: The following are the many approaches used in servlet session management:

User Authentication
A customer wants to access a service that is password-protected, such as a JSP page. If the customer is able, the servlet container makes the service available; or else, the customer is required for a username and password.

HTML Hidden Field
A hidden input field is specified using the input type="hidden"> tag. When a form is submitted, a hidden field allows site developers to enter information that users cannot see or change. When a form is submitted, a hidden field is frequently used to keep track of which database record has to be updated.
Cookies
A small text file is saved on the user's computer by a website, either temporarily for that session or permanently on the hard drive. Cookies allow a website to remember your preferences and recognise you.
URL Rewriting
URL rewriting is the process of changing a programme that manipulates the parameters in a URL automatically (Uniform Resource Locator). A Web server administrator uses URL modification for convenience, whereas a hacker uses it for malevolent objectives.
Session Management API
For session tracking, the Session Management API is constructed on top of the Request-Response methods. Session tracking is a method of keeping track of a user's current status and data. It's also known as servlet session management.

30. How can a servlet get the server's name and the port number for a particular request?

Ans: The name of the server and the port number for a certain request can be obtained by a servlet with getServerName()and getServerPort()  respectively:

public String ServletRequest.getServerName()
public int ServletRequest.getServerPort()

Those functions are characteristics of ServletRequest because the value can vary for different requirements if the server has several names (a technique called virtual hosting).

The getServerInfo() and getAttribute()methods of ServletContext supply information about the server software and its attributes:

public String ServletContext.getServerInfo()
public Object ServletContext.getAttribute(String name)


Conclusion

We are at the end of this “Servlet Interview Questions” blog. We hope that the above-given questions will help you to crack your interview successfully. 

Do you have any questions for us? Or Do you like to add some more questions to this blog? Please mention it in the comment section, We will get back to you with the answer as soon as possible. Good Luck with your Interview!

 

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Java Spring TrainingAug 05 to Aug 20
Java Spring TrainingAug 08 to Aug 23
Java Spring TrainingAug 12 to Aug 27
Java Spring TrainingAug 15 to Aug 30
Last updated: 04 August 2023
About Author
Remy Sharp
Soujanya

Soujanya is a Senior Writer at Mindmajix with tons of content creation experience in the areas of cloud computing, BI, Perl Scripting. She also creates content on Salesforce, Microstrategy, and Cobit. Connect with her via LinkedIn and Twitter.

Recommended Courses

1 /15