42 Servlets Interview Questions and Answers - Freshers, Experienced

Dear Readers, Welcome to Servlets Interview questions with answers and explanation. These 42 solved Servlets questions will help you prepare for technical interviews and online selection tests conducted during campus placement for freshers and job interviews for professionals.

After reading these tricky Servlets questions, you can easily attempt the objective type and multiple choice type questions on Servlets.

What is an Applet container?

- It is a container to manage the execution of applets.
- It consists of a web browser and a Java plug-in running together on the client.

What are the functions of Servlet container?

The main functions of Servlet container are:
1. Lifecycle management : Managing the lifecycle events of a servlet lik class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.

2. Communication support : Handling the communication between servlet and Web server.

3. Multithreading support : Automatically creating a new thread for every servlet request and finishing it when the Servlet service() method is over.

4. Declarative security : Managing the security inside the XML deployment descriptor file.

5. JSP support : Converting JSPs to servlets and maintaining them.

What is Servlet Chaining?

- It is a method in which the output of one servlet is piped into the next servlet.
- It is the last servlet in the chain that provides the output to the Web browser.

What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext?

- While using a ServletRequest a relative URL can be provided, which can not be done while using ServletContext.

How would you create deadlock on your servlet?

- Calling a doPost() method inside doGet() and doGet()method inside doPost() wouleate a deadlock for a servlet.

What are the uses of Servlet?

The important used of HTTP Servlets are:

- Storage and processing of data submitted by an HTML form.
- Providing dynamic content to the client for example outputting the result of a query.
- Improving the system performance by handling multiple requests at a time.
- Managing state information on top of the stateless HTTP.

Why is HttpServlet declared abstract?

- The default implementations of the main service methods can not do anything and need to be overridden. This calls of the HttpServlet class to be declared as abstract.

- With its use the developers do not need to implement all the service methods.

Differentiate between GET and POST.

- When you use GET, the entire form submission gets encapsulated in one URL. The query length is limited to 260 characters, not secure, faster, quick and easy.

- When you use POST your name/value pairs inside the body of the HTTP request, which makes a cleaner URL. It imposes no size limitations on the form's output. It is used to send a large amount of data to the server to be processed. It is comparatively more versatile and secure.

When should you prefer to use doGet() over doPost()?

GET is preferred over POST in most of the situations except for the following:

- When the data is sensitive.
- When the data is greater than 1024 characters.

When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?

- Building a DOCTYPE line informs the HTML validators about the version of HTML you are using. This tells them the specification against which your document should be checked.

- These validators work as valuable debuggers which help you catch the HTML syntax errors.

Why is a constructor needed in a servlet even if we use the init method?

- Although the init method of the servlet initializes it, a constructor instantiates it.
- A developer might never explicitly call the servlet's constructor but a container uses it to create an instance of the servlet.

What is lazy loading?

The servlets are not initialized by the container from the start. It happens when the servlet is requested for the first time. This is called lazy loading.

What is GenericServlet class?

- GenericServlet is an abstract class which implements the Servlet interface and the ServletConfig interface.

- Other than the methods included in above two interfaces, it also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.

- Since this class is not specific to any protocol, it is known as generic servlet.

How can the session in Servlet be destroyed?

There are two ways to destroy a session:

1. Programatically : By using session.invalidate() method. It makes the container abandon the session on which the method is called.
2. When the server shuts down.

What are the types of Session Tracking ?

Following are the popular ways of session tracking:

1. URL rewriting: In this method of session tracking, some extra data is appended at the end of the URL, which identifies the session. This method is used for those browsers which do not support cookies or when the cookies are disabled by the user.

2. Hidden Form Fields: This method is similar to URL rewriting. New hidden fields are embedded by the server in every dynamically generated form page for the client. When the form is submitted to the server the hidden fields identify the client.

3. Cookies: Cookie refers to the small amount of information sent by a servlet to a Web browser. Browser saves this information and sends it back to the server when requested next. Its value helps in uniquely identifying a client.

