Advanced Servlet Interview Questions and Answers

    1 Votes

Advanced Servlet Interview Questions and Answers for freshers and 2-6 year experienced java programmers asked by top MNC's like IBM, Oracle, Wipro, TCS, Infosys, Accenture and CTS.

1. How to set values in HTTP Session?

We can set values in session object using setAttribute() method of the HTTPSession interface.
HTTPSession session = request.getSession();
session.setAttribute(String attributeName, Object value);
Let's take a web mail application where user Name and location are stored.
HTTPSession session = request.getSession();
session.setAttribute(“User”,”Tim”);
session.setAttribute(“Location”,”Bangalore”);

 

2. How to retrieve attributes from session?
We can retrieve attributes from the session object using getAttribute() method of the HTTPSession interface.
HTTPSession session = request.getSession();
Object var = session.getAttribute(String attributeName);
Taking a web mail application where user Name and location are stored and retrieving the values.
HTTPSession session = request.getSession();
String userName = (String)session.getAttribute(“User”);
String location = (String)session.getAttribute(“Location”);
3. How to remove attributes from session?
Values can be removed from the session object using removeAttribute() method of the HTTPSession interface.
HTTPSession session = request.getSession();
session.removeAttribute(String attributeName);
Example: Taking a web mail application where user Name and location are stored. Assume we need to remove the userName attribute “Tim” from the session, the following API needs to be fired on HTTP request object.
HTTPSession session = request.getSession();
session.removeAttribute(“User”);
4. How to invalidate a session?

Session invalidating is the process of unbinding the session object from the user thereby removing all the previously stored data in the session and freeing the memory. To invalidate a session we call the invalidate() method.

5. When session invalidate() method is used?

This is typically used when user logs off from a web application to free up the memory utilized by the session object.

HTTPSession session = request.getSession();
Session.invalidate();

6. Why to avoid storing bulky objects in session?

Session objects are stored in server and it utilizes memory. So store only the needed information in sessions. Avoid bulky objects in session this can result in “out of memory error” resulting in a application crash.

7. What are the advantages of using HTTP Session?

Simple to use since it is managed in the server. It can function even when the cookie functionality is turned off in the browser.

8. What are the disadvantages of HTTP Session?

Since session objects are stored in the server the server memory required is more which is costly.

9. What are the attribute scopes in servlet?

Attribute scopes in servlet are:

  • Application scope
  • Session scope
  • Request scope

10. Compare between different attribute scopes in servlet?

Application scope:

  • It can be accessed by all servlet/JSP in the web application.
  • It is available for the life time of the application.
  • Achieved by storing in the ServletContext object.

Session scope:

  • It can be accessed by all servlet/JSP in the web application.
  • It is available for the life time of the session.
  • Achieved by storing in the HTTPSession object.

Request scope:

  • It is available to all servlet/JSP that have access to this specific request.
  • Available for the life of the request that is until response send to the client.
  • Achieved by storing in the HTTPServletRequest object.

11. What is a servlet event listener?

Listeners are used to perform some logic on trigger of certain events. Listeners are java classes that is used to implement the event handling mechanism. Example for Listener:

  • Listener class can be used for auditing user login information’s.
  • Listener classes can be used to clean up session objects and free memory when user logs off.

12. Classify the type of events in an web application?

There are three kind of events:

  • Servlet Context Events: These are events triggered when there is a change in the ServletContext object.
  • HTTP Session Events: These are events triggered when there is a change in the Session object.
  • Servlet Request Events: These are events triggered when there is a change in the request object.

13. When are events triggered?

The events are triggered under two circumstances:

  • Lifecycle changes: If there is a lifecycle change on the object. For example, when session created (or) initialized (or) destroyed.
  • Attribute changes: Any attribute stored /changed in the session. For example, when a attribute “message” is stored in the session.

14. Who triggers the events?

Whenever one of the changes in lifecycle or attribute happens the events are triggered by the web container which can be captured by listeners to perform a logic.

15. What are the steps to develop a servlet listener?

  • Step 1: Create the listener class. Listener class is done by implementing the required servlet listener interface by a normal java class and overriding all the methods.
  • Step 2: Listener class is registered with the deployment descriptor file.

