Introduction to Servlets
Java EE Web Application
Development
What is a Servlet?
• - A Java class that handles HTTP requests
• - Runs on the server side (Java EE container)
• - Generates dynamic responses (HTML, JSON,
etc.)
• - Works with JSP in modern web apps
Servlet vs JSP
• - Servlet: Java code for controlling logic
• - JSP: Presentation layer (HTML with Java)
• - Servlets are better for business logic
• - JSPs are easier for UI and displaying data
Servlet Lifecycle
• 1. init() - Called once when the servlet is
created
• 2. service() - Called for each request
• 3. destroy() - Called once when the servlet is
destroyed
Basic Servlet Example
• @WebServlet("/hello")
• public class HelloServlet extends HttpServlet {
• protected void doGet(HttpServletRequest
req, HttpServletResponse res) throws
IOException {
• [Link]().println("Hello from Servlet");
• }
• }
Request Flow: JSP → Servlet → JSP
• - User submits form from JSP
• - Servlet receives request with parameters
• - Servlet sets attributes and forwards to result
JSP
• - JSP reads attributes and displays result