4. Secure Socket Layer (SSL) Sessions

What are the disadvantages of storing session state in cookies?

Disadvantages of storing session state:

- Using a cookie, all the session data is stored with the client. If the cookies at client side get corrupt, purged or expired, the information received won't be complete.

- Some user may disable the cookies or their browser might not support them. Some users might have a firewall filtering out the cookies. So, you may either not receive the information or trying to switch to an alternate means may cause complexity.

- Cookie based solutions work only for HTTP clients.

- A low-level API controls the cookies. It is quite difficult to implement them.

Tell us something about ServletConfig interface.

- This interface is implemented by the servlet container to pass configuration information to a servlet.
- The server passes an object that implements the ServletConfig interface to the servlet's init() method.
- There exists one ServletConfig parameter per servlet.
- The param-value pairs for ServletConfig object are specified in <init-param> in the <servlet> tags in the web.xml file.

Tell us something about ServletContext interface.

- This interface defines a set of methods a servlet uses to communicate with its servlet container.
- There is one ServletContext for the entire webapp. All the servlets in a webapp share it.
- The param-value pairs for ServletContext object are specified in the <context-param> tags in the web.xml file.

Explain the differences between Jsp and Servlet.

- The JSP is used mainly for presentation purpose.
- The Servlets are not used for presentation purpose only.
- JSP can be only HttpServlet.
- HTTP is the only supported protocol in JSP.
- A servlet is supported by any protocol . e.g HTTP, FTP, SMTP etc.

Explain the custom JSP tags and the beans.

Custom JSP tag:

- In Tag libraries we define a custom tag along with its attributes , how its body is interpreted and grouped the tags into collections .

- We can use the custom JSP tag in any number of JSP files.

- For custom JSP tags, we define three different components:

1. The tag handler class which defines the tag’s behaviour.

2. The tag library descriptor file which maps the XML element names in the tag implementations.

3. The JSP file which uses the tag library.

Beans:

- JavaBeans & Java utility classes are defined simultaneously.

- For Java classes, Beans have a standard format.

- We use tag Custom tags and beans for accomplishing the same objectives - encapsulating complex behaviours in simple and accessible forms.

Name the different ways of session tracking.

These ways are given below:

- Cookies

- URL rewriting

- HttpSession,

- Hidden form fields

What are the mechanisms used by a Servlet Container for maintaining session information?

For maintaining session information Servlet Container uses:

- Cookies

- URL rewriting

- HTTPS protocol information

Explain GET and POST.

GET:

- In GET the entire form submission is encapsulated in one URL.
- The data gets submitted as a part of URL.

POST:

- In POST the data is submitted in the body of HTTP request.
- The data is not visible on the URL and it is more secure.

What is session?

- The session may be said as an object.
- It is used by a servlet to track a user’s interaction.
- It interacts with the Web application.
- It works across multiple HTTP requests.
- The sessions are mainly stored in the server.

Define the servlet mapping.

- The servlet mapping is defined as an association between the URL pattern and a servlet.
- The mapping is used in mapping requests.
- It maps in the Servlets only.

Explain the servlet context.

- The servlet context is coined as an object.
- It is contained information about the Web application and the container.
- With a context, a servlet can be used for logging events, to obtain URL references to resources, and for setting and storing attributes for the other servlets within the context.

Explain servlet.

- A servlet is simply a java program .
- It runs for an action.
- It runs inside a web container.
- The servlet is used in various implementation project.

what is the procedure for initializing a servlet?

- To initialize a servlet init() is used.
- init() initializes a java program.
- A constructor can also be used to initialize a servlet.

Tell the new features added in ServletRequest interface i.e. Servlet 2.4

Following methods had been added to the ServletRequest 2.4 version:

- public int getRemotePort()
- public java.lang.String getLocalName()
- public java.lang.String getLocalAddr()
- public int getLocalPort()

How many JSP scripting elements are there and what are those?