16. What is a servlet filter?

Servlet filter are programs that runs on the server which intercepts HTTP request/response for transformations/processing/filtering.

17. How does filter work?

Steps of operation of a servlet filter:

  • Step 1: Intercepts the HTTP request and preprocess the request.
  • Step 2: Invokes the requested resource with the preprocessed HTTP request.
  • Step 3: Intercepts the HTTP response and transforms it.
  • Step 4: The transformed HTTP response will be sent back to the client.

18. What are the usage of filters?

  • Used for authenticating all HTTP request coming to the server. Example: All requests to the application will be authenticated and authorized against stored user credentials.
  • All the HTTP requests can be logged and audited in a flat file or database for tracking users of a web application. Example: The user credentials can be logged as “Ron logged in at 8:00 PM and he transferred 10,000 dollars from the account.
  • To perform some formatting of HTTP response, say display a message in the header (or) bread crumbs for all the pages of the application. Example: All the HTML pages displayed in the client should have the navigation breadcrumb like “Home Page> Savings Account> Account Summary”

19. Name and define important filter interfaces?

  • Filter: Contains the methods for filtering the request/response.
  • FilterChain: Contains the methods for chaining the filters.
  • FilterConfig: It is an object used by a servlet container to pass information to a filter during initialization.

20. What are the steps to create a filter?

  • Step 1: Create a class that implements the filter interface.
  • Step 2: Implement the doFilter method with the pre/post processing logic.
  • Step 3: Invoke the doFilter method of the FilterChain object.
  • Step 4: Register the filter with the appropriate servlets.

21. What is doFilter method?

public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws ServletException, IOException

This method is executed every time when a servlet (or) JSP associated with this filter is invoked. This contains the filtering or pre and post processing logic.

Method Arguments:
  • ServletRequest: Request object of the incoming request to be intercepted and processed.
  • ServletResponse: Response object of the outgoing response to be intercepted and processed.
  • FilterChain: The filter chain object on which the doFilter method of the FilterChain interface can be called.
22. What is FilterChain interface?

Multiple filters can be chained and invoked one by one this is achieved using the FilterChain interface. Filter uses the FilterChain to invoke the next filter in the chain or if the calling filter is the last filter in the chain it will invoke the resource at the end of the chain. FilterChain contains only one method, void doFilter(ServletRequest request,ServletResponse response).

23. Why do we override doFilter method?

It is overridden to perform one or more of the following tasks:

  • Transform the incoming request.
  • Transform the response before being sent to the client.
  • It invokes the doFilter method of the FilterChain interface.

24. What are the two elements used for declaring filters in web.xml file?

Web.xml uses two elements for declaring filters,

  • Filter - Registers a filtering object with the system.
  • Filter-mapping - Specifies the URLs to which the filtering object applies.

25. What is filter chaining?

Filter chaining is the process of applying more than one filter to a servlet.

26. How is filter chaining configured?

This is done by configuring more than one filter mapping for a servlet in the deployment descriptor file. The filters are invoked in the order they are declared in the deployment descriptor file.

27. What is a web application?

Web application is a collection of components assembled to provide services over the web for users to consume the service provided. Example: online train ticket reservation, internet banking.

28. How are web application accessed?

Web applications are accessed over the web using URL address. URL stands for Uniform Resource Locator which is a unique identifier available to locate a particular service.

29. How HTTP works?

HTTP stands for Hypertext Transfer Protocol. The following below steps explains about working:

  • Clients opens connection.
  • Clients sends HTTP request.
  • Server sends HTTP response.
  • Client closes connection.

30. Why HTTP is called stateless protocol?

Since the connection is open and closed for each HTTP request, the state is not maintained across HTTP requests. Hence HTTP is called “Stateless Protocol”.

31. Where do web application live?

Web application are deployed and managed in web or application server.

32. What is the difference between web and application server?

Web server is a software which provides services to host web applications which can be accessed via HTTP protocol. Example: Application built using servlet/JSP only. Application server or Java EE server is a software which supports application built over HTTP and other protocols such as IIOP,RMI,JMS. It also provides services to manage application built using JDBC transaction, JNDI tree, EJB, LDAP, JMS etc.

