Servlet Interview Questions and Answers

    1 Votes

Top 75+ frequently asked J2EE Interview Questions on servlet with best answers for freshers and 2-6 year experienced java programmers and web developers on basic and advanced topics.

1. What is a servlet?

A servlet is a java program that runs within a web server and serves the client request hence the name servlet. Servlets can receive and respond to requests from web clients working on any client-server protocol, but HTTP is predominantly used. Servlet is a server side script technology which can process client request and give back the response.

2. What is a servlet container?

A servlet container is a container for servlets which is responsible for managing the servlets. The main functions are load, initialize and execute servlets to serve client requests. When a request is received, the container decides what servlet to call based on a configuration file. Servlet container comes installed with the web servers. Examples: Tomcat, Glassfish, JBoss.

3. What is CGI?

Common Gateway Interface(CGI) was the most commonly used for server side scripting before the evolution of the java servlet technology. With traditional CGI, a new process is started for each HTTP request eating up more of the CPU cycles thus degrading the performance of the system.

4. What are the advantages of servlet over CGI?

  • When a CGI script is called, a new process is created for each and every client request. But for servlets, each request is handled by a separate thread. Hence, servlet is more efficient because process creation takes more time compared to thread creation.
  • For each new CGI requests, CGI script is copied into memory. But with servlets, there is only one copy across requests and is shared among threads.
  • In CGI multiple process serves concurrent requests. But for servlets, only single instance serves concurrent requests.

5. Describe about the life cycle of servlet?

Life cycle methods of a servlet are:

  • init() method: During initialization web container initializes the servlet instance by calling the init() method passing a ServletConfig interface object as parameter. The ServletConfig object allows the servlet to access initialization parameters. It is called only once in the life cycle of servlet.
  • service() method: When client requests are serviced this method gets called. Each requests is serviced in its own thread. For every client requests web container calls the servlet’s service method. The service method determines the type of requests and invokes the appropriate method e.g. if the client request is HTTP get method then corresponding servlet’s doGet() method will be called.
  • destroy() method: The web container calls the destroy method and takes the servlet out of service. It is called only once in the life cycle of servlet, when you stop the server or when you undeploy the application from the server.

6. Explain MVC design pattern?

Model-View-Controller (MVC) is a design pattern which divides a software application into three parts namely model, view and controller.

  • A model deals with behavior of the application. It contains the data and business logic of the application. It notifies views and controllers when there is change in its state.
  • A view renders the information to the user so that it looks attractive and appealing. It takes information from the model using which it generates output.

A controller takes input from user and sends command to model or view. It controls the flow of application.

7. Explain the web application directory structure?

