BTCE | 5th Sem
Adv-Java SubjectUnit 2

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

  1. init() – Called only once when the servlet is first loaded. Used for initialization (loading config, opening DB connection, etc.)
  2. service() – Called for every client request. Internally calls doGet() or doPost().
  3. destroy() – Called only once just before the servlet is unloaded. Used to release resources.

Important Points

  • init() and destroy() are called only once
  • service() 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

PointdoGet()doPost()
HTTP MethodGETPOST
Data LocationURL (Query String)Request Body
VisibilityVisible in browser address barNot visible
BookmarkableYesNo
IdempotentYesNo
Data Size LimitLimitedUnlimited (practically)
Best Used ForRetrieving data / NavigationSubmitting 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 value
  • getParameterValues("name") → multiple values (checkboxes)
  • getParameterMap() → all parameters
  • getHeader("name") → request header
  • getMethod() → GET or POST
  • getRequestURI() → requested URL
  • getSession() → session object
  • getCookies() → array of cookies
  • getAttribute("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 data
  • getOutputStream() → binary data
  • setStatus(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)

Pointforward()sendRedirect()
ExecutionServer-sideClient-side
Browser URLDoes not changeChanges
Request ObjectSame requestNew request
AttributesPreservedLost
SpeedFasterSlower (extra network trip)
Can go outside app?NoYes
Typical UseController → ViewAfter 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

  1. HttpSession (most preferred)
  2. Cookies
  3. URL Rewriting
  4. 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 exists
  • request.getSession(false) → returns null if no session
  • session.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 cookie
  • setMaxAge(-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

  1. Translation (JSP → Java source)
  2. Compilation (Java → .class)
  3. jspInit()
  4. _jspService() (called for every request)
  5. jspDestroy()

15. JSP Scripting Elements

ElementSyntaxPurpose
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:

ObjectTypeUse
requestHttpServletRequestGet parameters, attributes
responseHttpServletResponseSet headers, redirect
outJspWriterWrite output
sessionHttpSessionSession data
applicationServletContextApplication scope
configServletConfigInit parameters
pageContextPageContextAccess all scopes
pageObjectCurrent servlet instance
exceptionThrowableOnly 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

TagPurpose
<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

  1. Servlet Life Cycle → init → service → destroy
  2. One servlet instance + multiple threads
  3. doGet → URL data, doPost → body data
  4. forward() → server side, same request
  5. sendRedirect() → client side, new request
  6. HttpSession is the best way to maintain state
  7. JSESSIONID cookie is used by container
  8. JSP is converted into Servlet by container
  9. 9 Implicit Objects in JSP
  10. Prefer EL + JSTL instead of scriptlets
  11. <c:forEach>, <c:if>, <c:choose> are most used JSTL tags
  12. @WebServlet is preferred over web.xml

On this page