Servlet Interview questions and Answers

Thumb

Author

BIQ

Questions

28

Last updated

Mar 11, 2022

The Servlet is a class used in Java applications for enhancing the capabilities of the server. Java servlets run on web application server container and are used to generate HTML content that shows on the web browser. Servlets respond to request from the browser and return response content.  Our new collection of Servlet interview questions is a must-read for all developers. Servlets are mostly implemented for HTTP protocol and are also called as HTTP Servlet.

About Servlet
What is Servlet Servlets generate dynamic HTML content and respond with excel, XML, pdf, and JSON and other formats. Initially, servlets were meant for creating HTML content in applications, but now they are mostly used at the controller layers.
Latest Version 4.0, released in September 2017.
Created By Pavni Diwanji
Specification JSR 369
Platform Java EE 8
Important Changes HTTP/2

Most Frequently Asked Servlet Interview questions

Here in this article, we will be listing frequently asked Servlet Interview questions and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.

Q1. What is Servlet and list its types?
Answer

The Servlet is a class used in Java applications for enhancing the capabilities of the server. Servlets respond to a request from the browser and return response content and also run on web application server container and are used to generate HTML content that shows on the web browser.

There are two types of servlets - generic and HTTP

Q2. Explain the difference between generic Servlet and HTTP Servlet?
Answer
  Generic Servlet HTTP Servlet
1. Subclass of javax.servlet.GenericServlet Subclass of javax.servlet.HttpServlet
2. Protocol independent Protocol dependent
3. Belongs to javax.servlet package Belongs to javax.servlet.http package
Q3. Explain the lifecycle of a Servlet?
Answer

Servlert’s life cycle is the entire process from its creation until its destruction. A Servlet follows this path:

  • Initialized by calling init( ) method
  • Calls service( ) method to process request
  • Terminated by destroy( ) method

Finally, the servlet is nothing but the garbage that gets collected by JVM's garbage collector.

Q4. What do you mean by CGI in Servlet?
Answer

CGI or Common Gateway Interface provides dynamic content to users by executing a program that resides in the server. This program processes data to produce dynamic content. Other programs that reside in the server can be written in the native OS such as C++.

Q5. What are the difference between Servlet and CGI?
Answer
  Servlet CGI
1. Portable Not portable
2. Requests handled by lightweight Java Thread Requests handled by heavyweight OS process
3. Data sharing possible Data sharing not available
4. Link directly to the Web server Cannot link directly to the Web server
Q6. Explain the difference between GET and POST method in Servlet?
Answer
  GET method POST method
1. A limited amount of data can be sent as data is sent in the header Lot of data can be sent as data is sent in the body
2. Not secured because data is exposed Secured because data is not exposed
3. Can be bookmarked Cannot be bookmarked
Q7. Explain the difference between ServletConfig and ServletContext in Servlet?
Answer
  ServletConfig ServletContext
1. Parameters specified for a specific servlet. Parameters specified for the entire application.
2. The object created during the initialization process. The object created during web application deployment.
3. Available as long as the servlet is executing. Available as long as the application is executing.
Q8. What do you mean by Session Tracking and also explain its techniques?
Answer

Session tracking is a technique that servlets use to maintain a record of a series of requests originating from the same user or the same browser across a period of time. These sessions are shared between the servlets that are accessed by a client.

There are 4 techniques to track sessions:

  • Cookies
  • Hidden Fields.
  • URL Rewriting.
  • Session Tracking API.
Q9. What are the difference between session and cookies in Servlet? Explain
Answer
  Sessions Cookies
1. Server-side files. Client-side files.
2. Stores unlimited content in user's browser. Stores limited content of limited users.
3. Data is not easy to modify. Data is easy to modify.
Q10. What do you mean by filter in servlet?
Answer

A filter is an object that filters tasks that are either request to a resource, or response from a resource, or both. Filtering is performed in doFilter method. Filters get configured in deployment descriptor of your application.

Q11. How to upload a file to the server using servlet?
Answer
Q12. What do you mean by Request Dispatcher in Servlet? Also explain its methods.
Answer

RequestDispatcher interface defines an object that can dispatch the request to resources like HTML, JSP, and Servlet, on the server. This interface provides two methods

forward (ServletRequest request, ServletResponse response) will forward a request from Servlet to another resource such as a Servlet, JSP, or HTML, on the server.

Include (ServletRequest request, ServletResponse response) will include the content of a resource such as Servlet, JSP, or HTML, in the response.

Q13. What is the difference between forward () and sendRedirect () functions in Servlet? Explain
Answer
  forward() sendRedirect()
1. Server-side redirect. Client-side redirect.
2. Redirect is at the server end, not visible to the client. Redirection is at the client end and visible to the client.
3. Original URL remains intact. Original URL changes.
Q14. Explain the jar and war files in servlet?
Answer

Both WAR and JAR have the same file structure of a single file that is compressed and contains multiple files inside it. WAR files combine servlets, JSPs, Java and XML files, JAR libraries, javascript libraries, static web pages, and other resources that are needed to run the applications.