We can name three scripting language elements:

scriptlets
- JSP Scriplet is a jsp tag which is used for enclosing a java code in the JSP pages.
- Scriplet begins with <% tag and ends with %> tag.

Declarations
- Declarations are also a kind of tag.
- It is used mainly for allocating variables.

expressions
- The Expression is a tag used for inserting Java values directly into the output.
- The Syntax is given as: <%= expression %>

How can we include static files in the JSP page?

- Static resources can be included in the JSP.
- It can be included with an include directive.
- By this way, the inclusion is being performed for once.
- The inclusion performs during the translation phase.

How can we implement a JSP page?

- It's possible to make our JSPs thread-safe.
- So we can do it by adding the directives.
- The directive we have to add is :
<%@ page isThreadSafe="false" %>

Explains the differences between context.getRequestDispatcher() and request.getRequestDispatcher()?

- To create the relative path for the resource we use request.getRequestDispatcher(path) .
- To create the absolute path of the resource we use resourcecontext.getRequestDispatcher(path).

Define the lifecycle for executing a JSP page.

While executing the JSP page the JSP engine works in the following 7 phases :

1. Page translation: - page parsing.
2. Page compilation into a class file.
3. Page loading by the class file loading.
4. Creating an instance of servlet.
5. jspInit() method is being called.
6. _jspService is being called for handling the service calls.
7. _jspDestroy is being called for destroying it when the servlet not required.

Define context initialization parameters.

- Context initialization parameters are specified in the web.xml files,
- These are basically initialization parameters.
- This happens for the whole application.

What is an Expression?

- Expressions are used as place holders for the language expressions.
- These are evaluated each time, the page is being accessed.
- This includes in the service method of the newly generated servlet.

Define Declaration.

- Declaration is used to declare one or more variables or methods.
- It is used in the JSP source file later on.
- The declaration must be contained minimum one full declarative statement.
- You can declare any number of variables or methods in one declaration, whereas semicolons separate them.
- In the JSP file the declaration can be done in the scripting language .
- This is included in the declaration section of the newly generated servlet.

What is a Scriptlet?

- Scriptlet contains language statements, variable & expressions.
- These are valid in the page scripting language.
- By using scriptlet tags we can declare variables for using later in the file.
- By using scriptlet we can write expressions valid in the page scripting language .
- In General a scriptlet may contain a java code which is valid inside a java method.

What are the different methods involved in generic servlet?

Generic servlet is a base class of servlet. It involves the following methods:

init() method: This method is called once by the servlet container in its lifecycle . It takes a ServletConfig object that contains the initialization parameters and configuration of the servlet.

Service() method : This method is defined as a public void service as ServletRequest “req” OR ServletResponse “res” which gives Servlet Exception, as IOException .If once the servlet starts getting requests, the service() method is called by the servlet container to respond to the requests.

Getservlet config(): The method comprises of the initialization and the startup of the servlet. It is also responsible for returning the Server Config object.

Getservlet info(): This method is defined as public String getServletInfo() .It is responsible for returning a string which is in the form of plain text and not any kind of markup.

destroy(): This method is defined as public destroy().this method is called when want to close the servlet.

Define the life cycle of a servlets.

Among various other roles of the web container, the most important is to manage the life cycle of a servlet. The functionality of a servlet is managed by a well defined life cycle that states how it is loaded, Instantiated, initialized, handles client request and taken out of service.

Servlet lifecycle can be divided into four parts:

1. Loading and instantiation:
In this the web container first loads the servlet class. The web container then creates an instance of this servlet. Loading of servlet is done during the startup when the first request is made, whereas the creation of instance can occur at startup or can be delayed till service to a request is required by the servlet.

2. Initialization:
After the creation of an instance the init() method is called by the servlet to initialise the servlet instance. The init() method must be called before any of the requests are serviced by the servlet. The parameters of initialization are passed to init() and persist till servlet is destroyed. If loaded successfully the servlet is available for service, if not then the servlet is unloaded by the servlet container.

