What is a Java Servlet?
Servlets are Java programs that run on a web server. They handle requests from clients (typically browsers), process them, and return a response, often in the form of dynamic web pages. Servlets are a key component of Java EE for building web applications.
What are some important characteristics of Servlet?
- It is server-side technology used to develop web applications.
- Provides a powerful API including classes and interfaces for request and response handling.
- Platform-independent as it is written in Java.
- Highly scalable — each request is handled in a separate thread.
- Leverages Java’s features like garbage collection and exception handling, reducing memory leaks.
What are the types of Servlet in Java?
- GenericServlet (protocol-independent)
- HttpServlet (specific to HTTP protocol)
What is a Servlet container?
A Servlet container (like Apache Tomcat) provides the runtime environment for Servlets. It manages the servlet lifecycle, handles request and response, and performs mapping between URLs and servlets.
What is the hierarchy of the servlet ecosystem?
The hierarchy is as follows:
- Servlet (interface)
- GenericServlet (implements Servlet and ServletConfig)
- HttpServlet (extends GenericServlet and adds HTTP-specific methods like doGet() and doPost())
What is the servlet context?
ServletContext is an interface that provides a communication link between the servlet and the web container. It allows the servlet to:
- Access initialization parameters from
web.xml
- Share data between different servlets
- Access application-wide attributes using setAttribute(), getAttribute(), and removeAttribute()
What is DispatcherServlet?
DispatcherServlet is a core component in Spring MVC framework. It acts as a front controller, handling all incoming requests and routing them to appropriate controllers, views, and exception handlers as configured in Spring.
How to call a servlet from JSP?
You can call a servlet from a JSP page using:
<jsp:include page="/servletURL" />
Ensure the servlet URL matches the <url-pattern> specified in web.xml
or with annotations.
Difference between POST and GET method in servlet?
- GET: Used to request data; parameters appear in the URL; handled by
doGet()
. - POST: Used to send data (e.g., form submission); data is sent in the body; handled by
doPost()
.
How to pass value from one Servlet to another Servlet?
- Using
RequestDispatcher.forward()
orinclude()
- Using query strings or hidden fields
- Using session or application context attributes
Differentiate between SendRedirect and RequestDispatcher in servlet?
SendRedirect | RequestDispatcher |
---|---|
Client-side redirection using a new request | Server-side forwarding or inclusion within the same request |
Visible URL change | URL remains the same |
Slower due to extra HTTP round trip | Faster since no round trip |
What is the use of listener in servlet?
Servlet listeners respond to lifecycle events like context initialization, session creation, or attribute changes. Example: ServletContextListener
for context startup/shutdown events.
What is MIME type in servlet?
MIME (Multipurpose Internet Mail Extensions) type indicates the type of content sent to the client. For example, text/html
, application/json
. You can set MIME type using:
response.setContentType("text/html");
How to run servlet program in Tomcat?
- Create your servlet and compile it.
- Place the compiled class in
WEB-INF/classes
. - Define servlet and mapping in
web.xml
or use annotations. - Deploy your project in
webapps
folder of Tomcat. - Start Tomcat and access servlet via browser.
What is a Generic servlet?
GenericServlet
is a protocol-independent abstract class that implements Servlet
and ServletConfig
. It simplifies servlet development by providing default implementations and requires overriding only the service()
method.
What is servlet life cycle?
- Loading: The class is loaded by the container.
- Instantiation: The servlet object is created.
- Initialization:
init()
is called once. - Request Handling:
service()
method handles each request. - Destruction:
destroy()
is called before removal.
Differentiate between HttpServlet and GenericServlet?
HttpServlet | GenericServlet |
---|---|
Protocol-specific (HTTP) | Protocol-independent |
Includes doGet() , doPost() , etc. |
Only has service() method to override |
Subclass of GenericServlet | Implements Servlet and ServletConfig |
When and how is the destroy method called in Servlet?
The destroy()
method is called by the servlet container before the servlet is removed from service, such as during shutdown or redeployment. It allows resource cleanup.
Which method of servlet interface is used for handling request?
The service()
method is used for handling client requests. In HttpServlet
, it delegates to doGet()
, doPost()
, etc., depending on the request method.
What is init() method in Servlet?
init()
is called once when the servlet is first loaded. It’s used for initializing resources. This method is not called again during the servlet’s lifecycle.
What are the advantages of using Servlets over CGI?
Servlets offer better performance and scalability than CGI due to their multithreaded nature. In CGI, each request spawns a new process, which is resource-intensive. Servlets, on the other hand, handle multiple requests using threads, which are more efficient. Additionally, Servlets benefit from Java’s portability, security, and powerful APIs.
How do Servlets handle session management?
Servlets manage sessions using:
- Cookies – Store session ID on the client.
- HttpSession API – Provides methods like
getSession()
,setAttribute()
, andinvalidate()
. - URL Rewriting – Appends session ID to the URL.
- Hidden Form Fields – Transfers session data through forms.
Can you explain the role of web.xml
in a Servlet application?
web.xml
is the deployment descriptor for a servlet-based application. It is used to:
- Define servlet mappings
- Set initialization parameters
- Configure listeners, filters, and error pages
- Define welcome files and security constraints
What is the difference between doGet() and doPost()
methods?
- doGet() is used when data is sent in the URL and is visible in the address bar.
- doPost() is used when data is sent in the body of the request, making it more secure and suitable for sensitive information.
- doPost() is preferred for sending large amounts of data.
What are Filters in Servlet?
Filters are objects used to intercept requests and responses to perform preprocessing or postprocessing tasks. They are used for tasks like:
- Logging
- Authentication
- Compression
- Input validation
They implement the javax.servlet.Filter interface.
What are annotations in Servlets?
Annotations in Servlets (introduced in Servlet 3.0) allow developers to configure servlets without using web.xml
. Example:
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
// ...
}
What are some common Servlet exceptions?
- ServletException – A general exception thrown by a servlet when it encounters difficulty.
- IOException – Thrown when there is an input or output failure.