Advanced Java Essentials – Episode 14: Servlets and Session Management Deep Dive (Updated June 2026) (Updated June 2026)
Here is the thing about Java web development that no tutorial tells you clearly enough: Servlets are the foundation that everything else is built on. Spring MVC, JSF, Jakarta EE Faces, every Java web framework — they all eventually call the Servlet API under the hood. TCS saw 12,000 layoffs in July 2025 while simultaneously accelerating hiring for Java web developers who understand underlying mechanics, not just framework surface. Episode 14 of our Advanced Java series goes deep on Servlets — the lifecycle, request handling, form processing, and the session management techniques that keep users logged in and secure between requests.
- Servlets are Java classes that handle HTTP requests and generate dynamic responses on a web server
- The Servlet lifecycle has three phases: initialization (init), request handling (service), destruction (destroy)
- doGet handles form submissions via URL, doPost handles sensitive data sent in the request body
- Session management tracks user state across stateless HTTP — cookies and HttpSession are the two mechanisms
- Understanding Servlets makes you a far better Spring MVC and Jakarta EE developer
What Is a Servlet? The Foundation of Java Web Applications
A Servlet is a Java class that extends HttpServlet and runs inside a web container (also called a Servlet container or application server). When a browser sends an HTTP request to your Java web application, the container receives it and routes it to the appropriate Servlet based on URL mapping. The Servlet processes the request — reads parameters, interacts with a database, applies business logic — and writes an HTTP response back to the browser. This is the fundamental mechanism that makes Java web applications work, and it predates all modern frameworks. Tomcat, Jetty, and JBoss are all Servlet containers. When you deploy a Spring Boot application with an embedded Tomcat, there is a DispatcherServlet inside handling every request and routing it to your Spring MVC controllers. When you use Jakarta Faces, a FacesServlet handles the request lifecycle. Frameworks abstract the Servlet API, but they do not replace it. A Java web developer who understands Servlet mechanics can debug framework behavior that appears magical to colleagues who only know the framework surface.

The Servlet Lifecycle: init, service, and destroy Explained
The Servlet lifecycle is managed entirely by the container — you implement callbacks, the container calls them at the right time. When the container first needs a Servlet (either at startup if load-on-startup is set, or on first request), it calls init(ServletConfig config). This runs exactly once per Servlet instance and is where you initialize expensive resources — database connections, configuration loading, thread pools. For each incoming request, the container calls service(HttpServletRequest req, HttpServletResponse res). HttpServlet's default service() implementation reads the HTTP method and delegates to doGet(), doPost(), doPut(), doDelete() — you override the methods relevant to your endpoint. Multiple requests can execute in service() concurrently on different threads, so Servlet instance variables must be thread-safe or absent. When the application shuts down, the container calls destroy() — clean up resources here. The most common beginner mistake: storing request-specific data in instance variables. Since all requests share the same Servlet instance, instance variables cause race conditions. Always use local variables within doGet/doPost for request-specific data.
| Approach | Controls Request Handling | View Technology | Learning Curve | Used In |
|---|---|---|---|---|
| Raw Servlet | Direct | PrintWriter HTML or JSP forward | Low | Learning, legacy apps |
| JSP | Via Servlet container | JSP itself | Low | Simple dynamic pages |
| Spring MVC | DispatcherServlet | Thymeleaf, JSP, JSON | Medium | Enterprise web apps |
| Jakarta Faces | FacesServlet | Facelets (XHTML) | High | Component-based enterprise UI |
Handling HTTP Requests: doGet vs doPost
HTTP defines several request methods, but in Servlet development doGet and doPost handle the vast majority of cases. doGet is called for GET requests — URL-encoded parameters are visible in the address bar (good for search queries, navigation, bookmarkable operations, idempotent reads). doPost is called for POST requests — data is sent in the request body, not visible in the URL (required for login forms, file uploads, any data you do not want cached or bookmarked). Reading parameters from either method uses req.getParameter("fieldName") — it works the same regardless of method. Reading multiple values for the same parameter name (checkbox groups) uses req.getParameterValues("interest"). The HttpServletResponse object controls what goes back to the browser: response.setContentType("text/html") sets the MIME type, response.getWriter() returns a PrintWriter for writing HTML, response.setStatus(404) sets the HTTP status code. Always set the content type before getting the writer.