3. Handling requests:
After initialization the servlet can be used to handle client requests. Requests are represented by request objects of type ServletRequest. A separate thread is created for each request.

4. Taking servlet out of service (Destroying servlet):
When a servlet is no longer required the destroy method() is called by servlet container. This method removes the servlet. Once removed there are no request sent to the servlet and all resources associated with it are released.

How to generate the server side programming and the advantages of it over the other languages?

The advantages are as follows:

1. Server side programming is one of the efficient and faster method to implement the server code on the remote machines.

2. The programs are centralized on a single server and any of the remote machines can access the server programs.

3. The clients can add new functionalities to the server side without making any change from there side.

4. Adding of patches, switching to new database and migrating to new version, architecture and design is not dependent on the software and hardware capabilities thus making it more independent.

5. Service side applications can be used to manage issues related to enterprise application.

6. Server side programming is capable of generating dynamic and user band content also it is very portable.

What is the requirement of servlet config and servlet context implemented and how are they implemented?

The servlet config is used for initialization of a servlet. Using servlet config initialization parameters can be passed for the srevlet by making use of web xml.
<servlet>
<servlet-name>ServletConfigABC</servlet-name>
<servlet-class>com.javapapers.ServletConfigABC</servlet-class>
<init-param>
<initparam-name>topic</initparam-name>
<initparam-value>Difference between ServletConfig and ServletContext</initparam-value>
</init-param>
</servlet>

What are the objects involved when a servlet receives a call from client?

Servlets are designed to receive request or calls from clients. When a servlet receives a call from a client there are two objects involved in the process. The objects involved the request received from the client and the response of servlet to the client.

The 2 objects involved when a servlet receives a call from a client are :

1. Servlet Request :
The servlet request represents the request made by the client. It encapsulates communication from client side to server side. The servlet request checks the request and finds out which servlet shall respond to the request made by client.

2. Servlet Response:
The servlet response represents the response made by the servlet to the client. It assists the servlet in sending a response to the client.

How can a servlet be used to generate plain text instead of html?

A servlet generally generates html. Set content type response header by any of the method. The example for producing text message ABCD using the HTML code inside the servlets.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ABCD extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
        "Transitional//EN\">\n" +
        "<HTML>\n" +
        "<HEAD><TITLE>ABCD</TITLE></HEAD>\n" +
        "<BODY>\n" +
        "<H1>ABCD</H1>\n" +
        "</BODY></HTML>");
    }
}

What is HTTP servlet? Explain with the help of an example.

HTTP servlet is an extension of the Generic servlets. It provides various methods such as doPut(), doGet() etc. Which are useful in determining the type of request being made and thus picking the right method.

Example:
HttpServlet:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ABCDServlet extends HttpServlet
{
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.println("<HTML>");
        out.println(
        "<HEAD><TITLE>Title</TITLE></HEAD>");
        out.println(
        "<BODY><H1>ABCD!</H1><H6>Again.</H6></BODY></HTML>");
    }
}

How to rectify errors in java servlet while compilation?

A java servlet is harder to compile then any other java programs. To remove errors while compiling java following method can be used:

1. Check and resolve the errors on top of the listing. These errors could be the reason for related errors and thus removing them will eradicate the related errors.

2. Check if the compiler is choking on packages not built into java as these packages cannot be found since these packages can’t be imported and the classes under these are not usable. If there is any tell the compiler where to find these classes. This will resolve the errors that occurred in compiling servlet.

What are the steps involved in placing a servlet within a package?

Packages are used to separate the servlets under a directory to eradicate confusion among programmers working simultaneously on creating servlets on the same server. This can be done by the following steps:

1. Sorting of files into different sub directories by matching the package name to the subdirectory name to organize the packages.
2. After sorting the packages into subdirectories insert the package statement in the class file.

Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class servlet1 extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String docType =
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
        "Transitional//EN\">\n";
        out.println(docType +
        "<HTML>\n" +
        "<HEAD><TITLE>Servlet test</TITLE></HEAD>\n" +
        "<BODY BGCOLOR=\"#FDF5E6\">\n" +
        "</BODY></HTML>");
    }
}