33. How are web application deployed?

A web application to be deployed in web/application server it needs to be packaged and deployed in a specific format which can be recognized by the servers. The packaging format is web archive format(war) used for packaging web application containing servlets, JSP,HTML,image files or other web components.

34. How MVC works?

  • Step 1: The controller servlet handles the user’s request.
  • Step 2: The controller servlet then invokes the model and performs the business logic or data retrieval.
  • Step 3: The model returns back the data (response) back to the controller.
  • Step 4: The controller then transfers the data to the view.
  • Step 5: The view renders the data in the appropriate format requested by the client.

35. What are the benefits of MVC?

  • Clear separation of layers, modular and easy to maintain. Example: The model holds business logic or data manipulation logic and view holds the presentation logic. System is modular and easy to maintain as developer know which logic is present in which layer.
  • Supports parallel development so reduces development time. Example: The view and model can be developed by different teams and finally integrated. This reduces development time to market.
  • Flexible for future enhancements. Example: Any changes done like database upgradation or change in business logic it is enough if the model is changed without changing the view or controller.

36. What are the features of servlets?

  • Security: A Web container provides a runtime environment for executing a servlet. Servlets inherit the security feature provided by the web container. This allows developers to focus on the servlet functionality and leave the security issues to the Web container to handle.
  • Session management: It is the mechanism of tracking the state of a user across multiple requests. A session maintains the client identity and state across multiple requests.
  • Instance persistence: Servlets help to enhance the performance of the server by preventing frequent disk access. For example, if a customer logs on to an online banking site, the customer can perform activities, such as checking for the balance or applying for a loan. The account number of the customer will be validated at every stage from the database. Instead of every time checking the account number against the database, servlets retain the account number in the memory till the user logs out of the Web site.
  • It is platform and server independent.

37. What is the difference between HTTP Get vs HTTP Post?

HTTP Get:

  • 1. User entered information is appended in a URL string.
  • 2. It can send only a limited amount of data.
  • 3. The browser caches the data.

HTTP Post:

  • 1. User entered information is send as data as a part of the message body not appended to URL.
  • 2. It can send any amount of data.
  • 3. The data’s are not cached.

38. What is get method usage?

If the processing of a form is idempotent (that is it has no side effect on the state of the database), then the form method should be GET. Many database searches have no side-effects and make ideal applications of query forms. GET method can only populate 255 characters.


39. What is post method usage?

One should normally use METHOD=POST if and only if the form submission may cause changes. There are some situations where one may consider using METHOD=POST even for pure queries too.
If the form data would contain non-ASCII characters, then METHOD=GET is inapplicable in principle, although it may work in practice.

Thus, for a query where the keywords might contain such as accented letters, you have to select among two evils: using METHOD=GET against the rules which restrict the character repertoire to ASCII within it, or using METHOD=POST against the rules which says that it should not be used when the processing is idempotent. The former alternative is probably more dangerous.

40. What is Unavailable exception in servlet API?
It is thrown when a particular servlet is temporarily or permanently not available. For example, if a servlet is not correctly configured , or resource it depends on is not available.
41. What is a status code and what are the categories of status codes?
A status code is the code that the application server sends to the client about the success or failure of a client request. Status codes are grouped into following five categories:
  • Information: Represents messages about the receipt of a request and that the application server is processing the request.
  • Success: Represents a success message, which indicates that the request is successful.
  • Redirection: It indicates that the request is redirected to another page for processing and service.
  • Client error: It indicates that the request has some error and cannot be serviced.
  • Server error: It indicates that the server is unable to fulfill the client request.
42. How to send error message to client?
Error message can be send to client by using methods:
public void sendError(int status_code)
or
public void sendError(int status_code, String message)

Status_code describes the type of error occurred, message describes the error and sends the error response to the client.

43. What will happen if sendError method is called after a response is committed?

if sendError method is called after a response is committed, it will throw an IllegalStateException.

44. How to set the status information about a servlet?

Status information can be set by using methods:

public void setStatus(int status_code)
or
public void setStatus(int status_code, String message)

Status_code represents the status code, message describes the status of the servlet.

