Google News
logo
Java Servlets Interview Questions
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. Servlets can also access a library of HTTP-specific calls and receive all the benefits of the mature Java language, including portability, performance, reusability, and crash protection. Servlets are often used to provide rich interaction functionality within the browser for users (clicking link, form submission, etc.)
To write a servlet that is part of a web application :
Create a Java class that extends javax.servlet.http.HttpServlet
Import the classes from servlet.jar (or servlet-api.jar). 
These will be needed to compile the servlet.
A web server responsibility is to handler HTTP requests from client browsers and respond with HTML response. A web server understands HTTP language and runs on HTTP protocol.

Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as the servlet container, for example, Tomcat.

Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management, etc. So we can say that the Application server is a web server with additional functionalities to help developers with enterprise applications.
* GET is a safe method (idempotent) where POST is non-idempotent method.

* We can send limited data with GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.

* GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can’t bookmark it.

* GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.

* Hyperlinks in a page uses GET method.
Servlet technology was introduced to overcome the shortcomings of CGI technology.
 
* Servlets provide better performance than CGI in terms of processing time, memory utilization because servlets use benefits of multithreading and for each request, a new thread is created, that is faster than loading creating new Object for each request with CGI.

* Servlets and platform and system independent, the web application developed with Servlet can be run on any standard web container such as Tomcat, JBoss, Glassfish servers and on operating systems such as Windows, Linux, Unix, Solaris, Mac, etc.

* Servlets are robust because container takes care of the life cycle of servlet and we don’t need to worry about memory leaks, security, garbage collection, etc.

* Servlets are maintainable and the learning curve is small because all we need to take care is business logic for our application.
Servlets are mostly used because they are platform-independent Java classes and are compiled to platform-neutral byte code. Java byte code can be loaded dynamically into and run by java enabled web server.
CGI stands for Common Gateway Interface which is a set of codes written on the server-side that is used to interact through the Web Server with a client running on a web server.
 
It takes the incoming request and for every new request, it starts a new process.
 
Drawbacks of Common Gateway Interface :
 
* As it creates a new process for every incoming request, if the number of incoming requests are more then the response generated will be very slow, which in turn reduces the efficiency.

* CGI is platform dependent.
Generic Servlet can handle all types of requests. As it has a service () method, it is independent, whereas Http Servlet extends the generic servlet and supports the HTTP methods such as doGet (), doPost (), doHead (), doTrace (), etc.
The life cycle of a servlet is explained with reference to the below diagram.
 
* At first, the Servlet class is loaded as per the request received from the Client.
* Then the new instance or object of a servlet is created. Only one object is created, for every life cycle.
* Then the Init () method, used to initialize the servlet is invoked.

Syntax : public void Init ()
 
* The Service () method is invoked every time when a new request is received to perform any operations.
Syntax : public void service ()
 
* Then the destroy method is invoked to perform the clean-up operation.
Syntax : destroy ()
Servlet containers are also called web containers and are used to store other servlet components such as multiple threads.

Servlet containers :
 
* Eases communication between browsers and servlets.
* Manage servlet life cycles.
* Create new threads for every servlet request, providing them with the response and request objects.
* Provide support for JavaServer Pages (JSP).
* Handle numerous miscellaneous tasks such as garbage collection, providing security configurations, and memory optimization.
PrintWriter is a character-stream class where as ServletOutputStream is a byte-stream class.

The PrintWriter class can be used to write only character-based information whereas ServletOutputStream class can be used to write primitive values as well as character-based information.
The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interceptor can also be used to include the content of antoher resource.
Yes, one of the way is RequestDispatcher interface for example:
RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");  
rd.forward(request,response);

 

Session simply means a particular interval of time.
 
Session Tracking is a way to maintain state of an user.Http protocol is a stateless protocol.Each time user requests to the server, server treats the request as the new request.So we need to maintain the state of an user to recognize to particular user.
A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
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.
The important 3 annotations used in the servlets are.
 
@WebServlet : for servlet class.
@WebListener : for listener class.
@WebFilter : for filter class.
The RequestDispatcher interface defines the object that receives the request from the client and dispatches it to the resources such as a servlet, JSP, HTML file. The RequestDispatcher interface has the following two methods:
 
* public void forward(ServletRequest request, ServletResponse response)

Forwards request from one servlet to another resource like servlet, JSP, HTML etc.
 
* public void include(ServletRequest request, ServletResponse response)

Includes the content of the resource such as a servlet, JSP, and HTML in the response.
We need Servlet Filters for the following reasons :
 