What is the difference between the servlets and CGI programs?

1. Servlets provide the component bases services that are platform independent, whereas Common gateway interface (CGI) programs are used for the dynamic web content creation and to take the request and send them to the user.

2. Servlets performs better than CGI programs as they use the inbuilt API and keep the program size under control, whereas CGI suffer from the performance that is very low and it takes more time for the request to be answered.

3. Servlets are portable across all the platform and various web servers, whereas CGI are not portable to all the places due to increase in the size of the overall program.

4. Servlets allow the server-side programming to be written without any platform specification and by the use of APIs, whereas CGI is used to send and receive the request from the user.

5. Servlets are more efficient due to its lightweight use of java thread that handles the servlet requests, whereas the CGI is heavier due to the operating system process.

What is the use of Java Servlet API?

The servlet APIs represent the classes that are used to define an interface in between the web client and servlet. API is used to request the server to pass the object to the server. This servlet consists of the objects that produce the response that is passed to the client side. The API consists of two packages that are used to support the generic protocol independent servlets like javax.servlet and javax.servlet.http this also include the specific support files to support the HTTP protocol and the properties are also provided in there. The Java Servlet API is used to make it easy for the programmer to write the codes in an easy way and it also increase the overall performance of the system.

Why are HTTP servlets used in programming?

HTTP servlets define the servlets for the web to access the services using the HTTP protocol. The servlet interface in this is having a class that consists of the centralized abstraction using the Java Servlet API. The servlet class defines the methods that can be used for the communication between the clients. HTTP is used as a simple and stateless protocol that allows the client to make the request and server responds to it when the transaction is done. when a request is received from the client possibly a web browser than using the HTTP command a method will be called that allow the servers to take certain types of action on the particular request. The URL of the document represents the version of the HTTP protocol that is being used in the program.

What are the steps that are involved in using the HttpServlet class?

The HttpServlet class is used to take the request and respond to it using the necessary services that exist. The client sends a request to the servlet that is represented using the HttpServletRequest object. This object allows the communication to be performed in between the client and the server. It consists of all the messages that has to be transmitted for the communication. The class consists of the information that is provided for the client environment and any data that is being sent from the client using the servlet. The server responds using the object of HttpServletResponse. This response can be dynamically generated and includes the HTML page with the data and its request that can be gathered from the other servlet.

What are the key methods that are involved in processing of HTTP servlets?

There are many methods that are involved and to successfully allow the client to get the response the subclass of HttpServlet should override at least one method out of doGet or doPost. The GET requests are the common requests that are made by the browser when it request for the web pages. The GET method gets activated when the user uses the URL and clicks on the link. POST requests are used on the submission of HTML form that specifies the particular post request to be generated and handled. This method allows the client to send the data that is of variable length to the Web server at one time. This allows the simple and easy posting of the confidential information like credit card password, etc.

What are the common methods that are included in the HTTP servlet class?

The common methods that are included in HTTP servlet class includes of doGet and doPost methods that are used mostly in all the code files. These are the services that are implemented by the servlet as it allows different types of data to be displayed. The other methods that are used in the HTTP servlet class are:

1. doPut() method is used to put the HTTP requests. It is called by the server to allow the servlet to handle the requests. This operation allows the client to upload a file on the server or handle the file sending request by using FTP. It is used as:
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException,java.io.IOException

2. doDelete() method allows the deletion of the HTTP requests by the server. It is called by the server to perform the delete operation using which the client is allowed to remove the document from the web page that will remove it from the server as well. It is given as:
protected void doDelete(HttpServletRequest req,HttpServletResponse resp) throws ServletException, java.io.IOException

What are the ways to handle multi-threading in Servlets?

