![]() |
VOOZH | about |
Servlet interview questions are mainly asked to test your understanding of Java web application development and how server-side request handling works. These questions focus on the servlet lifecycle, HTTP methods, session handling, and communication between servlets and JSP.
A Servlet is a Java program that runs on a web server and handles client requests dynamically. It is mainly used to build server-side web applications.
A Servlet Container is a part of the web server that manages servlets. It controls servlet lifecycle and provides services like request handling and session management.
The servlet lifecycle defines how a servlet is created, initialized, used, and destroyed by the container.
doGet() and doPost are http request method where doGet() handles GET requests while doPost() handles POST requests. GET is mainly used for fetching data, POST is used for submitting data securely.
| Feature | doGet() | doPost() |
|---|---|---|
| Purpose | Used to retrieve data | Used to send/submit data |
| Data Location | Data goes in URL (query string) | Data goes in request body |
| Security | Less secure (data visible in URL) | More secure (data not shown in URL) |
| Data Limit | Limited (URL length limit) | Can send large data (no URL limit) |
init() is a servlet lifecycle method used to initialize the servlet when it is loaded for the first time by the servlet container. It is called only once during the servletโs life.
Syntax:
public void init() throws ServletException {
// initialization code
}
The service() method is responsible for handling requests and generating responses. It is called every time the client sends a request.
Syntax:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
// request handling code
}
The destroy() method is called when the servlet is removed from the container. It is used to clean up resources.
Syntax:
public void destroy() {
// cleanup code
}
Servlet is used for backend logic while JSP is mainly used for view (presentation). JSP is internally converted into a servlet.
| Feature | Servlet | JSP |
|---|---|---|
| Type | Java class (backend component) | Web page (view layer) |
| Coding Style | More Java code, HTML written inside Java | More HTML, Java used inside JSP |
| Best Used For | Business logic + request handling | UI / presentation (dynamic pages) |
| Compilation | Compiled into .class directly | Converted into a Servlet first, then compiled |
HttpServlet is a class in Servlet API that provides HTTP-specific methods like doGet(), doPost(), doPut(), etc.
GenericServlet is an abstract class that provides a protocol-independent implementation of the Servlet interface.
GenericServlet is protocol independent while HttpServlet is protocol dependent (HTTP only).
| Feature | GenericServlet | HttpServlet |
|---|---|---|
| Protocol Dependency | Protocol-independent | HTTP protocolโspecific |
| Key Method | Implements only service() | Provides doGet(), doPost(), doPut(), etc. |
| Package | jakarta.servlet | jakarta.servlet.http |
| Usage | Rarely used in web apps | Most commonly used for web applications |
A RequestDispatcher is an interface in Servlet API used to forward a request from one servlet/JSP to another resource. It also allows including the output of another resource into the current response.
forward() transfers control completely, while include() adds output of another resource in the same response.
| Feature | forward() | include() |
|---|---|---|
| Control Flow | Current resource stops | Current resource continues |
| Response | Only forwarded resource output is sent | Both outputs are combined |
| URL in Browser | Does not change | Does not change |
| Use Case | Navigation to another page/resource | Reusing common content (header/footer) |
sendRedirect() is a method in Servlet API used to redirect the client to a new URL. It tells the browser to make a new request to another resource (Servlet/JSP/External website).
forward() transfers the same request to another servlet/JSP inside the server without creating a new request and sendRedirect() sends the response back to the browser and asks it to make a new request to a new URL.
| Feature | forward() | sendRedirect() |
|---|---|---|
| Type | Server-side forwarding | Client-side redirection |
| Request | Same request object | New request object |
| URL Change | URL does not change | URL changes in browser |
| External Redirect | Not possible (same server only) | Possible (can go to another site) |
ServletConfig is an interface in Servlet API used to get initialization parameters and configuration details for a specific servlet. It is created by the container and provided to the servlet during init().
ServletContext is an interface in Servlet API that provides application-level information shared by all servlets in a web application. It is created once per application by the container.
A session is a way to store user-specific data on the server so the application can remember the user across multiple requests. It helps maintain state because HTTP is stateless by default.
A session is created in a servlet using the HttpSession object, which is obtained from the request. If a session does not already exist, the container automatically creates a new one.
HttpSession session = request.getSession();
Creates a new session if not present. Session data is stored using:
session.setAttribute()
A Session stores user data on the server-side, while a Cookie stores small data on the client-side (browser). Both are used to maintain user information between multiple requests.
| Feature | Session | Cookie |
|---|---|---|
| Stored In | Server-side | Client-side (Browser) |
| Security | More secure | Less secure (can be modified) |
| Data Size | Large (depends on server) | Small (around 4KB) |
| Lifetime | Ends on timeout/logout | Ends on expiry time set |
A Cookie is a small piece of data stored in the userโs browser that helps the server identify the user across multiple requests. It is commonly used for tracking, login sessions, and remembering user preferences.
Cookie Created using:
Cookie cookie = new Cookie("name","value");
Cookie sent to browser using:
response.addCookie(cookie)
Cookie read using:
request.getCookies()
A cookie is deleted by setting its value as empty and its maximum age to 0, then sending it again to the browser. This tells the browser to remove that cookie.
Set cookie:
cookie.setMaxAge(0);
Add again cookie:
response.addCookie(cookie);
URL Rewriting is a technique used to maintain session tracking by adding the session ID or extra data directly into the URL. It is mainly used when cookies are disabled in the browser.
A hidden form field is an input field in HTML that is not visible to the user but is used to send extra data from client to server along with the form submission.
Servlet Filters are components in Servlet API used to intercept requests and responses before they reach a servlet or after they leave it. They are mainly used for common tasks like logging, authentication, and input validation.
Servlet Listeners are components in Servlet API that listen to events in a web application, like session creation, session destruction, and context loading. They are used to perform tasks automatically when these events occur.
web.xml is the deployment descriptor file used to configure servlets, mappings, filters, listeners, and other settings in a Java web application. It tells the server how to load and run web components.
web.xml is an XML-based configuration file used to define servlets and mappings manually and @WebServlet is an annotation-based approach used to configure servlets directly inside the Java class.
| Feature | web.xml | @WebServlet |
|---|---|---|
| Configuration Type | XML-based (external file) | Annotation-based (inside class) |
| Ease of Use | More lengthy | Simple and faster |
| Changes | Requires editing XML | Just update Java code |
| Best For | Large apps with centralized config | Small/medium apps with clean setup |
Servlet chaining is a process where one servlet passes the request to another servlet to continue processing. It helps multiple servlets work together to generate a final response.
A servlet can get information about the client machine using the HttpServletRequest object. It provides methods to read details like client IP address, browser type, operating system, and request headers.
Client IP address:
request.getRemoteAddr()
Browser and OS details:
request.getHeader("User-Agent")
Client host name:
request.getRemoteHost()
Single-Thread Model in servlets is an old mechanism where the servlet container allows only one request at a time for a servlet instance. It was used to avoid thread-safety issues in servlets.
javax.servlet is a package that provides the core classes and interfaces required to build servlets in Java. It contains the basic servlet APIs like Servlet, ServletRequest, ServletResponse, ServletConfig, and ServletContext.