J A V A W E B D E V E L O P M E N T · J A K A R T A E E Module 2 Servlets · JSP · JSTL Building dynamic, server - side web applications — the request/response engine, session state, and view - layer tags. HttpServlet Life Cycle Sessions Cookies JSP JSTL Core Developer Track · Rich Code Examples A G E N D A Module Roadmap Module 2 · Servlets, JSP & JSTL 01 Introduction to Servlets 02 Servlet Life Cycle 03 doGet() & doPost() 04 RequestDispatcher 05 sendRedirect() 06 Dispatcher vs Redirect 07 Session Management 08 Cookies 09 Servlet Annotations 10 Introduction to JSP 11 JSP Implicit Objects 12 JSTL Core Tags P A R T 1 Servlet Fundamentals The server - side engine: how container - managed Java classes receive HTTP requests, run a defined life cycle, and build dynamic responses. Life Cycle Requests Responses Dispatch Module 2 · Servlets, JSP & JSTL F O U N D A T I O N S Introduction to Servlets Module 2 · Servlets, JSP & JSTL What is a Servlet? A Java class that runs inside a web container and handles HTTP requests, generating dynamic responses. – Extends javax/jakarta.servlet.http.HttpServlet – Managed entirely by the container (Tomcat, Jetty) – One instance serves many requests via threads Why Servlets over CGI? – Persistent, in - process — no per - request process fork – Portable across servers and operating systems – Full access to the Java API and connection pools – Robust, scalable and secure by design HelloServlet.java import jakarta.servlet.http.*; @WebServlet ( "/hello" ) public class Hello extends HttpServlet { protected void doGet ( HttpServletRequest req, HttpServletResponse res) throws IOException { res. setContentType ( "text/html" ); res. getWriter (). println ( "Hello!" ); } } S E R V L E T A R C H I T E C T U R E How a Request Flows Module 2 · Servlets, JSP & JSTL Client Browser sends HTTP request Web Server Receives request on a port Container Maps URL, manages threads & lifecycle Servlet service() → doGet / doPost logic Response Dynamic HTML back to client Key idea: The container owns the servlet instance — it creates it once, dispatches every request to it on a worker thread, and destroys it at shutdown. // Because one instance is shared across threads, keep servlets stateless — avoid mutable instance fields. C O N T A I N E R - M A N A G E D Servlet Life Cycle Module 2 · Servlets, JSP & JSTL 1 init() Called once when the servlet is first loaded. Perform one - time setup — DB pools, config. 2 service() Invoked for every request. Dispatches to doGet(), doPost(), etc. Runs on many threads. 3 destroy() Called once before the servlet is unloaded. Release resources and clean up. MyServlet.java public class MyServlet extends HttpServlet { public void init () throws ServletException { // load config, open resources } protected void service (HttpServletRequest r, HttpServletResponse s) { // per - request work (auto - dispatch) } public void destroy () { // release resources } } H A N D L I N G H T T P M E T H O D S doGet() and doPost() Module 2 · Servlets, JSP & JSTL doGet() – Handles HTTP GET requests – Parameters appear in the URL query string – Idempotent & bookmarkable – Size - limited; visible in history – Use for reads / navigation doPost() – Handles HTTP POST requests – Parameters travel in the request body – Not cached or bookmarked – No practical size limit – Use for writes / sensitive data LoginServlet.java @WebServlet ( "/login" ) public class Login extends HttpServlet { protected void doGet (req, res) { // show the login form } protected void doPost (req, res) { String u = req. getParameter ( "user" ); String p = req. getParameter ( "pass" ); // authenticate & respond } } T H E R E Q U E S T O B J E C T Reading Request Data Module 2 · Servlets, JSP & JSTL HttpServletRequest methods – getParameter(name) — single form/query value – getParameterValues(name) — checkboxes, multi – getParameterMap() — every parameter at once – getHeader(name) — a request header – getMethod() / getRequestURI() — routing info – getCookies() / getSession() — client state – getReader() / getInputStream() — raw body – getAttribute(name) — forwarded attributes FormServlet.java protected void doPost (req, res) { // single value String email = req. getParameter ( "email" ); // multi - valued (checkboxes) String[] roles = req. getParameterValues ( "role" ); // iterate all params req. getParameterMap (). forEach ( (k, v) - > log(k, v)); } H T T P S E R V L E T R E S P O N S E The Response Object Module 2 · Servlets, JSP & JSTL Shaping the reply – setContentType("text/html") — MIME type – setCharacterEncoding("UTF - 8") – getWriter() — character output stream – getOutputStream() — binary output – setHeader / addHeader — response headers – setStatus(code) — e.g. 200, 201 – sendError(code, msg) — error responses – addCookie(c) / sendRedirect(url) ApiServlet.java protected void doGet (req, res) { res. setContentType ( "application/json" ); res. setStatus (HttpServletResponse. SC_OK ); res. setHeader ( "Cache - Control" , "no - store" ); PrintWriter out = res. getWriter (); out. println ( "{ \ "status \ ": \ "ok \ " }" ); } F O R W A R D ( ) & I N C L U D E ( ) RequestDispatcher Module 2 · Servlets, JSP & JSTL forward() Passes control to another resource on the server. The original response is discarded — the target produces the full output. – Same request & response objects – Client sees one URL — no browser round - trip – Common for controller → JSP view include() Runs another resource and merges its output into the current response, then returns control back to the caller. – Caller keeps control after the include – Ideal for headers, footers, reusable fragments Dispatcher.java // Forward to a JSP view (server - side) RequestDispatcher rd = req. getRequestDispatcher ( "/view.jsp" ); rd. forward (req, res); // Include a reusable fragment req. getRequestDispatcher ( "/header.jsp" ) include (req, res); // Attributes survive a forward req. setAttribute ( "user" , u); C L I E N T - S I D E R E D I R E C T sendRedirect() Module 2 · Servlets, JSP & JSTL How it works response.sendRedirect(url) tells the browser to make a brand - new request to a different URL (HTTP 302). – A full client - to - server round - trip occurs – The URL in the browser changes – Request attributes are lost — new request – Can target external sites (any URL) When to use it – After a successful POST (Post/Redirect/Get) – Redirecting to another application or domain – Preventing duplicate form submissions OrderServlet.java protected void doPost (req, res) { // ... process the order ... // relative to the app context res. sendRedirect ( req. getContextPath () + "/success.jsp" ); // external redirect res. sendRedirect ( "https://site.com" ); } K E Y D I F F E R E N C E S Dispatcher vs. sendRedirect Module 2 · Servlets, JSP & JSTL Aspect RequestDispatcher.forward() response.sendRedirect() Runs on Server side Client (browser) side Round - trips One request Two requests (302 + new) Browser URL Unchanged Changes to target Request data Preserved (same request) Lost (new request) Target scope Within same application Any URL, incl. external Speed Faster (no round - trip) Slower (extra trip) Defined in RequestDispatcher HttpServletResponse Rule of thumb: forward() keeps everything on the server for internal views; sendRedirect() when the browser must go somewhere ne w. C O N F I G U R A T I O N I N C O D E Servlet Annotations Module 2 · Servlets, JSP & JSTL @WebServlet Maps a servlet to one or more URL patterns @WebFilter Registers a filter for request/response interception @WebListener Declares a lifecycle event listener @WebInitParam Supplies initialization parameters @MultipartConfig Enables file - upload (multipart) handling ReportServlet.java // Since Servlet 3.0, annotations replace // most web.xml <servlet> declarations. @WebServlet ( urlPatterns = { "/report" , "/r" }, initParams = @WebInitParam ( name = "fmt" , value = "pdf" )) public class ReportServlet extends HttpServlet { // getInitParameter("fmt") - > "pdf" } // Equivalent to a verbose web.xml entry C R O S S - C U T T I N G C O N C E R N S Filters & Listeners Module 2 · Servlets, JSP & JSTL Filters Intercept requests/responses before and after a servlet — chained via FilterChain. – Declared with @WebFilter – Implement doFilter(req, res, chain) – Great for auth, logging, compression, CORS Listeners React to lifecycle events in the app, session, or request scope. – Declared with @WebListener – ServletContextListener — app start/stop – HttpSessionListener — session create/destroy AuthFilter.java @WebFilter ( "/secure/*" ) public class AuthFilter implements Filter { public void doFilter (req, res, FilterChain chain) { if (loggedIn(req)) { chain. doFilter (req, res); // pass } else { ((HttpServletResponse) res) sendRedirect ( "/login" ); } } } P A R T 2 Session & State Management HTTP is stateless — every request stands alone. These techniques tie a series of requests to one user and carry data between them. HttpSession Cookies URL Rewriting Hidden Fields Module 2 · Servlets, JSP & JSTL T R A C K I N G S T A T E O V E R H T T P Session Management Module 2 · Servlets, JSP & JSTL HTTP is stateless — each request is independent. Session management links a series of requests to one user. Cookies Small key – value pairs stored by the browser and returned on each request. URL Rewriting Session id appended to every URL — works when cookies are disabled. Hidden Form Fields State carried in <input type="hidden"> across form posts. HttpSession Server - side object keyed by JSESSIONID — the standard approach. session - basics.java // The container tracks the session with a // JSESSIONID cookie (or ;jsessionid= in URL) HttpSession session = req. getSession (); session. setAttribute ( "cart" , cart); session. setMaxInactiveInterval ( 1800 ); T H E S T A N D A R D A P I HttpSession in Practice Module 2 · Servlets, JSP & JSTL Core methods – getSession(true) — return current or create new – getSession(false) — return null if none exists – setAttribute(name, value) — store state – getAttribute(name) — retrieve state – removeAttribute(name) — drop one value – getId() — the unique session identifier – invalidate() — end the session (logout) – setMaxInactiveInterval(sec) — idle timeout SessionFlow.java // --- Login: create & populate --- HttpSession s = req. getSession (); s. setAttribute ( "user" , account); // --- Later request: read back --- User u = (User) s. getAttribute ( "user" ); if (u == null ) res. sendRedirect ( "/login" ); // --- Logout: destroy --- req. getSession (). invalidate (); C L I E N T - S I D E K E Y – V A L U E S T O R A G E Cookies Module 2 · Servlets, JSP & JSTL Essentials A Cookie is a small named value the server sends via Set - Cookie; the browser returns it on every subsequent request. – Created with new Cookie(name, value) – Added to the response via res.addCookie() – Read from req.getCookies() (array) – setMaxAge(sec): persistent vs session cookie – setHttpOnly / setSecure for safety – Store only small, non - sensitive values CookieServlet.java // Create and send a cookie Cookie c = new Cookie( "theme" , "dark" ); c. setMaxAge ( 60 * 60 * 24 ); // 1 day c. setHttpOnly ( true ); res. addCookie (c); // Read cookies back Cookie[] all = req. getCookies (); if (all != null ) for (Cookie ck : all) { if ( "theme" equals (ck. getName ())) theme = ck. getValue (); } C O O K I E L E S S T R A C K I N G URL Rewriting & Hidden Fields Module 2 · Servlets, JSP & JSTL URL Rewriting Append the session id to every link so tracking survives when cookies are disabled. – response.encodeURL(url) adds ;jsessionid – Encode every link the app emits – Fallback the container uses automatically Hidden Form Fields Carry small pieces of state across form submissions inside the page itself. – <input type="hidden"> travels with the POST – No server storage; visible in page source – Best for short, non - sensitive multi - step data tracking.jsp // --- URL rewriting --- String url = res. encodeURL ( "/cart?item=42" ); out. println ( "<a href='" + url + "'>Cart</a>" ); <% -- --- Hidden field (JSP) --- -- %> <form method = "post" action = "/step2" > <input type = "hidden" name = "step" value = "1" /> <button>Next</button> </form> P A R T 3 JSP & JSTL Move presentation out of Java code: JSP pages compile into servlets, expose implicit objects, and pair with Expression Language and the JSTL tag library. JSP Implicit Objects EL JSTL Core Module 2 · Servlets, JSP & JSTL