JSP (JavaServer Pages) - Complete Exam Theory
1. Introduction to JSP
What is JSP?
JavaServer Pages (JSP) is a server-side technology developed by Sun Microsystems (now Oracle) for
creating dynamic web content. JSP allows developers to embed Java code directly into HTML pages
using special JSP tags.
Key Features of JSP:
Platform Independent: Runs on any server that supports Java
Server-Side Technology: Executed on the web server, not the client
Separation of Concerns: Separates presentation logic from business logic
Reusable Components: Supports JavaBeans and custom tags
Easy to Learn: Familiar HTML syntax with Java integration
Automatic Compilation: JSP pages are automatically compiled into servlets
Advantages of JSP:
1. Ease of Development: HTML designers can easily work with JSP
2. Code Reusability: Java code can be reused across multiple pages
3. Separation of Logic: Business logic separated from presentation
4. Automatic Memory Management: Garbage collection handled by JVM
5. Exception Handling: Built-in error handling mechanisms
6. Session Management: Automatic session tracking support
Disadvantages of JSP:
1. Learning Curve: Requires knowledge of Java
2. Debugging Complexity: Can be difficult to debug
3. Performance Overhead: Compilation overhead on first request
4. Platform Dependency: Requires Java-enabled server
JSP vs Servlets:
JSP: HTML-centric with embedded Java code
Servlets: Java-centric with embedded HTML code
JSP: Better for presentation layer
Servlets: Better for business logic
2. The Anatomy of a JSP Page
Basic Structure of JSP Page:
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Page Structure</title>
</head>
<body>
<h1>Welcome to JSP</h1>
<%
String message = "Hello World";
out.println(message);
%>
<p>Current time: <%= new java.util.Date() %></p>
</body>
</html>
Components of JSP Page:
1. Template Text:
Static HTML content
Sent directly to the client browser
Forms the structure and presentation of the page
2. JSP Elements:
Directives: Provide information about the page
Declarations: Declare variables and methods
Scriptlets: Contain Java code
Expressions: Evaluate Java expressions
Actions: Perform specific tasks
3. Comments:
HTML Comments: <!-- comment --> (visible in source)
JSP Comments: <%-- comment --%> (not sent to client)
Java Comments: // comment or /* comment */ (within Java code)
JSP Page Elements Syntax:
Directives:
jsp
<%@ directive attribute="value" %>
Declarations:
jsp
<%! declaration %>
Scriptlets:
jsp
<% Java code %>
Expressions:
jsp
<%= expression %>
Actions:
jsp
<jsp:action attribute="value" />
3. JSP Processing
JSP Lifecycle:
The JSP lifecycle consists of several phases from creation to destruction.
1. Translation Phase:
JSP page is translated into a Java servlet
JSP container generates servlet source code
File typically named pagename_jsp.java
2. Compilation Phase:
Generated servlet source code is compiled
Creates .class file
Compilation errors are reported at this stage
3. Initialization Phase:
Servlet container loads the servlet class
Calls jspInit() method
Occurs only once during servlet lifecycle
4. Request Processing Phase:
For each request, _jspService() method is called
Method processes the request and generates response
This phase repeats for each client request
5. Destruction Phase:
When server shuts down or JSP is removed
jspDestroy() method is called
Used for cleanup activities
JSP Processing Steps:
Step 1: Client Request
Browser sends HTTP request to server
Server identifies the requested resource as JSP page
Step 2: JSP Container Processing
JSP container checks if servlet exists
If not, translation and compilation occur
If servlet exists, checks if JSP is modified
Step 3: Servlet Execution
Servlet processes the request
Generates dynamic content
Combines with static HTML
Step 4: Response Generation
Complete HTML response is generated
Response sent back to client browser
JSP Container Responsibilities:
1. Translation: Convert JSP to servlet
2. Compilation: Compile servlet source code
3. Loading: Load servlet class into memory
4. Instantiation: Create servlet instance
5. Initialization: Call initialization methods
6. Request Handling: Process client requests
7. Response Generation: Generate and send responses
4. Declarations, Directives, Expressions, Code Snippets
JSP Declarations:
Purpose:
Declarations are used to declare variables and methods that become part of the generated servlet
class.
Syntax:
jsp
<%! declaration %>
Characteristics:
Declared variables become instance variables
Declared methods become instance methods
Available throughout the JSP page
Shared among all requests to the page
Examples:
jsp
<%!
int counter = 0;
String siteName = "My Website";
%>
<%!
public String getCurrentDate() {
return new java.util.Date().toString();
}
private int calculateSum(int a, int b) {
return a + b;
}
%>
JSP Directives:
Purpose:
Directives provide information about the page to the JSP container and control various aspects of
servlet generation.
Types of Directives:
1. Page Directive:
jsp
<%@ page attribute="value" %>
Common Attributes:
language : Scripting language (default: java)
contentType : MIME type of response
pageEncoding : Character encoding
import : Import Java packages/classes
session : Enable/disable session (default: true)
buffer : Output buffer size
autoFlush : Auto-flush buffer (default: true)
isThreadSafe : Thread safety (default: true)
errorPage : Error handling page
isErrorPage : Mark page as error page
Example:
jsp
<%@ page language="java"
contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
import="java.util.*,java.sql.*"
session="true"
buffer="8kb"
autoFlush="true" %>
2. Include Directive:
jsp
<%@ include file="relative_url" %>
Purpose: Include content of another file at translation time Example:
jsp
<%@ include file="header.jsp" %>
<%@ include file="footer.html" %>
3. Taglib Directive:
jsp
<%@ taglib uri="tag_library_URI" prefix="prefix" %>
Purpose: Use custom tag libraries Example:
jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
JSP Expressions:
Purpose:
Expressions evaluate Java expressions and insert the result into the output.
Syntax:
jsp
<%= expression %>
Characteristics:
Must be valid Java expressions
Result is converted to String
Semicolon is not required
Cannot contain statements
Examples:
jsp
<%= new java.util.Date() %>
<%= "Hello " + request.getParameter("name") %>
<%= Math.random() %>
<%= session.getId() %>
<%= application.getServerInfo() %>
Code Snippets (Scriptlets):
Purpose:
Scriptlets contain Java code that is executed when the page is requested.
Syntax:
jsp
<% Java code %>
Characteristics:
Can contain any valid Java code
Variables are local to the _jspService() method
Can include control structures (if, for, while)
Require semicolons for statements
Examples:
jsp
<%
String userName = request.getParameter("username");
if (userName != null && !userName.isEmpty()) {
out.println("Welcome, " + userName);
} else {
out.println("Please enter your name");
}
%>
<%
for (int i = 1; i <= 5; i++) {
out.println("<p>Number: " + i + "</p>");
}
%>
<%
java.util.Date now = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:s
String formattedDate = sdf.format(now);
%>
5. Implicit Objects
Definition:
Implicit objects are pre-defined objects that are automatically available in JSP pages without explicit
declaration. They provide access to various servlet and JSP environments.
List of Implicit Objects:
1. request (HttpServletRequest):
Purpose: Represents client request
Scope: Request
Common Methods:
getParameter(String name) : Get parameter value
getParameterValues(String name) : Get multiple values
getAttribute(String name) : Get attribute
setAttribute(String name, Object value) : Set attribute
getSession() : Get session object
getRequestDispatcher(String path) : Get request dispatcher
Example:
jsp
<%
String name = request.getParameter("name");
request.setAttribute("userInfo", "Active User");
%>
2. response (HttpServletResponse):
Purpose: Represents response to client
Scope: Page
Common Methods:
setContentType(String type) : Set content type
sendRedirect(String location) : Redirect to URL
addCookie(Cookie cookie) : Add cookie
setHeader(String name, String value) : Set header
Example:
jsp
<%
response.setContentType("text/html");
response.addCookie(new Cookie("username", "john"));
%>
3. out (JspWriter):
Purpose: Write output to client
Scope: Page
Common Methods:
print(String s) : Print string
println(String s) : Print string with newline
flush() : Flush output buffer
close() : Close output stream
Example:
jsp
<%
out.println("<h1>Welcome to JSP</h1>");
out.print("Current time: " + new java.util.Date());
%>
4. session (HttpSession):
Purpose: Represents user session
Scope: Session
Common Methods:
getAttribute(String name) : Get attribute
setAttribute(String name, Object value) : Set attribute
removeAttribute(String name) : Remove attribute
getId() : Get session ID
invalidate() : Invalidate session
Example:
jsp
<%
session.setAttribute("username", "john");
String sessionId = session.getId();
%>
5. application (ServletContext):
Purpose: Represents web application
Scope: Application
Common Methods:
getAttribute(String name) : Get attribute
setAttribute(String name, Object value) : Set attribute
getInitParameter(String name) : Get init parameter
getServerInfo() : Get server information
Example:
jsp
<%
application.setAttribute("totalUsers", 100);
String serverInfo = application.getServerInfo();
%>
6. config (ServletConfig):
Purpose: Servlet configuration information
Scope: Page
Common Methods:
getInitParameter(String name) : Get init parameter
getServletName() : Get servlet name
getServletContext() : Get servlet context
7. pageContext (PageContext):
Purpose: Access to page scope and other scopes
Scope: Page
Common Methods:
setAttribute(String name, Object value, int scope) : Set attribute in specific scope
getAttribute(String name, int scope) : Get attribute from specific scope
findAttribute(String name) : Find attribute in all scopes
forward(String relativeUrlPath) : Forward request
8. page (Object):
Purpose: Reference to current JSP page instance
Scope: Page
Usage: Rarely used directly, equivalent to this in servlet
9. exception (Throwable):
Purpose: Available only in error pages
Scope: Page
Usage: Handle exceptions in error pages
Availability: Only when isErrorPage="true"
6. Using Beans in JSP Pages
What are JavaBeans?
JavaBeans are reusable Java components that follow specific conventions for naming, construction,
and behavior. They encapsulate data and provide methods to access and manipulate that data.
JavaBean Conventions:
1. Default Constructor: Must have a no-argument constructor
2. Private Properties: Instance variables should be private
3. Getter Methods: Public methods to read properties (getPropertyName)
4. Setter Methods: Public methods to write properties (setPropertyName)
5. Serializable: Should implement Serializable interface
Sample JavaBean:
java
public class User implements Serializable {
private String name;
private int age;
private String email;
// Default constructor
public User() {}
// Parameterized constructor
public User(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// Getter methods
public String getName() { return name; }
public int getAge() { return age; }
public String getEmail() { return email; }
// Setter methods
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
public void setEmail(String email) { this.email = email; }
}
JSP Bean Actions:
1. jsp:useBean:
Purpose: Instantiate or locate a JavaBean Syntax:
jsp
<jsp:useBean id="beanName" class="package.ClassName" scope="page|request|session|applic
Attributes:
id : Unique identifier for the bean
class : Fully qualified class name
scope : Where to store the bean (default: page)
type : Type of the bean reference
Examples:
jsp
<jsp:useBean id="user" class="com.example.User" scope="session" />
<jsp:useBean id="product" class="com.example.Product" scope="request" />
2. jsp:setProperty:
Purpose: Set properties of a JavaBean Syntax:
jsp
<jsp:setProperty name="beanName" property="propertyName" value="value" />
<jsp:setProperty name="beanName" property="propertyName" param="parameterName" />
<jsp:setProperty name="beanName" property="*" />
Examples:
jsp
<jsp:setProperty name="user" property="name" value="John Doe" />
<jsp:setProperty name="user" property="age" param="userAge" />
<jsp:setProperty name="user" property="*" />
3. jsp:getProperty:
Purpose: Get property value from a JavaBean Syntax:
jsp
<jsp:getProperty name="beanName" property="propertyName" />
Examples:
jsp
<p>Name: <jsp:getProperty name="user" property="name" /></p>
<p>Age: <jsp:getProperty name="user" property="age" /></p>
Complete Bean Example:
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<jsp:useBean id="user" class="com.example.User" scope="session" />
<jsp:setProperty name="user" property="name" value="John Doe" />
<jsp:setProperty name="user" property="age" value="25" />
<jsp:setProperty name="user" property="email" value="john@example.com" />
<!DOCTYPE html>
<html>
<head>
<title>JavaBean Example</title>
</head>
<body>
<h1>User Information</h1>
<p>Name: <jsp:getProperty name="user" property="name" /></p>
<p>Age: <jsp:getProperty name="user" property="age" /></p>
<p>Email: <jsp:getProperty name="user" property="email" /></p>
</body>
</html>
Bean Scopes:
1. page: Available only in current page
2. request: Available during current request
3. session: Available during user session
4. application: Available to entire web application
7. Using Cookies and Session for Session Tracking
Session Tracking:
Session tracking is the mechanism to maintain state across multiple HTTP requests from the same
user, as HTTP is stateless protocol.
Methods of Session Tracking:
1. Cookies
2. URL Rewriting
3. Hidden Form Fields
4. HttpSession API
Cookies:
What are Cookies?
Cookies are small pieces of data stored on the client's computer by the web browser. They are sent
back to the server with each request.
Cookie Characteristics:
Name-Value Pairs: Store data as key-value pairs
Persistence: Can be temporary (session) or persistent
Domain Specific: Sent only to the domain that created them
Size Limitation: Typically 4KB maximum
Browser Dependent: Can be disabled by users
Creating Cookies in JSP:
jsp
<%
// Create cookie
Cookie userCookie = new Cookie("username", "john_doe");
userCookie.setMaxAge(60 * 60 * 24); // 1 day
userCookie.setPath("/");
response.addCookie(userCookie);
// Create multiple cookies
Cookie[] cookies = {
new Cookie("theme", "dark"),
new Cookie("language", "en"),
new Cookie("fontSize", "12")
};
for (Cookie cookie : cookies) {
cookie.setMaxAge(60 * 60 * 24 * 7); // 1 week
response.addCookie(cookie);
}
%>
Reading Cookies in JSP:
jsp
<%
Cookie[] cookies = request.getCookies();
String username = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
username = cookie.getValue();
break;
}
}
}
if (username != null) {
out.println("Welcome back, " + username);
} else {
out.println("Welcome, new user!");
}
%>
Cookie Methods:
setMaxAge(int seconds) : Set cookie expiration
setPath(String path) : Set cookie path
setDomain(String domain) : Set cookie domain
setSecure(boolean secure) : Set secure flag
getName() : Get cookie name
getValue() : Get cookie value
Sessions (HttpSession):
What is a Session?
A session represents a conversation between a client and server. It maintains state across multiple
requests from the same user.
Session Characteristics:
Server-Side Storage: Data stored on server
Session ID: Unique identifier for each session
Automatic Management: Container handles session creation/destruction
Timeout: Sessions expire after inactivity
Thread-Safe: Session objects are thread-safe
Using Sessions in JSP:
jsp
<%
// Get session (implicit object)
HttpSession userSession = request.getSession();
// Set session attributes
userSession.setAttribute("username", "john_doe");
userSession.setAttribute("role", "admin");
userSession.setAttribute("loginTime", new java.util.Date());
// Get session attributes
String username = (String) userSession.getAttribute("username");
String role = (String) userSession.getAttribute("role");
// Session information
String sessionId = userSession.getId();
boolean isNew = userSession.isNew();
long creationTime = userSession.getCreationTime();
long lastAccessTime = userSession.getLastAccessedTime();
int maxInactiveInterval = userSession.getMaxInactiveInterval();
%>
<p>Session ID: <%= sessionId %></p>
<p>Username: <%= username %></p>
<p>Role: <%= role %></p>
<p>Is New Session: <%= isNew %></p>
Session Management:
jsp
<%
// Check if user is logged in
String username = (String) session.getAttribute("username");
if (username == null) {
response.sendRedirect("login.jsp");
return;
}
// Logout functionality
if ("logout".equals(request.getParameter("action"))) {
session.removeAttribute("username");
session.invalidate();
response.sendRedirect("login.jsp");
return;
}
// Set session timeout (30 minutes)
session.setMaxInactiveInterval(30 * 60);
%>
Session Configuration (web.xml):
xml
<session-config>
<session-timeout>30</session-timeout>
<cookie-config>
<name>JSESSIONID</name>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</session-config>
Comparison: Cookies vs Sessions:
Aspect Cookies Sessions
Storage Client-side Server-side
Security Less secure More secure
Size Limit 4KB No practical limit
Persistence Can be persistent Temporary
Performance Faster Slower
Browser Dependency Can be disabled Always available
8. Connecting to Database in JSP
Database Connectivity in JSP:
JSP can connect to databases using JDBC (Java Database Connectivity) API to perform database
operations like SELECT, INSERT, UPDATE, DELETE.
JDBC Architecture:
1. JDBC API: Java application interfaces
2. JDBC Driver Manager: Manages database drivers
3. JDBC Drivers: Database-specific implementations
4. Database: Actual data storage
Steps for Database Connection:
Step 1: Import Required Packages
jsp
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
Step 2: Load Database Driver
jsp
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// or for other databases:
// Class.forName("oracle.jdbc.driver.OracleDriver");
// Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
out.println("Driver not found: " + e.getMessage());
}
%>
Step 3: Establish Database Connection
jsp
<%
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
out.println("Database connected successfully!");
} catch (SQLException e) {
out.println("Connection failed: " + e.getMessage());
}
%>
Database Operations:
SELECT Operation:
jsp
<%
String sql = "SELECT id, name, email FROM users";
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
out.println("<table border='1'>");
out.println("<tr><th>ID</th><th>Name</th><th>Email</th></tr>");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
out.println("<tr>");
out.println("<td>" + id + "</td>");
out.println("<td>" + name + "</td>");
out.println("<td>" + email + "</td>");
out.println("</tr>");
}
out.println("</table>");
} catch (SQLException e) {
out.println("Query failed: " + e.getMessage());
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
}
%>
INSERT Operation:
jsp
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
if (name != null && email != null) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, email);
int rowsAffected = pstmt.executeUpdate();
if (rowsAffected > 0) {
out.println("User added successfully!");
}
} catch (SQLException e) {
out.println("Insert failed: " + e.getMessage());
} finally {
if (pstmt != null) pstmt.close();
}
}
%>
UPDATE Operation:
jsp
<%
String userId = request.getParameter("userId");
String newName = request.getParameter("newName");
if (userId != null && newName != null) {
String sql = "UPDATE users SET name = ? WHERE id = ?";
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, newName);
pstmt.setInt(2, Integer.parseInt(userId));
int rowsAffected = pstmt.executeUpdate();
if (rowsAffected > 0) {
out.println("User updated successfully!");
}
} catch (SQLException e) {
out.println("Update failed: " + e.getMessage());
} finally {
if (pstmt != null) pstmt.close();
}
}
%>
DELETE Operation:
jsp
<%
String userId = request.getParameter("userId");
if (userId != null) {
String sql = "DELETE FROM users WHERE id = ?";
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, Integer.parseInt(userId));
int rowsAffected = pstmt.executeUpdate();
if (rowsAffected > 0) {
out.println("User deleted successfully!");
}
} catch (SQLException e) {
out.println("Delete failed: " + e.getMessage());
} finally {
if (pstmt != null) pstmt.close();
}
}
%>
Complete Database Example:
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Database Connection Example</title>
</head>
<body>
<h1>User Management System</h1>
<%
// Database connection parameters
String url = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "password";
Connection conn = null;
try {
// Load driver and establish connection
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
// Display all users
String sql = "SELECT * FROM users ORDER BY id";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
out.println("<h2>All Users</h2>");
out.println("<table border='1' cellpadding='5'>");
out.println("<tr><th>ID</th><th>Name</th><th>Email</th><th>Created</th></t
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("id") + "</td>");
out.println("<td>" + rs.getString("name") + "</td>");
out.println("<td>" + rs.getString("email") + "</td>");
out.println("<td>" + rs.getTimestamp("created_at") + "</td>");
out.println("</tr>");
}
out.println("</table>");
rs.close();
stmt.close();
} catch (Exception e) {
out.println("<p style='color:red'>Error: " + e.getMessage() + "</p>");
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
out.println("Error closing connection: " + e.getMessage());
}
}
}
%>
<h2>Add New User</h2>
<form method="post" action="addUser.jsp">
<p>Name: <input type="text" name="name" required></p>
<p>Email: <input type="email" name="email" required></p>
<p><input type="submit" value="Add User"></p>
</form>
</body>
</html>
Database Best Practices:
1. Connection Management:
Always close connections, statements, and result sets
Use try-with-resources or finally blocks
Use connection pooling for production applications
2. Security:
Use PreparedStatement to prevent SQL injection
Validate and sanitize input data
Use proper authentication and authorization
3. Error Handling:
Implement proper exception handling
Log errors appropriately
Provide user-friendly error messages
4. Performance:
Use connection pooling
Optimize SQL queries
Implement proper indexing
Use batch operations for multiple inserts/updates
Connection Pooling Example:
jsp
<%@ page import="javax.naming.*" %>
<%@ page import="javax.sql.*" %>
<%
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/mydb");
Connection conn = ds.getConnection();
// Use connection for database operations
// Connection will be returned to pool automatically when closed
} catch (Exception e) {
out.println("Connection pool error: " + e.getMessage());
}
%>
This comprehensive guide covers all the essential JSP topics for your exam. Focus on understanding
the concepts, syntax, and practical applications of each topic.