Q15. What are the types of an HTTP request?
Answer

HTTP outlines a set of request methods that indicate the action to be performed for a resource. Each request method implements a different semantic, but they also share some common features. Here are the 7 HTTP request methods every web developer preparing for Servlet interview questions and answers should know:

  • GET
  • HEAD
  • POST
  • PUT
  • DELETE
  • OPTIONS
  • PATCH
Q16. How we can create war file in servlet?
Answer

In order to create a WAR file, use JDK's JAR tool. Use -c switch of jar for creating the war file. Enter the project directory of your project and write this command: jar -cvf projectname.war * Here, -c is for creating file, -v for generating verbose output and -f for specifying name of the archive file.

Q17. What do you mean by SingleThreadModel interface?
Answer

The SingleThreadModel interface ensures that only one thread is executed at a given point of time in a given servlet service method. This is a marker interface and contains no methods. This interface also ensures thread-safe servlets.

Q18. What is URL Encoding in Servlet?
Answer

URL Encoding process transforms user input to a Common Gateway Interface (CGI) form. It is fit to travel across the network through stripping spaces, punctuation and replacement with escape characters.

Q19. What is URL Pattern in Servlet?
Answer

The url-pattern associates a servlet with a set of URLs. When a request from the user arrives, the container uses basic process to match the URL in the request with a URL pattern in the web.xml file. A URL pattern may sometimes contains subsets of US-ASCII characters.

Q20. How we can get IP address of client in servlet?
Answer

Here are 2 methods for getting client’s IP address in Servlet:

HttpServletRequest.getRemoteAddr method returns IP of the client that sends request.

HttpServletRequestgetRemoteHost method returns the hostname of the client that is sending the request. However, it may return an empty string if hostname is unknown.

Q21. Explain the features are in Servlet 3?
Answer

Servlet 3.0 is an update of Servlet 2.5. Servlet 3.0 focuses on extensibility and pluggability. Key features in Servlet 3.0 can be categorized into the following areas:

  • Easier development with annotations.
  • Web application modularity.
  • Asynchronous Servlet.
  • Programmatic instantiation of Servlets/Filters.
  • Security Enhancements.
Q22. Explain the different ways for servlet authentication?
Answer

There are ways of servlet authentication:

  • HTTP basic authentication.
  • HTTP digest authentication.
  • HTTPS client authentication.
  • Form-based authentication.
Q23. How to call a jsp from the servlet?
Answer

You can invoke a JSP web page from a servlet via the functionality of the popular javax.servlet.RequestDispatcher interface. Complete the following steps in your code to use this mechanism:

  • Get a servlet context instance from the servlet instance:
    ServletContext sc = this.getServletContext();
  • Get a request dispatcher from the servlet context instance, specifying the page-relative or application-relative course of the goal JSP page as enter to the getRequestDispatcher() method:
    RequestDispatcher rd = sc.getRequestDispatcher("/jsp/mypage.jsp");
    Prior to or in the course of this step, you can optionally make facts on hand to the JSP page thru attributes of the HTTP request object. See the next section, "Passing Data Between a JSP Page and a Servlet", for information.
  • Invoke the include() or forward() approach of the request dispatcher, specifying the HTTP request and response objects as arguments. The performance of these techniques is similar to that of jsp:include and jsp:forward actions. The include() approach solely briefly transfers control; execution returns to the invoking servlet afterward.
Q24. What is Annotations in Servlet?
Answer

Servlet 3.0 has introduced javax.servlet.annotation that provides annotation types, which can annotate servlet classes. Annotation also represents metadata. So, if you are using annotation, you may not require deployment descriptor.

Note: This is very essential java servlet interview questions which is asked in every interviews.

Q25. Explain the difference between a Web server and a web container?
Answer
  Web Server Web Container
1. Provides Request and response for HTTP . Ensures servlet objects life style is maintained.
2. Handles client request through HTTP. Uses service method for some servlet objects .
3. Delivers resources and data of web pages . Responsible for running the servlets .
4. Serves static content. Serves dynamic content
5. Superset Only a part of a superset
Q26. Explain the difference between JSP and servlet?
Answer
  Servlet JSP
1. Java code HTML-based code
2. Acts like a controller in MVC. View for showing output in MVC approach.
3. Accepts protocol requests. Accepts only HTTP requests.
4. May override service() method. Not possible to override service() method.
Q27. What do you mean by chaining in Servlet?
Answer

Accepting a request from the browser and processing it using multiple servlets in a chain is called Servlet Chaining. In this process, communication occurs between chains of servlets and servlet programs in order to process the client's request. This process may make the user requests visible to multiple servlets.

Note: This is a very important Servlet Interview Questions.

Q28. What is event in Servlet?
Answer
Events are scenarios of activity that take place throughout a software existence cycle.
For example, if you are jogging a Graphical User Interface (GUI) program, click on a button can be a scenario of interest.