Form Processing and Reading Request Parameters
HTML forms are the primary way users submit data in traditional Java web applications. A form with method POST and an input field named username: in the Servlet, String user = req.getParameter("username") retrieves it. Form validation is your responsibility — always validate on the server side regardless of client-side JavaScript validation, because client validation can be bypassed. The forward vs redirect distinction matters practically: req.getRequestDispatcher("/result.jsp").forward(req, res) sends the request to another resource within the same application — the URL does not change and the response happens within the same request. response.sendRedirect("/success") sends a 302 response to the browser, causing it to make a new GET request to the specified URL — the URL changes. The Post-Redirect-Get pattern (submit POST form, process, then redirect) prevents duplicate form submissions when users press browser back. This is why every well-built login form redirects after success rather than forwarding.
Session Management: Cookies vs HttpSession
HTTP is stateless — the server has no memory of previous requests from the same browser. Session management is the technique that provides continuity. Two main approaches in Servlet development. Cookies: the server sends a small piece of data to the browser via the Set-Cookie header, the browser sends it back on every subsequent request via the Cookie header. You can store user identity, preferences, or session tokens in cookies. Set secure=true (HTTPS only), httpOnly=true (inaccessible to JavaScript, prevents XSS theft), and a reasonable maxAge. Never store sensitive data directly in cookies — store a session ID that maps to server-side data. HttpSession: the Servlet container manages session state for you. req.getSession() returns the current session or creates a new one. session.setAttribute("user", userObject) stores data server-side, identified by the session ID the container sends to the browser as a cookie (JSESSIONID by default). session.invalidate() destroys the session on logout. The tradeoff: cookies are stateless (good for horizontal scaling), HttpSession is stateful (simpler but requires sticky sessions or shared session storage in clustered environments). Modern microservices architectures prefer JWT tokens over HttpSession for this reason.
Deploying Servlets on Apache Tomcat: Complete Guide
Apache Tomcat is the most widely used Servlet container for Java development and is the server bundled inside Spring Boot's embedded option. For standalone Tomcat deployment: create your Servlet classes extending HttpServlet with @WebServlet annotation or web.xml mapping. Package as a WAR file using Maven (change packaging to war, add provided scope to the embedded Tomcat dependency). Copy the WAR to Tomcat's webapps directory and start Tomcat — it auto-deploys. Context path is the first segment of the URL (e.g., /myapp for a file named myapp.war). For development, use the Tomcat Maven Plugin to hot-deploy and restart from your IDE without manual WAR copying. IntelliJ IDEA Ultimate and Eclipse both have built-in Tomcat integration for debug-mode deployment. Once deployed, access your Servlet at http://localhost:8080/myapp/your-servlet-mapping. This deployment process is what Jakarta EE and traditional enterprise Java shops still use — understanding it is necessary for roles at IT services companies supporting legacy Java applications.
Maharashtra's Chief Minister Yuva Karmadharak Prakalp Yojana (CMYKPY) offers eligible youth Rs 6,000–10,000 monthly stipends during skill training. ABC Trainings is an approved CMYKPY center for IT and software training. Enroll in our Advanced Java program and offset your fees with government support. Call +91 7039169629 or WhatsApp 7774002496 for details.Get the IT Training Brochure + Fees + Batch Dates on WhatsApp
Free 1:1 counselling. Placement track record. CMYKPY/PMKVY eligibility check.
💬 Get Brochure on WhatsApp📞 Call 7039169629About the author: Amit Kulkarni. 8 yrs leading IT training at ABC Trainings, ex-Infosys.
Visit Our Centers
- Wagholi (Pune): 1st Floor, Laxmi Datta Arcade, Pune-Ahilyanagar Highway. Call 7039169629
- Hadapsar (Pune HQ): 1st Floor, Shree Tower, opp. Vaibhav Theater, Magarpatta. Call 7039169629
- Cidco (Chh. Sambhajinagar): Kalpana Plaza, opp. Eiffel Tower, N-1 Cidco. Call 7039169629
- Osmanpura (Chh. Sambhajinagar): S.S.C Board to Peer Bazar Road, near Jama Masjid. Call 7039169629
- Sangli: Shubham Emphoria, 1st Floor, Above US Polo Assn., Sangli-Miraj Rd, Vishrambag. Weekend batches available. Call 7039169629
FAQs
Do I need to learn Servlets before learning Spring MVC?
Understanding Servlets is not mandatory to use Spring MVC, but it makes you a much more effective Spring developer. When something breaks in a Spring MVC application — DispatcherServlet configuration issues, filter ordering problems, request mapping conflicts — developers who understand the underlying Servlet mechanism debug it in minutes while others waste hours. For interview purposes: many senior Java interviews explicitly test Servlet lifecycle knowledge because it reveals whether a candidate understands Java web fundamentals or only knows framework surface. Cover Servlets early in your Advanced Java learning, even if you plan to use Spring MVC in production.
What is the difference between doGet and doPost in Java Servlets?
doGet handles HTTP GET requests — parameters are sent as URL query string (visible in the browser address bar). Use GET for read-only, idempotent operations: fetching a record, running a search, rendering a page. doPost handles HTTP POST requests — parameters are sent in the request body (not visible in the URL). Use POST for write operations, login forms, file uploads, and any data that should not be bookmarked or cached. From a Servlet code perspective, both methods use req.getParameter() to read submitted values — the difference is how the browser packages and sends the data.
How does session management work in Java Servlet applications?
HTTP is inherently stateless — each request is independent with no memory of previous requests. Session management adds state on top of HTTP. The two Servlet approaches: cookies store small pieces of data in the browser and are sent back on every request (the server reads them via req.getCookies()). HttpSession stores data on the server side keyed by a session ID — the container sends the session ID to the browser as a JSESSIONID cookie and reads it back on subsequent requests to retrieve the session. For security: always invalidate the session on logout (session.invalidate()), use HTTPS, and set cookies as httpOnly and secure to prevent XSS and man-in-the-middle attacks.
Are Servlet skills required for Java jobs in India in 2026?
Yes — especially in IT services companies. TCS, Infosys, Wipro, and HCL maintain large codebases of legacy Java web applications built on Servlets and JSP. Developers who can maintain, debug, and migrate these applications are in ongoing demand. For new development roles, direct Servlet coding is less common — Spring Boot handles the web layer. However, Servlet knowledge is still tested in senior Java interviews as a signal of deep understanding, and it is required for roles involving legacy system modernization, which is a major revenue stream for Indian IT services.




