Adv-Java Unit 2: Complete Concept Guide
Unit 2: Servlets • JSP • JSTL -> Generated and Prepared By Thiruselvan (ThiruXD)
PART 1 – SERVLETS
1. What is a Servlet?
Theory
A Servlet is a Java class that runs inside a web container (Tomcat, Jetty, etc.) and handles client HTTP requests to generate dynamic responses.
Important Points
- Extends
HttpServlet - Managed by the container (not by the programmer)
- One instance of the servlet serves many requests using threads
- Persistent (stays in memory) unlike CGI
- Platform independent
Code Example
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.getWriter().println("<h1>Hello from Servlet</h1>");
}
}2. Servlet Life Cycle
Theory
The container controls the complete life of a servlet through three main methods.
Phases
- init() – Called only once when the servlet is first loaded. Used for initialization (loading config, opening DB connection, etc.)
- service() – Called for every client request. Internally calls
doGet()ordoPost(). - destroy() – Called only once just before the servlet is unloaded. Used to release resources.
Important Points
init()anddestroy()are called only onceservice()is called many times (multithreaded)- Never create the servlet object yourself – container does it
Code Example
public class LifeCycleServlet extends HttpServlet {
public void init() {
System.out.println("Servlet Initialized");
}
protected void service(HttpServletRequest req, HttpServletResponse res) {
System.out.println("Service method called");
}
public void destroy() {
System.out.println("Servlet Destroyed");
}
}3. doGet() vs doPost()
Theory
| Point | doGet() | doPost() |
|---|---|---|
| HTTP Method | GET | POST |
| Data Location | URL (Query String) | Request Body |
| Visibility | Visible in browser address bar | Not visible |
| Bookmarkable | Yes | No |
| Idempotent | Yes | No |
| Data Size Limit | Limited | Unlimited (practically) |
| Best Used For | Retrieving data / Navigation | Submitting forms / Sensitive data |
Code Example
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
// Show the login form
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.setContentType("text/html");
res.getWriter().println("<form method='post' action='login'>"
+ "Username: <input type='text' name='user'><br>"
+ "Password: <input type='password' name='pass'><br>"
+ "<input type='submit' value='Login'>"
+ "</form>");
}
// Process the form
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException {
String user = req.getParameter("user");
String pass = req.getParameter("pass");
// authentication logic
res.getWriter().println("Welcome " + user);
}
}4. Reading Request Data
Theory
HttpServletRequest object contains all data sent by the client.
Important Methods
getParameter("name")→ single valuegetParameterValues("name")→ multiple values (checkboxes)getParameterMap()→ all parametersgetHeader("name")→ request headergetMethod()→ GET or POSTgetRequestURI()→ requested URLgetSession()→ session objectgetCookies()→ array of cookiesgetAttribute("name")→ attribute set during forward
Code Example
protected void doPost(HttpServletRequest req, HttpServletResponse res) {
String email = req.getParameter("email");
String[] hobbies = req.getParameterValues("hobby");
// Print all parameters
req.getParameterMap().forEach((key, values) -> {
System.out.println(key + " = " + Arrays.toString(values));
});
}5. Writing Response
Theory
HttpServletResponse is used to send data back to the client.
Important Methods
setContentType("text/html")setCharacterEncoding("UTF-8")getWriter()→ character datagetOutputStream()→ binary datasetStatus(200)setHeader("name", "value")addCookie(cookie)sendRedirect(url)sendError(404, "Not Found")
6. RequestDispatcher (forward & include)
Theory
forward()
- Transfers control to another resource on the server
- Same request and response objects are used
- Browser URL does not change
- Original servlet loses control completely
- Most common use: Servlet (Controller) → JSP (View)
include()
- Includes the output of another resource into the current response
- Control returns back to the original servlet
- Used for common headers, footers, menus
Code Example
// Forward
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
request.setAttribute("username", "Ram");
rd.forward(request, response);
// Include
request.getRequestDispatcher("header.jsp").include(request, response);7. sendRedirect()
Theory
sendRedirect() tells the browser to make a completely new request to a different URL.
Important Points
- Client-side redirect (HTTP 302)
- Browser URL changes
- New request is created → previous request attributes are lost
- Can redirect to any URL (even external websites)
- Preferred after successful form submission (Post-Redirect-Get pattern)
Code Example
// After successful login
response.sendRedirect("home.jsp");
// External redirect
response.sendRedirect("<https://www.google.com>");8. forward() vs sendRedirect() (Most Asked Question)
| Point | forward() | sendRedirect() |
|---|---|---|
| Execution | Server-side | Client-side |
| Browser URL | Does not change | Changes |
| Request Object | Same request | New request |
| Attributes | Preserved | Lost |
| Speed | Faster | Slower (extra network trip) |
| Can go outside app? | No | Yes |
| Typical Use | Controller → View | After POST / Logout / External |
9. Servlet Annotations
Theory
From Servlet 3.0 onwards, annotations replaced most of the web.xml configuration.
Important Annotations
@WebServlet→ maps URL to servlet@WebFilter→ registers filter@WebListener→ registers listener@WebInitParam→ init parameters@MultipartConfig→ file upload support
Code Example
@WebServlet(urlPatterns = {"/report", "/r"},
initParams = {
@WebInitParam(name = "format", value = "pdf")
})
public class ReportServlet extends HttpServlet {
public void init() {
String format = getInitParameter("format"); // "pdf"
}
}PART 2 – SESSION MANAGEMENT
10. Why Session Management is Needed?
Theory
HTTP is a stateless protocol. Every request is independent. Session management is used to maintain conversation state between client and server across multiple requests.
Four Techniques
- HttpSession (most preferred)
- Cookies
- URL Rewriting
- Hidden Form Fields
11. HttpSession
Theory
HttpSession is a server-side object that stores user-specific data. The container tracks it using a special cookie called JSESSIONID.
Important Methods
request.getSession()→ creates new session if not existsrequest.getSession(false)→ returns null if no sessionsession.setAttribute(name, value)session.getAttribute(name)session.removeAttribute(name)session.invalidate()→ destroy session (logout)session.setMaxInactiveInterval(seconds)session.getId()
Code Example
// Login
HttpSession session = request.getSession();
session.setAttribute("user", "Ram");
session.setMaxInactiveInterval(30 * 60); // 30 minutes
// Later request
String user = (String) session.getAttribute("user");
if (user == null) {
response.sendRedirect("login.jsp");
}
// Logout
session.invalidate();12. Cookies
Theory
A Cookie is a small piece of information sent by the server and stored by the browser. The browser automatically sends it back with every subsequent request.
Important Points
- Created using
new Cookie(name, value) - Added using
response.addCookie(cookie) - Read using
request.getCookies() setMaxAge(seconds)→ persistent cookiesetMaxAge(-1)or omit → session cookie- Use
setHttpOnly(true)for security
Code Example
// Create cookie
Cookie c = new Cookie("theme", "dark");
c.setMaxAge(60 * 60 * 24); // 1 day
c.setHttpOnly(true);
response.addCookie(c);
// Read cookies
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie ck : cookies) {
if (ck.getName().equals("theme")) {
String theme = ck.getValue();
}
}
}13. URL Rewriting & Hidden Fields
URL Rewriting
When cookies are disabled, session ID is appended to every URL.
Use response.encodeURL(url).
Hidden Form Fields
State is carried inside the HTML form using
<input type="hidden" name="..." value="...">
PART 3 – JSP & JSTL
14. What is JSP?
Theory
JSP (JavaServer Pages) is a technology that allows us to write HTML pages with embedded Java code.
The container translates the JSP into a Servlet automatically.
Advantages
- Better separation of presentation and logic
- Easier to write HTML-heavy pages
- Automatically compiled by container
JSP Life Cycle
- Translation (JSP → Java source)
- Compilation (Java → .class)
jspInit()_jspService()(called for every request)jspDestroy()
15. JSP Scripting Elements
| Element | Syntax | Purpose |
|---|---|---|
| Scriptlet | <% ... %> | Write Java statements |
| Expression | <%= ... %> | Print a value |
| Declaration | <%! ... %> | Declare variables/methods |
| Directive | <%@ ... %> | Page configuration |
| Comment | <%-- ... --%> | JSP comment |
Code Example
<%@ page contentType="text/html" %>
<html>
<body>
<%! int count = 0; %> <!-- Declaration -->
<%
String name = request.getParameter("name");
count++;
%> <!-- Scriptlet -->
<h1>Hello <%= name %></h1> <!-- Expression -->
<p>Visit count: <%= count %></p>
</body>
</html>16. JSP Implicit Objects (Very Important for Exam)
There are 9 implicit objects automatically available in every JSP:
| Object | Type | Use |
|---|---|---|
| request | HttpServletRequest | Get parameters, attributes |
| response | HttpServletResponse | Set headers, redirect |
| out | JspWriter | Write output |
| session | HttpSession | Session data |
| application | ServletContext | Application scope |
| config | ServletConfig | Init parameters |
| pageContext | PageContext | Access all scopes |
| page | Object | Current servlet instance |
| exception | Throwable | Only in error pages |
17. JSP Directives
<%@ page ... %>→ contentType, import, errorPage, isErrorPage, session<%@ include file="header.jsp" %>→ static include<%@ taglib prefix="c" uri="..." %>→ import tag library
18. Expression Language (EL)
Theory
EL is used to access data from different scopes without writing Java code in JSP.
It is the modern replacement of scriptlet expressions.
Syntax: ${expression}
Examples
${user.name}
${param.username}
${sessionScope.cart}
${10 + 20}
${empty name ? "Guest" : name}19. JSTL (JSP Standard Tag Library)
Theory
JSTL provides a set of ready-made tags that replace scriptlets, making JSP pages cleaner and more maintainable.
Most Important Library – Core
<%@ taglib prefix="c" uri="jakarta.tags.core" %>Important Core Tags
| Tag | Purpose |
|---|---|
<c:out value="..."/> | Print value (safe) |
<c:set var="x" value="..."/> | Create variable |
<c:if test="${condition}"> | Conditional rendering |
<c:choose> <c:when> <c:otherwise> | if-else-if ladder |
<c:forEach items="..." var="..."> | Looping |
<c:forTokens> | Split and loop string |
<c:redirect url="..."/> | Redirect |
<c:url value="..."/> | Create encoded URL |
Code Example
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<c:set var="name" value="Rahul"/>
<p>Hello <c:out value="${name}"/></p>
<c:if test="${marks >= 40}">
<p>Pass</p>
</c:if>
<c:forEach var="item" items="${list}">
<p>${item}</p>
</c:forEach>
<table>
<c:forEach var="p" items="${products}" varStatus="st">
<tr>
<td>${st.count}</td>
<td><c:out value="${p.name}"/></td>
<td>
<c:choose>
<c:when test="${p.stock > 0}">Available</c:when>
<c:otherwise>Out of Stock</c:otherwise>
</c:choose>
</td>
</tr>
</c:forEach>
</table>20. Final Exam Quick Revision Points
- Servlet Life Cycle → init → service → destroy
- One servlet instance + multiple threads
- doGet → URL data, doPost → body data
- forward() → server side, same request
- sendRedirect() → client side, new request
- HttpSession is the best way to maintain state
- JSESSIONID cookie is used by container
- JSP is converted into Servlet by container
- 9 Implicit Objects in JSP
- Prefer EL + JSTL instead of scriptlets
<c:forEach>,<c:if>,<c:choose>are most used JSTL tags@WebServletis preferred over web.xml
Adv-Java Unit 1: Questions & Answers
Unit 1: Object-Oriented Programming Concepts, Enumerations, Autoboxing, Annotations & Collections Framework -> Generated and Prepared By Thiruselvan (ThiruXD)
Adv-Java Unit 2: Questions & Answers
Unit 2: Servlets • JSP • JSTL -> Generated and Prepared By Thiruselvan (ThiruXD)