* Logging the request parameters to log files.
* Authentication and Authorization of the request for the needed resources.
* Formatting of the request body/header before sending it to the servlet.
* Compressing response data sent to the client.
* Change the response by adding some cookies and header information.
A servlet does not have a main() method, unlike a regular Java program, and just like an applet. It has some methods of a servlet that are called upon by the server for the purpose of handling requests. It invokes the servlet’s service() method, every time the server sends a request to a servlet.
 
To handle requests that are appropriate for the servlet, a typical servlet must override its service() method. The service() method allows 2 parameters : these are the request object and the response object.

The request object is used to inform the servlet about the request, whereas the response object is used to then give a response.
 
As opposed to this, an HTTP servlet typically does not override the service() method. However, it actually overrides the doGet() to handle the GET requests and the doPost() to handle POST requests. Depending on the type of requests it needs to handle, an HTTP servlet can override either or both of these methods.
Server-side inclusion (SSI) is a feature of a server in which a placeholder <SERVLET> tag is also returned. The <SERVLET> tag is then substituted by the corresponding servlet code.

The server just parses the pages that are specially tagged, and it doesn’t parse and analyses each page it returns. The Java Web Server parses solely pages with a .shtml extension by default. With the SERVLET tag, in contrast to the APPLET tag, the client web browser doesn’t see anything between SERVLET and /SERVLET unless SSI is not supported by the server.
Servlets ​​Init Method is used to initialise a Servlet.
 
After the web container loads and instantiates the servlet class and before it delivers requests from clients, the web container initializes the servlet. To customize this process to allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities, you override the init method of the Servlet interface.
 
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 determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources or when it is being shut down), the container calls the destroy method of the Servlet interface.
 
The following destroy method releases the database object created in the init method.
public void destroy() {
bookDB = null;
}

 

Servlet containers are also known as web container, for example, Tomcat. Some of the important tasks of servlet container are :
 
Communication Support : Servlet Container provides easy way of communication between web client (Browsers) and the servlets and JSPs. Because of the container, we don’t need to build a server socket to listen for any request from the web client, parse the request and generate a response. All these important and complex tasks are done by container and all we need to focus is on business logic for the applications.

Lifecycle and Resource Management : Servlet Container takes care of managing the life cycle of servlet. From the loading of servlets into memory, initializing servlets, invoking servlet methods and to destroy them. The container also provides utility like JNDI for resource pooling and management.

Multithreading Support : Container creates a new thread for every request to the servlet and provides them request and response objects to the processing. So servlets are not initialized for each request and save time and memory.

JSP Support : JSPs doesn’t look like normal java classes but every JSP in the application is compiled by container and converted to Servlet and then container manages them like other servlets.

Miscellaneous Task : Servlet container manages the resource pool, perform memory optimizations, execute garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.
javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation. We can use getServletConfig() method to get the ServletConfig object of the servlet.
javax.servlet.ServletContext interface provides access to web application parameters to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml using <context-param> element. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.
 
ServletContext is enhanced in Servlet Specs 3 to introduce methods through which we can programmatically add Listeners and Filters and Servlet to the application. It also provides some utility methods such as getMimeType(), getResourceAsStream() etc.
Some of the differences between ServletConfig and ServletContext are :
 
ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.

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

We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.
Following are the important functions of Filters :
 
* Security check
* Modifying the request or response
* Data compression
* Logging and auditing
* Response compression
Following are the modes that servlets can be used :
 
* Filter chains can be used to collect servlets together
* Support HTTP protocol
* Used for CGI based applications
* Dynamic generation of servlets
The reasons why the Get () method is preferred over the Post() method are given below.
 
Get () method :
* Here, a specific amount of data or information can be sent as the data is sent through the header.
* In the Get() method, data is not secured as it is exposed in the URL bar to the user.
* Get () method can be bookmarked.
* Generally, the get () method is more effective and used over the post () method.

Post () method :
* Here a huge amount of data or information can be transferred as the data is sent through the body.
* As the data in the Post () method is sent through the body, it is secured.
* Post () method cannot be bookmarked.
* Generally, the Post () method is less effective and is not often used.
Send Redirect () method which works at the client side is used to redirect the response to another resource like Servlet, JSP, HTML.
 
Syntax : void send Redirect(URL);
 