45. What are the scope of servlet objects?

There are three scope objects:

  • Web Context (ServletContext) – Accessible from web components within a web context.
  • Session – Accessible from web components handling a request that belongs to the session.
  • Request – Accessible from web components handling the request.

46. What is the format of URL specification?

Format of URL Specification: ProtocolName:IPAddress:PortNumber//WebContextRoot/WebResourceName
Example: http://localhost:8080//WelcomeApplication/WelcomeServlet

47. Explain HTTP request briefly?

An HTTP request has three parts:

  • A request line
  • One or more request headers
  • A message

A request line looks like: GET /WelcomeProject/Home.html HTTP/1.1

  • 1st token is the name of the HTTP method, which is GET in this case.
  • 2nd token is the URI, that gives information about the location of the resource to be gotten.
  • 3rd token is the version of HTTP to be used.

48. Explain HTTP response briefly?

An HTTP response has three parts:

  • A response line
  • One or more response headers
  • A message

A response line looks like: HTTP/1.1 200 OK

  • 1st token is the HTTP version.
  • 2nd token is one of the many predefined status codes. 
  • 3rd token is an English description of the status code.

49. What are the tasks performed by web container when a request comes for a servlet?

Tasks performed by web container are:

  • It loads the servlet class.
  • It instantiates the servlet.
  • It initializes the servlet instance.
  • It passes request to the servlet instance.
  • Finally it sends response to the client.

50. What are the features of CGI?

  • CGI is developed in C, C++, VB and Perl language.
  • Resource intensive and inefficient.
  • It is difficult to maintain, non-scalable and non-manageable.
  • It is application and platform specific.

51. What are the differences between sendRedirect and forward method?

sendRedirect:

  • It is a method of HTTPServletResponse interface.
  • It sends a redirect response back to the client’s browser. The browser will normally interpret this response by initiating a new request to the redirect URL given in the response.
  • Because a new request is being submitted all previous stored in the request will be unavailable.
  • This method is useful for redirecting to pages on other servers and domains.
  • A browser reload of the second URL will not repeat the original request, but will rather fetch the second URL. The back and forward button will work.
  • Redirect is always slower than a forward, since it requires a second browser request.

Forward:

  • It is a method of RequestDispatcher interface.
  • It does not involve the client’s browser. It just takes browser’s current request, and hands it off to another servlet/JSP than they originally called.
  • Forward is performed internally by the servlet.
  • This method is useful when communicating between server resources.
  • Browser is completely unaware that it has taken place, so its original URL remains intact. So, back and forward button of web browser will not work.
  • No network round trip is required to the server, so it is faster.

52. What is a web component?

It is a software entity that runs on a web server, providing with the capabilities needed for dynamically handling client requests and generating web presentation content.

53. What is a web server?

A computer program responsible for accepting HTTP requests and serving them HTTP responses along with data, which usually are web pages such as HTML pages. They are repository of web pages.

54. What are the features of web server?

Features of web server:

  • Web server program works by accepting HTTP requests from the client, and providing an HTTP response to the client.
  • It is a host for all server side scripting like servlet,JSP,ASP,CGI etc.

55. What is an application server?

An application server is a software engine that delivers applications to clients. Moreover, an application server handles most of the business logic and data access of the application.

56. What are the features of application server?

Features of application server:

  • Application servers enable applications to intercommunicate with dependent applications, like web servers, database management systems and chart programs.
  • Portals are common application server mechanism by which a single point of entry is provided to multiple devices.
  • EJB’s are hosted in an application server.

57. What is the difference between GenericServlet and HTTPServlet class?

  • GenericServletIt is used to code generic , protocol independent servlets. It is used as the basis for protocol specific subclasses.
  • HTTPServletHTTPServlet class operates over the HTTP protocol by providing methods such as doGet and doPost for handling HTTP specific services.

58. What are the tasks performed by doGet and doPost method?

  • Extracts client side information from HTTP request.
  • Sets and gets attributes to/from scope objects.
  • Performs some business logic or access database.
  • Forwards the request to other web components such as Servlets or JSP.
  • Populates HTTP response message and sent it to client.

59. What is doHead and doPut method?