web application’s directory structure has document root which contains JSP files, HTML files, JavaScript files and static files such as image files. There is a directory WEB-INF under the document root which contains configuration files related to application. This configuration files can’t be served directly to the client. The WEB-INF directory contains:

  • /WEB-INF/classes/* : It contains compiled class files
  • /WEB-INF/lib/*.jar : It contains different library jar files
  • /WEB-INF/web.xml : It is a deployment descriptor that specify the web application configuration.

8. what are the two packages that deal with servlets?

Servlet API exist in two packages:

  • Javax.servlet: The classes and interfaces in javax.servlet are not protocol dependent. e.g. It can support different protocols like HTTP, FTP.
  • Javax.servlet.http: The classes and interface in this package are specific for requests using HTTP protocol. Some of the classes and interfaces in this package extend those of javax.servlet package.

9. Explain servlet class hierarchy?

  • Interface Servlet: It declares the standaed API’s which all the servlet implementations needs to define. All servlet classes must implement this interface directly or indirectly.
  • Class GenericServlet: It defines a generic, protocol independent servlet. Servlet developed to cater NON-HTTP requests.
  • Class HTTPServlet: Servlet used to cater client HTTP requests.

10. What is Servlet interface?

The Servlet interface is the abstraction of Java Servlet API. It declares the life cycle methods of a servlet. All the servlet classes must implement it either directly or indirectly by extending a class which implements the Servlet interface. E.g. HTTPServlet, GenericServlet.

11. What is destroy() method of Servlet interface?

It is invoked by the servlet container to indicate that the servlet is taken out of service.

12. What is init() method of Servlet API?

It is called by the servlet container to indicate to a servlet that the servlet is being placed into service. Init() method takes ServletConfig object as an argument. ServletConfig object contains initialization and startup parameters for the servlet.

13. What is service() method of Servlet API?

It is invoked by the servlet container to allow the servlet to respond to a request.

14. What is HTTPServlet?

HTTPServlet is an abstract class. Any servlet that works on the HTTP should extend this class. This class contains implementations of methods that are specific to HTTP. It contains doXXXX methods which are known as the service methods. All the servlets extending this class should implement any one of the doXXXX() methods. E.g. doGet(), doPost().

15. List different types of HTTP requests?

get, post, head, options, put, trace, delete.

16. List the do-XXXX methods in HTTPServlet?

void doGet(HTTPServletRequest req, HTTPServletResponse res)
void doPost(HTTPServletRequest req, HTTPServletResponse res)
void doHead(HTTPServletRequest req, HTTPServletResponse res)
void doOptions(HTTPServletRequest req, HTTPServletResponse res)
void doPut(HTTPServletRequest req, HTTPServletResponse res)
void doTrace(HTTPServletRequest req, HTTPServletResponse res)
void doDelete(HTTPServletRequest req, HTTPServletResponse res)

17. Explain briefly the doGet and doPost methods in HTTPServlet?

Void doGet(HTTPServletRequest req, HTTPServletResponse res)

Above method is called by the server (via service method) to allow a servlet to handle a GET request. It will be called when a URL is requested or the form method is GET.

Void doPost(HTTPServletRequest req, HTTPServletResponse res)

It is called by the server (via service method) to allow a servlet to handle a POST request. It will be called when the form method is POST.


18. What is the use of HTTPServletRequest Interface?

This interface contains methods to access request information by the HTTP servlets. It is used by servlets to access the parameters sent by client as part of HTTP request from the browser. It is used to access client information like port number, client protocol and form field values.

19. What is the use of HTTPServletResponse interface?
This interface contains methods for managing the response send by an HTTP servlet to the client. It also contains a set of status codes for sending the request status to the client.
20. What is web.xml file?

web.xml is a configuration file which captures the application configuration and deployment details of a web application.

21. How ServletConfig object is loaded and initialized?

  • Step 1: When a request to a servlet comes for the first time from client or when the application is deployed the web container will initialize the servlet.
  • Step 2: The web container will parse the web.xml file and read the configurations of the servlet to be initialized.
  • Step 3: The web container then will create a ServletConfig object and load the configuration details of the servlet in the object.

22. How to use ServletConfig?

ServletConfig is passed as an argument to the init() method of the servlet by the web container during servlet initialization. Hence to use ServletConfig we need to override the method:

public void init(ServletConfig config) throws ServletException

23. What are servlet initialization parameters?

Initialization parameters are used by developers to set some parameter values for the servlet to use. This will be stored as key/value pairs.

Example: Assume in a application there is a rule that by default the employee citizenship is Indian. In EmployeeServlet the developer can set the initialization parameter as “Citizenship = Indian” where the “Citizenship” is the key and “Indian” is the value.

These parameters can be configured in web.xml. These parameters will be loaded to the ServletConfig object during the servlet initialization phase.

24. How do we set init parameter in web.xml?

Init parameters are declared inside <init-param> tag. The parameter name is declared <param-name> and value inside <param-value> respectively. Init parameter is declared separately for each servlet. Each init parameter needs to declared inside a separate <init- param> tag. For example,

<init-param>
<param-name>admin-email</param-name>
<param-value>This email address is being protected from spambots. You need JavaScript enabled to view it. </param-value>
</init-param>

25. How to read initialization parameter?

Init parameter can be read using the getInitParameter() method of ServletConfig object.

String var = config.getInitParameter(String parameterName)

Where config is the ServletConfig object and parameterName is the key name of the parameter set in web.xml.

26. What is a servlet context?

It refers to the context in which the servlet runs. It is a gateway between the web container and the servlets. There will be only one instance of servlet context per web application shared by all the servlets in the application. It is used for storing values which can be shared across all the servlets in the web application.

27. Where is servlet context used?

In development projects servlet context are used in the following instances,

  • To store master data values which is used by presentation tier, example: states, country, account status etc.
  • To store menu links which is used across many JSP/servlets in an application.

28. What is the difference between context parameter and attribute?

  • Context parameter are values which is set in the web.xml and can be loaded during the application deployment.
  • Context attribute are values which are dynamically set by the application(say servlet) for sharing it across the application.

29. How can we read context parameters?

Context parameters can be read using getInitParameter() method of the ServletContext interface.

String var = context.getInitParameter(String paramName);

Where paramName is the key with which the value is stored in web.xml.

30. What are context attributes?

Context attributes are the attribute values set by any servlet which can be accessed by any other servlet in the same context. It is used for sharing values among other servlets.

31. How can we set context attributes?

Attribute value can be set using the setAttribute() method of the ServletContext interface.

context.setAttribute(String attributeName, Object value);

Where attributeName - is the name of the attribute with which the value can be stored and referred to.
Value – the value stored in the context.

32. How can we read context attributes?

Attribute value can be read using the getAttribute() method of the ServletContext interface.

Object var = context.getAttribute( attributeName);

Where attributeName - is the name of the attribute which needs to be retrieved from the context.

33. What is Response Buffering?

By default, any response written to the output stream is immediately sent to the client as HTTP response. Buffering is the process by which the content are written into a buffer before being sent to the client, thus providing the servlet a better control on the response being sent.

Buffering also makes effective use of network bandwidth since response is sent to the client after a specified buffer size is reached.

34. How servlet works without buffering?

Assume that a client requests for payroll details and PayrollServlet responds back with 200 bytes of data. As soon as the first kb data response is written in the output stream it is pushed to the client. So before the servlet is able to process the entire request the client starts receiving the response.


35. How servlet works with buffering?

Assuming buffer size is set to 150 kb only if the buffer is filled with 150 bytes of data the response will be sent to client. So buffering allows the servlet to control the response till the buffer gets filled up.

36. What is servlet chaining?

Servlet chaining is a technique in which two or more servlets orchestrate in servicing a single request. In servlet chaining, one servlet’s response is piped to next servlet’s input. This process continues until the last servlet is reached. Its output is sent back to the client. The same request and response objectare available across all the servlets in the process.

37. Explain about two ways of servlet chaining?

Two ways of servlet chaining are:

  • Include: This refers to the process of including the response of one or more servlets with the response of the servlet being requested and the collated response sent to the client by the servlet being requested.
  • Forward: The servlet being requestesd by the client forwards the request to one or more servlet and finally the response is sent to the client by last servlet invoked in the Chain.

38. How do we chain servlets?

  • Create the RequestDispatcher for the resources to be chained.
  • Set attributes to request if needed.
  • Call the include or forward method on the RequestDispatcher object.

The include/forward method can be performed only in the service methods(get/post) of a servlet and in turn can be handled in the service method of the included/forwarded servlet. Example: Include from a get method in first servlet can be handled only by get method in the included servlet. Same applies to post method also.

39. What is a RequestDispatcher object?

RequestDispatcher is an object which accepts the request from the client and redirects them to any resource(Servlets, JSP, HTML etc). The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or identified by a particular name.

40. How do we get RequestDispatcher object?

RequestDispatcher dispatcher = request.getRequestDispatcher(“FooterServlet”);

Where request is the HTTPServletRequest object and FooterServlet is the servlet to which the request needs to be dispatched.

41. What are include() and forward() methods?

  • forward() : Used to forward request to another resource.
dispatcher.forward(request,response);
  • include() : Includes the content of a resource(servlet, jsp page, html file etc) in the response.
dispatcher.include(request,response);

where request, response are HTTPServletRequest and HTTPServletResponse object and dispatcher is a RequestDispatcher object.

42. How to share value in servlet chain?

Values can be shared among the included/forwared servlets by setting attributes, we can set values as attributes in the request object and share between the servlets.
Request attribute is available only in the request scope which means the attribute is lost once the response is send to the user.

request.setAttribute(attributeName,value);

43. What are the steps to incude a servlet?

  • Step 1: Create the RequestDispatcher object
RequestDispatcher dispatcher = request.getRequestDispatcher(“SecondServlet”);
  • Step 2: Set request attributes if needed
  • Step 3: Call the include method to include the servlet
dispatcher.include(request,response);

44. Where to use include method in an application?

  • Include is used for reusing common code. Like a servlet to print the user login information in all the pages, the common servlet can be included in all the pages.
  • Use include if you want to present a collated response from a set of components(servlets,JSP etc).
  • Include can also be used for including static content to a page such as the page footer can be reused across all the pages in the application.

45. Where to use forward method in an application?

  • Forward is also used for code reusability.
  • Forward are typically used to forward a request to a success or error page after some processing. Example: After login credentials validated if success the control will be forwarded to home page else sent to error page.

46. What are the steps to forward a request?

  • Step 1 : Create the RequestDispatcher object
RequestDispatcher dispatcher = request.getRequestDispatcher(“SecondServlet”);
  • Step 2 : Set request attributes if needed.
  • Step 3 : call the forward method to forward request.

47. What happens if forward method is called after response is committed?

Forward should be called before response has been committed. If the response has already been committed, forward method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

48. How Send Redirect works?

  • User requests a URL to the server.
  • Server sends the browser a status to redirect to a new URL.
  • Browser requests a new URL and sends a new request.

49. What are the disadvantages of Send Redirect?

  • It requires a round trip process.
  • The original request parameters are not included in the new HTTP request.

50. How forward method works?

  • User requests for a resource in server.
  • Server redirects the request to a new resource.
  • New resource sends the response to the client.

51. What are the advantages of forward method?

  • It works inside the servlet engine hence it is faster.
  • Forward is invisible to browser.
  • The original request received is preserved in the redirected resource.

52. What is session management?

Session management is a mechanism for maintaining state across multiple HTTP requests. This is managed by the web container. In other words it is a technique to hold some values passed by user across multiple HTTP requests arising out from a single browser instance.

53. How long session life cycle is managed?

Session life cycle is managed for each web browser instance opened and it exists till the browser is closed or till the session time outs(set in the server configurations).

54. What is the need for session?

HTTP is a stateless protocol. So if developers need to develop pages where needs to maintain the application user’s state across multiple requests he can use session. For example, he can store the following information: Login name, users state/city, user ID number etc.

55. How is session tracked for a user?

Each user session is tracked by unique ID called JSESSIONID. This is similar to how a employee is identified in a organization using employee id. JSESSIONID will be generated the first time the user visits a site. JSESSIONID will be generated for each browser instance.

56. What are session management techniques?

The following are the session management techniques. These are used for managing the data’s between pages of the user in a session.

  • Hidden Form fields
  • URL Rewriting
  • Cookies
  • Session object

57. What is a Hidden Field?

Hidden Fields are nothing but normal HTML form element with type Hidden to store the user data across HTTP request.

58. How Hidden Form field is used for session tracking?

The user state to be preserved across HTTP request can be stored as a hidden elements in the HTML pages which can be read from other pages.

59. How to access Hidden form field values?

Hidden form field values can be read using request.getParameter(“key”) method.

60. What are the advantages of Hidden form field?

  • It does not consume any memory space in web server as it is stored in the HTML pages.
  • It works even if users disable cookies.

61. What are the disadvantages of Hidden form field?

  • It can be used only with HTML forms.
  • This is not secured.
  • Very complex to develop and maintain as all the pages which needs state information needs to be implemented for the hidden fields.

62. What is URL rewriting?

The mechanism by which the user state or information’s are appended to the URL for tracking the state/session of the user. Example: The userName is appended to the URL.

http://ww.a4academics.com/SuccessServlet?userName=”Tim”&location=”India”

where, userName and location are user information set as parameter in the URL.

63. What are the advantages of URL rewriting?

  • Every data is appended to the URL. So it is easy to debug.
  • It works even if users disable cookies.

64. What are the disadvantages of URL rewriting?

  • URL length is a limitation, so we cannot store information beyond a limit.
  • The URL contains data so it is not secured.
  • Difficult to maintain in large application since in each page the URL should be rewritten to carry the data.

65. What is a cookie?

It is a simple piece of textual information(in key value pair format) stored on the client(browser machine). Cookies information are returned to the server with every request from the client.

66. How cookies are identified in client machine?

The browser matches the cookies present with the site URL. If a match is found, that cookie is returned with the request.

67. What are the steps for using cookie?

  • Step 1: Create the cookie object.
  • Step 2: Set the cookie object to the HTTP response.
  • Step 3: Read the cookies from the next HTTP request.
  • Step 4: Validate the cookie value for session tracking.

68. How cookie is created?

Cookies are created using the Cookie class of Servlet API.

Cookie cookie = new Cookie(identifier,value);

Where identifier is the name of the state information, value represents the value of the state.

Example: Cookie cookie = new Cookie(“userName”,”Tim”);

69. How cookies are set to the response?

Since cookies are stored at the client, cookies are set to the response object and sent to the client using the addCookie() method of the HTTPServletResponse interface.

Cookie cookie = new Cookie(“userName”,”Tim”);
response.addCookie(cookie);

70. How cookie values are read from request?

Cookies stored in the client will be sent to the server along with the HTTP request, each time the client requests a page. The cookies in request object can be read using the getCookies() of the HTTPServletRequest interface.

Cookie[] cookieList = request.getCookies();

cookieList array can be traversed to read all the cookie value associated with particular client session.

71. What are the advantages of using cookie?

  • It is easy to develop and maintain.
  • Less overhead to the server since data is stored in the client.
  • It minimizes the server memory usage.

72. What are the disadvantages of using cookie?

  • Size and number of cookies stored are limited.
  • Stored as plain text in a specific directory, everyone can view and modify them. So it is not secured.
  • It is browser dependent, so if client has disabled cookies this can lead to erroneous behavior of the application.

73. What is a session object?

Session object is a container used for storing user states in server.

  • The session object lifecycle is maintained by web container.
  • The Servlet API HTTPSession interface provides features for session tracking.
  • HTTPSession objects are objects used for storing client session information.

74. How are session values stored?

Session values are stored in key/value format similar to Map interface. Each value would have a name bound to it for retrieving the values.

75. How session object is accessed?

Session object associated with a user session is read from the user HTTP request using the getSession() method of the HTTPServletRequest interface.

HTTPSession session = request.getSession();

Popular Videos

communication

How to improve your Interview, Salary Negotiation, Communication & Presentation Skills.

Got a tip or Question?
Let us know

Related Articles

JSP Interview Questions and Answers
Advanced Servlet Interview Questions and Answers
EJB Interview Questions and Answers
Spring Interview Questions and Answers