Example : response.sendredirect(“http://www.google.com”);
Forward () method :
* It is used to send the exact same request to another resource.
* It works on the server-side within the server.

Send Redirect () method :
* It always sends a new request to the resources as it uses URL.
* It works at the client-side both outside and within the server.
The four servlet authentication methods are :
 
* HTTP basic authentication
* HTTP digest authentication
* HTTPS client authentication
* Form-based authentication
HttpServlet overrides the service() method to handle HTTP requests and dispatch them to one of the doXXX() handler methods depending on the Http request type (GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE).
 
Following are the seven doXXX() methods that the request is dispatched to from the service() method.
 
doGet() : Handles Http GET requests
doPost() : Handles Http POST requests
doPut() : Handles Http PUT requests
doDelete() : Handles Http DELETE requests
doHead() : Handles Http HEAD requests
doOptions() : Handles Http OPTIONS requests
doTrace() : Handles Http TRACE requests
By default, the servlet container instantiates only one instance of a servlet per JVM. The servlet container sends multiple concurrent requests to the service() method of the servlet to process, via a separate thread for each request. Hence the service() method and the servlet has to be designed to be thread safe for concurrent processing with multiple threads.
Files can be send to the servlet container for processing by requests that are of type Multipart/form-data.
 
HttpServletRequest defines following methods for handling Multipart data.
 
getParts() : Gets all the Part components of this request, provided that it is of type multipart/form-data. If this request is of type multipart/form-data, but does not contain any Part components, the returned collection will be empty.
 
getPart(String name) : Gets the Part with the given name. The Part with the given name, or null if this request is of type multipart/form-data, but does not contain the requested Part.
The ServletRequest interface defines the following methods to get more information about the client or the last proxy that send the request.
 
getRemoteAddr() : Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.
 
getRemoteHost() : Returns the fully qualified name of the client or the last proxy that sent the request.
 
getRemotePort() : Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request.
 
HttpServletRequest interface that extends from ServletRequest interface inherits above methods.
The ServletRequest interface defined in Servlet API provides the following methods for authentication.
 
authenticate() : Uses the container's login mechanism configured for the ServletContext to authenticate the user making this request.
 
getAuthType() : Returns the name of the authentication scheme used to protect the servlet.
 
getUserPrincipal() : Returns a java.security.Principal object containing the name of the current authenticated user.
 
isUserInRole() : Returns a boolean indicating whether the authenticated user is included in the specified logical role.
 
login() : Validate the provided username and password in the password validation realm used by the web container login mechanism configured for the ServletContext.
 
logout() : Establish null as the value returned when getUserPrincipal(), getRemoteUser(), and getAuthType() is called on the request.
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.
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.
The WAR(Web Application Resource) file specifies the web elements. Either a Servlet or JSP project can be converted into a war file. Moving one Servlet project from one place to another will be fast as it is combined into a single file.
The war file can be created using jar tool found in jdk/bin directory. If you are using Eclipse or Netbeans IDE, you can export your project as a war file.
 
To create war file from console, you can write following code.

jar -cvf abc.war *  

Now all the files of current directory will be converted into abc.war file.
Yes, a Deadlock situation can be created on a servlet by calling doPost() method inside doGet() method, or by calling a doGet() method inside doPost() method will successfully create a deadlock situation for a servlet.
A web container or a Servlet container is used to interact with the Servlet and includes all the Servlet, JSP, XML files inside it. Web Container’s responsibility is to manage the life cycle of a servlet and to help to map the URL of a specific servlet. A web container is also used creates the object of a servlet.
Yes, There are a couple of primary ways in which a servlet can be automatically refreshed. One way is to add a “Refresh” response header containing the number of seconds after which a refresh should occur. The TestServlet class below shows an example of this.
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());
      }
}

 

In a servlet, the Java code is written in HTML but JSP(Java Server Page) allows us to write Java code in HTML. JSP allows easy development of web pages and allows web designer and web developer to work independently. All JSP pages are translated into servlet and web container is responsible for translating JSP into the servlet.
The service() method is actually the main method that is expected to perform the actual task. The servlet container calls the service() method to handle requests coming from the client/browsers and to provide the response back to the client.
 
Each time the server receives a request for a servlet, the server creates a new thread and calls for the service. The service() method checks the HTTP request type and calls the respective methods as required.
 
syntax :
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException{
}

The container calls the service() method and service method invokes doGet(), doPost(), doPut(), doDelete(), methods as needed. So you have nothing to do with service() method but you override either doGet() or doPost() depending on the request you receive from the client-end.

Servlet Chaining is a way where the output of one servlet is piped to the input of another servlet, and the output of that servlet can be piped to the input of yet another servlet and so on. Each servlet in the pipeline can either change or extend the incoming request. The response is returned to the browser from the last servlet within the servlet chain. In the middle, the output out of each servlet is passed as the input to the next servlet, so every servlet within the chain has an option to either change or extend the content.
Servlet chains have the following advantages :
 
* Servlet chains can be undone easily. This helps in quickly reversing the change.

* Servlet chains dynamically handle content that is created. Because of this, one can trust that all our restrictions are maintained, that the special tags are replaced, and even in the output of a servlet, all the dynamically converted PostScript images are properly displayed.

* Servlet chains cache the content for later, so it does not execute the script every time got added.
SingleThreadModel interface was provided for thread safety and it guarantees that no two threads will execute concurrently in the servlet’s service method. However, SingleThreadModel does not solve all thread-safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. Also, it takes out all the benefits of multithreading support of servlets, that’s why this interface is Deprecated in Servlet 2.4.
Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes in web application. There are three scopes for servlet attributes -  request scope, session scope and application scope.
 
ServletRequest, HttpSession, and ServletContext interfaces provide methods to get/set/remove attributes from request, session and application scope respectively.
 
Servlet attributes are different from init parameters defined in web.xml for ServletConfig or ServletContext.
If we have to initialize some resource before we want our servlet to process client requests, we should override the init() method. If we override init(ServletConfig config) method, then the first statement should be super(config) to make sure superclass init(ServletConfig config) method is invoked first. That’s why GenericServlet provides another helper init() method without argument that get’s called at the end of init(ServletConfig config) method. We should always utilize this method for overriding init() method to avoid any issues as we may forget to add super() call in overriding init method with ServletConfig argument.
WEB.XML is said to be the deployment descriptor in a servlet.
 
It is the entry point for any application and possesses the welcome file list. It defines resources, information about which servlet will be used and maps the servlet to URL.
There are basically four types of techniques which are given below :
 
* Cookies : Cookies are small information which is added to multiple client requests.
 
Example : One request comes to the server, the server adds some cookies with the response, now when again the same client sends the request to the server, the server recognizes the user.
 
* Hidden Form Field : Here we use a hidden text field for maintaining the state of the user.
 
* URL Rewriting : Here we give an extra link for the next servlet to be mapped.
 
* Http Session : Here a specific ID is generated for each user, so a server can recognize the user.
Servlets are Java based analog to CGI programs, implemented by means of a servlet container associated with an HTTP server. Servlets run on the server side. Beans are reusable code components written in Java that one can use in a variety of programming environments. JavaBeans are to Java what ActiveX controls are to Microsoft. Javabeans can run on server side, client side, within an applet etc.
If we have to make sure an object gets notified when session is destroyed, the object should implement javax.servlet.http.HttpSessionBindingListener interface. This interface defines two callback methods – valueBound() and valueUnbound() that we can define to implement processing logic when the object is added as attribute to the session and when session is destroyed.
We know that using ServletContext, we can create an attribute with application scope that all other servlets can access but we can initialize ServletContext init parameters as String only in the deployment descriptor (web.xml). What if our application is database-oriented and we want to set an attribute in ServletContext for Database Connection.
 
If your application has a single entry point (user login), then you can do it in the first servlet request but if we have multiple entry points then doing it everywhere will result in a lot of code redundancy. Also if the database is down or not configured properly, we won’t know until the first client request comes to the server. To handle these scenarios, servlet API provides Listener interfaces that we can implement and configure to listen to an event and do certain operations.
A servlet can use getRemoteAddr() and getRemoteHost() to retrieve the IP address and hostname of the client machine, respectively :
public String ServletRequest.getRemoteAddr()
public String ServletRequest.getRemoteHost()
Both values are returned as String objects. 
Servlets running together in the same server have many ways to communicate with one another. There are two main styles of servlet collaboration :
 
Sharing information : Sharing information involves two or more servlets sharing the state or even resources. A special case of sharing information is Session tracking.

Sharing control : Sharing control involves two or more servlets sharing control of the request. For example, one servlet could receive the request but let another servlet handle some or all of the request-handling responsibilities.
The core of the Servlet API is the javax.servlet package. It includes the basic Servlet interface, which all servlets must implement in one form or another, and an abstract GenericServlet class for developing basic servlets.
 
This package comprises of the following :
 
* Classes for communicating with the host server and client (ServletRequest and ServletResponse)
* Communicating with the client (ServletInputStream and ServletOutputStream).

In situations where the underlying protocol is unknown, servlets should confine themselves to the classes within this package.
A servlet basically generates HTML. We can set the content-type response header by any of the methods. The example for producing text message FTL using the HTML code inside the servlets.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FTL 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>FTL</TITLE></HEAD>n" + "<BODY>n" + " <H1>FREE TIME LEARNING</H1>  n" + "</BODY></HTML>");
       }
}