doHead() method: It handles requests sent using the http head method. It returns the response header which contains Content-Type, Content-Length, Last-Modified etc. Head method is used to find whether a requested resource exists.
doPut() method: It handles requests sent using http put method. It allows a client to store information on the server.

60. What is the use of setContentType method?
setContentType() method is used to intimate the browser that which type of content is coming as response, depending upon the contentType browser treats with the response.
61. Suppose if we want a greek language support in application then which method we should use getWriter or getOutputStream method and why?

Instead of using PrintWriter out = response.getWriter(), you can also use ServletOutputStream out = response.getOutputStream(), but Unicode support will be not available. For Example, if you want a greek language support in your application then you need to use getWriter instead of getOutputStream.

62. How to get the servlet context object?

we can get ServletContext object by following process:

ServletContext context = getServletConfig().getServletContext();

Or

ServletContext context;
Public void init(ServletConfig cfg)
{
Context=cfg.getServletContext();
}

63. Explain the working of servlet?

  • Reading data submitted by the client – The first step performed by the servlet is to read any data sent by the client. This is usually html form data.
  • The servlet need to check the HTTP information embedded in the user’s request. 
  • As part of the process of responding to the client’s request, the servlet may have to access business tier components such as EJB’s, or RDBMS.
  • When all the necessary processing is done, the servlet formats the request results – usually in an HTML or XML format, although other formats can be sent, such as binary code or GIF images.
  • The servlet has to set the appropriate HTTP response parameters – this includes the telling the browser what type of document is being returned.
  • The final step in the process is for the servlet to return the response to the client.

64. When the servlet object is first created?

Depending on how you register your servlet with the web server, it can be created either when a client first references a URL that corresponds to the servlet, or when the web server is first started.

65. What operations do we basically perform in servlet’s destroy method?

cleanup operations such as closing database connections, writing cookie lists, and halting background threads before it is destroyed.

66. When a web server unloads a servlet instance?

A server may unload a servlet instance if its running incorrectly, or if the servlet has been idle for some time.

67. What is the main task of init() method?

The main task of the init() method is to allow the servlet to access deployment – specific initialization parameters, such as database settings.

68. What is the use of getParameter method of http servlet request object?

getParameter() method is used to read data from a request object as String.

69. What are the main responsibilities of Servlet, JSP and EJB?

JSP’S typically provide presentation functionality for users. EJB components are responsible for defining application’s business model and providing clients with access to database information. Servlets act as a intermediaries between JSP’s and EJB’s or databases.

70. How client state is maintained using HTTPSession interface?

It maintains client state by using servlet getAttribute() and setAttribute() methods of session scope.

71. Why the servlet are packaged in a standard packaging structure?

J2EE defines a standard packaging structure to package a servlet into a J2EE application to make it portable across different application servers. A standard packaging structure will allow application servers to easily locate and load application files from the standard directory structure.

72. On which existing session-tracking technologies do you think the HTTPSession interface is built?

The HTTPSession interface is founded on cookie and URL rewriting technology. It hides the complexity of having to manipulate cookies or information appended to URL’s from the servlet developer. This work is automatically done by the web container, which generates HTTPSession
objects as required.

73. HTTPSession interface handles the routine work of cookies, such as associating hash tables of session information with client requests. What other tasks do you think are carried out by the HTTPSession interface?

The HTTPSession interface generates the unique session IDs, identifies and extracts the particular cookie that stores the session ID, and sets a suitable expiration time for a session.

74. What are the functions of the Cookie class?

Creation of cookies, including long lived cookies, and setting duration for the lifetime of a cookie are functions of the cookie class.

75. How servlet filter chain works?

  • Multiple filters can be chained. Order is dictated by the order of <filter> elements in the deployment descriptor. 
  • The first filter of the filter chain is invoked by the container via doFilter(ServletRequest req, ServletResponse res, FilterChain chain) method. The filter then perform whatever filter logic and then call the next filter in the chain by calling chain.doFilter(…) method.
  • The last filter’s call to chain.doFilter() ends up calling service() method of the Servlet.

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
Servlet Interview Questions and Answers
EJB Interview Questions and Answers
Spring Interview Questions and Answers