Understand Servlets as a core component of J2EE for generating dynamic web content. Learn the Servlet lifecycle, API, session management, and how to build and deploy a structured web application using Servlets. Apply concepts like MVC, session tracking, and request dispatching in practical scenarios.
Stages:
init(ServletConfig)
method to initialize the Servlet.
service(ServletRequest, ServletResponse)
method for each client request.
HttpServlet
dispatches to doGet()
, doPost()
, etc., based on the HTTP method.destroy()
method when removing the Servlet (e.g., during undeployment).
Key Methods:
init(ServletConfig)
: Called once during initialization.service(ServletRequest, ServletResponse)
: Handles client requests.destroy()
: Called once before Servlet is removed.Example:
public class MyServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("Servlet Initialized");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("Hello from Servlet!");
}
@Override
public void destroy() {
System.out.println("Servlet Destroyed");
}
}
javax.servlet
and javax.servlet.http
packages.
Servlet
: Defines the contract for Servlets (init, service, destroy).HttpServlet
: Extends GenericServlet
for HTTP-specific functionality.HttpServletRequest
: Provides methods to access request data (e.g., getParameter()
, getHeader()
).HttpServletResponse
: Provides methods to send responses (e.g., getWriter()
, sendRedirect()
).ServletConfig
: Configuration data for a Servlet (e.g., init parameters).ServletContext
: Application-wide data and resources.Using web.xml
:
Map Servlets to URLs in the deployment descriptor.
Example:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
</servlet-mapping>
Using Annotations:
Modern approach with @WebServlet
annotation.
Example:
@WebServlet("/myServlet")
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("Hello, World!");
}
}
Deployment Process:
webapps/
directory).