A Servlet is a server-side Java program that handles client requests and generates
dynamic web content. It operates within a Servlet container (such as Apache
Tomcat) and follows the request-response model, typically using the HTTP protocol.
Servlets are a core component of the Java EE (Jakarta EE) platform and are used to
develop web-based applications. They process input sent by web clients (e.g.,
browsers), interact with business logic or databases, and produce responses in formats
like HTML, JSON, or XML.
1. HttpServletRequest
HttpServletRequest extends ServletRequest and provides HTTP-specific features to handle client
requests. It is commonly used to:
Retrieve form data submitted by the client
Access HTTP headers and cookies
Manage user sessions and authentication
Example:
String cookieValue = request.getHeader("Cookie");
HttpSession session = request.getSession();,
Important Methods:
Method Description
getParameter(String name) Retrieves the value of a request parameter
getHeader(String name) Returns the value of the specified header
getCookies() Returns an array of Cookie objects
getSession() Returns the current HttpSession or creates a new one
2. HttpServletResponse: HttpServletResponse extends ServletResponse and allows a servlet to
send a response to the client. It is typically used to:
Send HTML or file content as a response
Set HTTP headers and content types
Redirect the user to another URL
Set HTTP status codes like 200 or 404
Example:
response.sendRedirect("home.jsp");
response.setStatus(HttpServletResponse.SC_OK);
Important Methods:
Method Description
setContentType(String type) Sets the MIME type of the response
Method Description
getWriter() Gets a PrintWriter for writing response data
sendRedirect(String location) Redirects the client to a new location
setStatus(int sc) Sets the HTTP response status code
3. HttpSession
HttpSession is used to track user-specific data across multiple requests. It is essential for:
Maintaining login state
Storing shopping cart contents
Saving user preferences or temporary data
Example:
HttpSession session = request.getSession();
session.setAttribute("user", "Nivi");
Important Methods:
Method Description
setAttribute(String name, Object value) Stores a value in the session
getAttribute(String name) Retrieves a stored session value
invalidate() Invalidates the session and removes all attributes
getId() Returns the unique session ID
4. HttpSessionListener
HttpSessionListener listens for session lifecycle events. It is useful when you need to:
Count or log active user sessions
Perform actions on session creation or destruction
Clean up resources when a session end
Example:
public class SessionCounter implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session Created: " + se.getSession().getId());
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Session Destroyed: " + se.getSession().getId());
Important Methods:
Method
Description
sessionCreated(HttpSessionEvent se) Called when a new session is created
sessionDestroyed(HttpSessionEvent se) Called when a session is invalidated or times out
A JSP (Java Server Page) is a server-side technology which is used for creating web applications.
It is used to create dynamic web content. JSP consists of both HTML tags and JSP tags. In this,
JSP tags are used to insert JAVA code into HTML pages. It is an advanced version of Servlet
Technology i.e. a web-based technology that helps us to create dynamic and platform-
independent web pages.
A JSP tag consists of a combination of HTML tags and JSP tags. JSP tags define java code
that is to be executed before the output of JSP program is sent to the browser.
A JSP tag begin with a <%, which is followed by java code, and ends with %>,
There is an XML version of JSP tag jsp:TagID </jsp:TagID>
A JSP tags are embedded into the HTML component of a JSP program and are processed
by JSP virtual engine such as Tomcat.
Java code associated with JSP tag are executed and sent to browser by tomcat.
Type Definition (Simplified) Syntax Example
Used to write comments in JSP
Comment <%-- comment --
that are not visible in browser <%-- This is a comment --%>
Tag %>
output.
Declares variables, objects, or
Declaration <%! declaration
methods that can be used <%! int count = 0; %>
Tag %>
throughout the JSP page.
Instructs the JSP engine (e.g., <%@ page import="java.sql.*"
<%@ directive
Directive Tag to import packages, include %><%@ include file="file.html"
attr="value" %>
files, define tag libraries). %>
Expression Outputs result of a Java <%= expression
<%= new java.util.Date() %>
Tag expression to browser. %>
Contains Java code (loops,
<% for(int i=0;i<3;i++)
Scriptlet Tag conditions) that runs when the <% java code %>
{ out.print(i); } %>
page is requested.
✅ Types of JSP Tags
1. Comment Tag
A Comment Tag (<%-- --%>) in JSP allows developers to insert hidden
comments that describe code functionality. These comments are
excluded from the final HTML output, serving as internal
documentation visible only in the JSP source file.
Syntax: <%-- comment goes here --%>
Example: <%-- This section handles user login --%>
2. Declaration Tag
A Declaration Tag (<%! %>) in JSP allows developers to declare
variables, objects, or methods at the class level. These declarations
become part of the generated servlet and can be accessed throughout
the JSP page, maintaining state between requests.
Syntax: <%! declaration code %>
Example: <%! int count = 0; %> <%! String getMessage() { return
"Welcome!"; } %>
3. Directive Tag
A Directive Tag (<%@ %>) provides instructions to the JSP engine,
such as importing Java packages (import), including external files
(include), or declaring tag libraries (taglib). These commands are
processed during page translation, before the JSP becomes a servlet.
Syntax: <%@ directive attribute="value" %>
Examples:
o <%@ page import="java.sql.*" %> <%-- Imports Java SQL
package --%>
o <%@ include file="books.html" %> <%-- Includes another HTML
file --%>
o <%@ taglib uri="myTags.tld" %> <%-- Refers to a tag library --
%>
4. Expression Tag
A JSP Expression Tag (<%= %>) embeds Java expression results
directly into HTML output. It evaluates expressions like variables,
calculations, or method calls, converts them to strings, and inserts
them into the response sent to the browser.
Syntax: <%= expression %>
Example: <%= "Today is: " + new java.util.Date() %>
5. Scriptlet Tag
A Scriptlet Tag (<% %>) in JSP allows writing raw Java code (like loops,
conditions, or variable declarations) directly within the HTML page. This
code executes every time the JSP is requested, enabling dynamic
content generation before the final response is sent to the browser.
Syntax: <% java code %>
Example: