Core Java

Important Interview Questions/Answers of Servlet

Java Interview

“These Servlet Interview Questions are most frequently asked and most important for advance java interview. In advance, java Servlet is most important part of the interview. The interviewer will ask 30% of questions from Servlet”


Q1. What is the lifecycle of a servlet?

A servlet life cycle can be defined as the entire process from its creation till the destruction.Web container invokes these methods. The following are the paths followed by a servlet.

  • The servlet is initialized by calling the init ()
  • The servlet calls service() method to process a client’s request.
  • The servlet is terminated by calling the destroy()
  • Finally, the servlet is garbage collected by the garbage collector of the JVM.

Q2. What is the difference between Get and Post method?

It can send a limited amount of data because data is sent in the header. The post can send a large amount of data because data is sent in the body.

The Get is not  Secured because data is exposed in the URL bar. The post is secured because data is not exposed in the URL bar.

It can be bookmarked. The post cannot be bookmarked.

Get is more efficient and used than Post.

Q3. What is the difference between PrintWriter and ServletOutputStream?

PrintWriter is a character-stream class whereas 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.

Q4. What is the difference between GenericServlet and HttpServlet?

The GenericServlet is protocol independent whereas HttpServlet is HTTP protocol specific. HttpServlet provides additional functionalities such as state management etc.

Q5. What is servlet collaboration?

When one servlet communicates to another servlet, it is known as servlet collaboration. There are many ways of servlet collaboration:

  • RequestDispacher interface
  • sendRedirect() method etc.

Q6. Can you call a jsp from the servlet?

Yes, one of the way is RequestDispatcher interface for example:

  1. RequestDispatcher rd=request.getRequestDispatcher(“/login.jsp”);
  2. forward(request,response);

Q7. Difference between forward() method and sendRedirect() method?

Forward() sends the same request to another resource. sendRedirect() method sends new request always because it uses the URL bar used URL bar of the browser.

This method(forward) w the rks at server side. sendRedirect() method works at client side.

forward() method works within the server only. sendRedirect() method works within and outside the server.

Q8. What is Session Tracking?

Session simply means a particular interval of time.

Session Tracking is a way to maintain a state of a user. Http protocol is a stateless protocol. Each time user requests to the server, the server treats the request as the new request. So we need to maintain the state of a user to recognize to a particular user.

Q9. What is the difference between Cookies and HttpSession?

 Cookie works at client side whereas HttpSession works at the server side.

Q10. What is the filter?

A filter is an object that is invoked either at the preprocessing or postprocessing of a request. It is pluggable.

Q11. What is the use of the attribute in servlets?

An attribute is a map object that can be used to set, get or remove in the request, session or application scope. It is mainly used to share information between one servlet to another.

Q12. What is different between the web server and application server?

The biggest difference is a Web Server handles HTTP requests, while an Application server will execute business logic on any number of protocols. The border between these two is getting ever so thinner. Application servers expose business logic to a client.

Q13. What is MIME Type?

MIME stands for “Multipurpose Internet Mail Extensions. It’s a way of identifying files on the Internet according to their nature and format. For example, using the “Content-type” header value defined in an HTTP response, the browser can open the file with the proper extension/plugin.

Q14. What is a servlet?

Servlet can be described in many ways, depending on the context.

  • It is a technology i.e. used to create a web application.
  • Servlet is an API that provides many interfaces and classes including documentations.
  • It is an interface that must be implemented for creating any servlet.
  • The Servlet is a class that extends the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.
  • It is a web component that is deployed on the server to create a dynamic web page.

Q15. What are common tasks performed by Servlet Container?

  • Communication Support: Servlet Container provides an 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 the 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 a 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 process. 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 the 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.

Q16. What is a ServletConfig object?

javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has its own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.XML file or through the use of WebInitParam annotation. We can use getServletConfig() method to get the ServletConfig object of the servlet.

Q17. What is a ServletContext object?

The ServletContext interface provides information to servlets about the environment in which they are running. Each web application has only one ServletContext object. The context also is known as Web context and is created by the Web container as an object of the ServletContext interface.

Q18. How can we create a deadlock situation in servlet?

We can create a deadlock in servlet by making a loop of method invocation, just call doPost() method from doGet() method and doGet() method to doPost() method to create a deadlock situation in servlet.

Q19. What is the use of servlet wrapper classes?

Servlet HTTP API provides two wrapper classes – HttpServletRequestWrapper and HttpServletResponseWrapper. These wrapper classes are provided to help developers with a custom implementation of servlet request and response types. We can extend these classes and override only specific methods we need to implement for the custom request and response objects. These classes are not used in normal servlet programming.

Q20. What is the inter-servlet communication?

When we want to invoke another servlet from a servlet service methods, we use inter-servlet communication mechanisms. We can invoke another servlet using RequestDispatcher forward() and include() methods and provide additional attributes in a request for other servlet use.

