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.
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,
If you're looking for a Fresher role, you'll need to know the answers to these servlet interview questions given below.
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.).
Ans: To create a servlet for a web application, follow these steps:
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:
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.
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.
Ans: The following are some of the new features in Servlet 2.5:
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.
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.
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.
Now it's time to ramp up the difficulty, In the below questions, we've covered the Servlet interview questions for advanced candidates
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.
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.
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. |
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>
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);
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.
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>
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.
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.
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.
This section contains information to help experienced candidates demonstrate their breadth of expertise to the servlet interviewer.
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;
}
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.
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") |
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.
Ans: Some of the applications of Servlet chaining are listed below:
Ans: The following are some of the benefits of servlet chains:
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:
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.
ServletException, UnavailableException, or IOException may be thrown by the service() method during processing the request.
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.
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.
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)
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!
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Java Spring Training | Nov 19 to Dec 04 | View Details |
Java Spring Training | Nov 23 to Dec 08 | View Details |
Java Spring Training | Nov 26 to Dec 11 | View Details |
Java Spring Training | Nov 30 to Dec 15 | View Details |
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.