Servlets Interview Questions and Answers
Freshers / Beginner level questions & answers
Ques 1. What is Servlet?
A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request/response paradigm.
Ques 2. Why is Servlet so popular?
Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
Ques 3. What is servlet container?
The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.
Ques 4. When a client request is sent to the servlet container, how does the container choose which servlet to invoke?
The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
Ques 5. Difference between GET and POST
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.
Ques 6. What is session?
The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.
Ques 7. What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.
Ques 8. What is servlet context ?
The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial).
Ques 9. Which interface must be implemented by all servlets?
Servlet interface.
Ques 10. Explain the life cycle of Servlet.
Ques 11. When is the servlet instance created in the life cycle of servlet? What is the importance of configuring a servlet?
An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.
Ques 12. What are the two important APIs in Servlets?
Two important packages are required to build servlet "javax.servlet" and "javax.servlet.http". They form the core of Servlet API. Servlets are not part of core Java but are standard extensions provided by Tomcat.
Ques 13. What's the use of ServletContext?
ServletContext Interface: It gives information about the environment. It represents a Servlet's view of the Web Application.Using this interface servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an application scope for binding objects.
Ques 14. What's the difference between GenericServlet and HttpServlet?
HttpServlet class extends GenericServlet class which is an abstract class to provide HTTP protocol-specific functionalities. Most of the java application developers extend HttpServlet class as it provides more HTTP protocol-specific functionalities. You can see in HttpServlet class doGet (), doPOst () methods which are more targeted towards HTTP protocol specific functionalities. For instance we can inherit from GenericServlet class to make something like MobileServlet. So GenericServlet class should be used when we want to write protocol specific implementation which is not available. But when we know we are making an internet application where HTTP is the major protocol its better to use HttpServlet.
Ques 15. What’s the architecture of a Servlet package?
At the top of all is the main servlet interface which is implemented by the generic servlet. But generic servlet does not provide implementation specific to any protocol. HTTP servlet further inherits from the generic servlet and provides HTTP implementation like "Get" and "Post". Finally comes our custom servlet which inherits from HTTP Servlet.
Ques 16. Why is HTTP protocol called as a stateless protocol?
A protocol is stateless if it can remember difference between one client request and the other. HTTP is a stateless protocol because each request is executed independently without any knowledge of the requests that came before it.
Ques 17. What are the different ways we can maintain state between requests?
Following are the different ways of maintaining state’s between stateless requests:-
>> URL rewriting
>> Cookies
>> Hidden fields
>> Sessions
Intermediate / 1 to 5 years experienced level questions & answers
Ques 18. If a servlet is not properly initialized, what exception may be thrown?
During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.
Ques 19. Given the request path below, which are context path, servlet path and path info?
/bookstore/education/index.html
context path: /bookstore
servlet path: /education
path info: /index.html
Ques 20. What is filter? Can filter be used as request or response?
A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.
Ques 21. When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?
Ques 22. What is new in ServletRequest interface ? (Servlet 2.4)
The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()
Ques 23. Request parameter How to find whether a parameter exists in the request object?
1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)
Ques 24. How can I send user authentication information while making URL Connection?
You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
Ques 25. Why don't we write a constructor in a servlet?
Container writes a no argument constructor for our servlet.
Ques 26. When we don't write any constructor for the servlet, how does container create an instance of servlet?
Container creates instance of servlet by calling Class.forName(className).newInstance().
Ques 27. What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext?
>We can give relative URL when we use ServletRequest and not while using ServletContext.
Ques 28. What are advantages of servlets over CGI?
In CGI for every request there is a new process started which is quiet an overhead. In servlets JVM stays running and handles each request using a light weight thread. In CGI if there are 5000 request then 5000 CGI program is loaded in memory while in servlets there are 5000 thread and only one copy of the servlet class.
Ques 29. Can you explain in detail "javax.servlet" package?
Interfaces in javax.servlet :-
Servlet Interface: This interface has the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. Following are the method in Servlet interface :-
String getServletName():- Returns the name of the invoking servlet.
Experienced / Expert level questions & answers
Ques 30. The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to execute.
Ques 31. What mechanisms are used by a Servlet Container to maintain session information?
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information
Ques 32. Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time?
Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet?s service() method to finish.
Ques 33. Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()?
Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.
Ques 34. What is the difference between an application server and a Web server?
Most helpful rated by users:
- What is Servlet?
- Why is Servlet so popular?
- What is servlet container?
- When a client request is sent to the servlet container, how does the container choose which servlet to invoke?
- If a servlet is not properly initialized, what exception may be thrown?