Q21. Are Servlets Thread Safe? How to achieve thread safety in servlets?

HttpServlet init() method and destroy() method are called only once in servlet life cycle, so we don’t need to worry about their synchronization. But service methods such as doGet() or doPost() are getting called in every client request and since servlet uses multithreading, we should provide thread safety in these methods.

If there are any local variables in service methods, we don’t need to worry about their thread safety because they are specific to each thread but if we have a shared resource then we can use synchronization to achieve thread safety in servlets when working with shared resources.

Q22. How do we call one servlet from another servlet?

We can use RequestDispatcher forward() method to forward the processing of a request to another servlet. If we want to include the another servlet output to the response, we can use RequestDispatcher include() method.

Q23. How can we invoke another servlet in a different application?

We can’t use RequestDispatcher to invoke a servlet from another application because it’s specific for the application. If we have to forward the request to a resource in another application, we can use ServletResponse sendRedirect() method and provide complete URL of another servlet. This sends the response to the client with response code as 302 to forward the request to another URL.

Q24. Why is HttpServlet class declared abstract?

HttpServlet class provide HTTP protocol implementation of servlet but it’s left abstract because there is no implementation logic in service methods such as doGet() and doPost() and we should override at least one of the service methods. That’s why there is no point in having an instance of HttpServlet and is declared an abstract class.

Q25. What are life cycle methods of a servlet?

Servlet Life Cycle consists of three methods:

  1. The public void init(ServletConfig config) – This method is used by the container to initialize the servlet, this method is invoked only once in the lifecycle of a servlet.
  2. The public void service(ServletRequest request, ServletResponse response) – This method is called once for every request, container can’t invoke service() method until unless init() method is executed.
  3. public void destroy() – This method is invoked once when the servlet is unloaded from memory.

Q26. What is URL Encoding?

URL Encoding is the process of converting data into CGI form so that it can travel across the network without any issues. URL Encoding strips the white spaces and replace special characters with escape characters. We can use java.net.URLEncoder.encode(String str, String Unicode) to encode a String. URL Decoding is the reverse process of encoding and we can use java.net.URLDecoder.decode(String str, String Unicode) to decode the encoded string.

Q27. What are different methods of session management in servlets?

The session is a conversational state between client and server and it can consist of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

Some of the common ways of session management in servlets are:

  1. User Authentication
  2. HTML Hidden Field
  3. Cookies
  4. URL Rewriting
  5. Session Management API

Q28. How do Cookies work in Servlets?

Cookies are used a lot in web client-server communication, it’s not something specific to java. Cookies are text data sent by the server to the client and it gets saved to the client local machine.

Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.

There are three steps involved in identifying returning users:

  • Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  • The browser stores this information on the local machine for future use.
  • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

Q29. How to get the actual path of the servlet in the server?

We can use following code snippet to get the actual path of the servlet in file system.

getServletContext().getRealPath(request.getServletPath())

Q30. How to get the server information in a servlet?

We can use below code snippet to get the servlet information in a servlet through servlet context object.

getServletContext().getServerInfo()

Q31. How to get the IP address of the client in servlet?.

We can use request.getRemoteAddr() to get the client IP address in servlet.

Q32. What are important features of Servlet 3?

  1. Servlet Annotations: Prior to Servlet 3, all the servlet mapping and it’s inited parameters were used to defined in web.xml, this was not convenient and more error prone when a number of servlets are huge in an application. It introduced the use of java annotations to define a servlet, filter and listener servlets and init parameters. Some of the important Servlet API annotations are WebServlet, WebInitParam, WebFilter and WebListener. Read more about them at Servlet 3 annotations.
  1. Web Fragments: Prior to servlet specs 3.0, all the web application configurations are required to be present in the web.xml that makes it cluttered with a lot of elements and chances of error increases. So servlet 3 specs introduced web fragments where we can have multiple modules in a single web application, all these modules should have web-fragment.xml file in META-INF directory. We can include all the elements of web.xml inside the web-fragment.XML too. This helps us in dividing our web application into separate modules that are included as a JAR file in the web application lib directory.
  2. Adding Web Components dynamically: We can use ServletContext object to add servlets, filters, and listeners programmatically. This helps us in building a dynamic system where we are loading a component only if we need it. These methods are addServlet(), addFilter() and addListener() defined in the servlet context object.
  3. Asynchronous Processing: Asynchronous support was added to delegate the request processing to another thread rather than keeping the servlet thread busy. It can increase the throughput performance of the application. This is an advanced topic and I recommend to read Async Servlet.

Q33. What are different ways for servlet authentication?

servlet Container provides different ways of login based servlet authentication:

  1. HTTP Basic Authentication
  2. HTTP Digest Authentication
  3. HTTPS Authentication
  4. Form Based Login: A standard HTML form for authentication, the advantage is that we can change the login page layout as our application requirements rather than using HTTP built-in login mechanisms.