Multi-threading is used with the processes to divide the tasks into multiple threads and share the resources between them. It increases the speed and the performance of the system and the program that is in execution. When there are requests coming at the same time to the servlet, then the server will handle the requests coming from each client by creating a new thread and inserting the request in it. The model that is used consists of single thread per client/server request. This allows the thread to be reused again in the case when the same client is trying to make again the request. This multi-threading environment decreases the time delay using the API and decreases the delay in between the communication of the server and the client used for the requests.

What are the steps that are required to handle the multi-threading?

To handle the multi-threading environment the steps are required to be followed like:
The servlet has to be loaded by the the web server. The web application server consists of one instance that allows the handling of the object of the servlet one at a time. This object remains persistent throughout the lifecycle of the servlet.
The web browser that acts as a client request the services to be produced by the server or using the servlets. The server at that time creates the thread that is used to handle each request, by ignoring the instance object. The individual thread is used to access the variables that are initialized when the servlet is loaded on the server to respond to the client’s request. Individual threads handle their own requests that are sent back to the client who has asked for the services and requested for it.

What is the process to implement doGet and doPost methods?

doGet():
doGet() methods are the service methods that is included in the servlets. This allow the servlet to handle the GET request that is being processed by the client. This overrides the method to support the GET request that automatically supports the HTTP head request that is given in the no body in the response and included in the header fields. It is being implemented as:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException

It is used to read the request data and provide the response of it by putting the solution in the header. It uses the response’s writer or the object stream object that provides the response to the client. This is safe to use and can be safely repeated in case of any other request. .

doPost():
doPost() is used to handle a POST request that is also given at the time of filling up the form or any other action that is related to the user submission. This method allows the client to send the data of any length to the web server and that is also at single time. To read the request data the response headers are included that takes the response writer class to write that uses the output stream object. It uses the function of PrintWriter object that returns the response to set the content type of accessing the object. It is given as:
doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException

Write a program to show the functionality of doGet and doPost method?

doGet method reads the request data that is submitted by the user and sends the reply back to the client whose request is to processed. The parameters that are used in this method consists of strings, integers and appropriate exception need to be catched when using the method. getWriter method is used to provide the response object that provide different parameters to be passed to the client. The program consists of the doPost calling the doGet method where the program can alter the data that is provided in response. The program is written as:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    PrintWriter out = response.getWriter();
    printHeader(out, response);
    for (int k = 0; k < answers.length; k++)
    {
        try
        {
            userAnswers[k] = (Integer.parseInt (request.getParameter("answer"+k)));
        }
        catch (NumberFormatException e)
        {
            userAnswers[k] = 0;
        }
    }
    submit = request.getParameter("submit");
    printQuiz(out);
    printClosing(out);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    this.doGet(request, response);
}

How can the referrer and the target URLs be used in servlet?

The servlet first look for the referrer is defined as the parameter. The servlet after checking set it as an empty string. Referrer is not used after this and it is logged to a file or the database after accumulating the session tracking information on the user. The servlet checks for the target that is specified and throws an exception called as IllegalArgumentException. The informaiton of the target can be checked to see the starting of the Http service that does not exist at the time of test. The code shows the referrer and the target URLs be used as as:
public void getURLs(HttpServletRequest request)
{
    referrer = request.getParameter("referrer");
    if (referrer == null || 0 == referrer.length())
    {
        referrer = new String("");
    }
    target = request.getParameter("target");

    // If no target specified, raise an error
    if (target == null || target.equals(""))
    {
        throw new IllegalArgumentException();
    }
}
Advantages and selling points of Servlets
Servlet Advantages - Servlets are used to extend the server side functionality of a website...
What is Servlets and explain the advantages of Servlet life cycle?
Servlet life cycle - Servlets are the programs that run under web server environment. A copy of Servlet class can handle numerous request threads..
Different Authentication options available in Servlets
Servlets Authentication options - There are four ways of Authentication options available in servlets...
Post your comment