0% found this document useful (0 votes)
6 views14 pages

Java Server Pages Overview and Lifecycle

Java Server Pages (JSP) is a server-side technology for creating dynamic web applications by embedding Java code into HTML. It operates on a three-tier architecture involving a client, web server, and database, with a defined life cycle including translation, compilation, and request processing phases. Key features include scripting elements, directive elements, and implicit objects that facilitate the integration of Java functionality within web pages.

Uploaded by

ahanasayeed.786
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views14 pages

Java Server Pages Overview and Lifecycle

Java Server Pages (JSP) is a server-side technology for creating dynamic web applications by embedding Java code into HTML. It operates on a three-tier architecture involving a client, web server, and database, with a defined life cycle including translation, compilation, and request processing phases. Key features include scripting elements, directive elements, and implicit objects that facilitate the integration of Java functionality within web pages.

Uploaded by

ahanasayeed.786
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA Lecturer Notes, S.J.V.

P college, Harihar

UNIT 4
Java Server Pages
Introduction
What is JSP?
JSP (Java Server Pages) is a server-side technology used for creating dynamic, platform-
independent web applications.
It allows embedding Java code directly into HTML pages using special JSP tags.
Key Features of JSP:
 Developed by Sun Microsystems (now Oracle)
 Part of Java EE (Enterprise Edition)
 Similar to PHP, ASP, but uses Java
 Compiled into Servlets behind the scenes
 Supports HTML, Java, JavaBeans, and custom tags

Architecture of JSP
JSP architecture gives a high-level view of the working of JSP. JSP architecture is a 3 tier
architecture. It has a Client, Web Server, and Database. The client is the web browser or
application on the user side. Web Server uses a JSP Engine i.e; a container that processes
JSP. For example, Apache Tomcat has a built-in JSP Engine. JSP Engine intercepts the
request for JSP and provides the runtime environment for the understanding and processing
of JSP files. It reads, parses, build Java Servlet, Compiles and Executes Java code, and
returns the HTML page to the client. The webserver has access to the Database. The
following diagram shows the architecture of JSP.

Now let us discuss JSP which stands for Java Server Pages. It is a server-side technology. It
is used for creating web applications. It is used to create dynamic web content. In this JSP
tags are used to insert JAVA code into HTML pages. It is an advanced version of Servlet
Technology. It is a Web-based technology that helps us to create dynamic and platform-
independent web pages. In this, Java code can be inserted in HTML/ XML pages or both.
JSP is first converted into a servlet by JSP container before processing the client’s
request. JSP Processing is illustrated and discussed in sequential steps prior to which a

BY, PALLAVI P ASSISTANT LECTURER Page 1


JAVA Lecturer Notes, S.J.V.P college, Harihar

pictorial media is provided as a handful pick to understand the JSP processing better which
is as follows:

Step 1: The client navigates to a file ending with the .jsp extension and the browser
initiates an HTTP request to the webserver. For example, the user enters the login details
and submits the button. The browser requests a [Link] page from the webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file.
Otherwise, the request is forwarded to the JSP Engine. This is done by recognizing the
URL ending with .jsp extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java code). This
is done by converting all the template text into println() statements and JSP elements to
Java code. This process is called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is forwarded to
the Servlet engine. This process is called compilation or request processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web Server.
The output is an HTML file. The Servlet engine passes the output as an HTTP response to
the webserver.
Step 6: The web server forwards the HTML file to the client's browser.

Life Cycle of JSP

The life cycle of a JSP defines the steps the web server (servlet container) follows from
loading the JSP to serving requests and destroying it.

1. Translation Phase

 The JSP file is translated into a Servlet by the JSP engine.


 The file gets converted into a Java class that extends HttpJspBase.

<% [Link]("Hello"); %>

→ becomes servlet code like:

BY, PALLAVI P ASSISTANT LECTURER Page 2


JAVA Lecturer Notes, S.J.V.P college, Harihar

[Link]("Hello");

2. Compilation Phase

 The translated servlet is compiled into a .class file (Java bytecode).


 This step is performed only once, unless the JSP is modified.

3. Class Loading Phase

 The generated servlet class is loaded into memory using the servlet class loader.

4. Instantiation Phase

 The JSP class object is created by the servlet container.

5. Initialization Phase (jspInit())

 The container calls the jspInit() method once after instantiation.


 Used to initialize resources like DB connections, configuration, etc.

6. Request Processing (_jspService())

 For every HTTP request, the container calls the _jspService(HttpServletRequest,


HttpServletResponse) method.
 This is where the main logic resides (mix of HTML and Java code).
 Called every time a request is made.

7. Destruction Phase (jspDestroy())

 When the JSP is removed from service or the server shuts down, jspDestroy() is
called.
 Used to release resources, like closing DB connections, cleaning up memory, etc.

BY, PALLAVI P ASSISTANT LECTURER Page 3


JAVA Lecturer Notes, S.J.V.P college, Harihar

Summary of Key Methods:

Method Called When Purpose


jspInit() Once when JSP is initialized Resource initialization
_jspService() Every time a client sends a request Handles client request and response
jspDestroy() When JSP is unloaded from memory Cleanup operations

Scripting elements (Scriplets, JSP Declarations, JSP Expression)

JSP scripting elements are used to insert Java code directly into a JSP page. These
elements allow embedding logic, declaring variables/methods, and outputting dynamic
values.1. Scriptlets (<% ... %>)

Used to insert Java code inside HTML. This code is placed inside the _jspService() method
of the servlet.

🔹 Syntax:

<%
// Java code
int a = 5;
[Link]("Value of a: " + a);
%>

Example:

<html>
<body>
<%
int x = 10;
int y = 20;

BY, PALLAVI P ASSISTANT LECTURER Page 4


JAVA Lecturer Notes, S.J.V.P college, Harihar

int sum = x + y;
[Link]("Sum is: " + sum);
%>
</body>
</html>

2. JSP Declarations (<%! ... %>)

Used to declare methods or class-level variables that are outside _jspService() (i.e., they
belong to the class, not the method).

🔹 Syntax:

<%!
int counter = 0;

public int square(int n) {


return n * n;
}
%>

Example:

<%!
int count = 0;

public void incrementCount() {


count++;
}
%>

<%
incrementCount();
[Link]("Current count: " + count);
%>

3. JSP Expressions (<%= ... %>)

Used to evaluate a Java expression and print the result directly to the output. It's short for
[Link](...).

🔹 Syntax:

<%= expression %>

🔹 Example:

<html>
<body>

BY, PALLAVI P ASSISTANT LECTURER Page 5


JAVA Lecturer Notes, S.J.V.P college, Harihar

<%
int num = 7;
%>
<p>Square of <%= num %> is <%= num * num %></p>
</body>
</html>

Summary Table:
Element Type Syntax Purpose
Scriptlet <% code %> Embed Java logic in JSP
Declaration <%! code %> Declare methods or variables
Expression <%= expression %> Output the result of an expression

Directive Elements(page, include, taglib)

In Java web development using JSP (JavaServer Pages), directive elements are special
instructions that are processed by the JSP engine at page translation time, i.e., before the
JSP is compiled into a servlet.

There are three main types of directive elements in JSP:

1. <%@ page ... %> — Page Directive

The page directive defines page-level instructions, such as language, error pages, buffering,
etc.

Syntax:
<%@ page attribute="value" %>

Common attributes:
Attribute Description
language Language used (default is "java").
contentType MIME type of the response (e.g., "text/html").
import Java packages to import (e.g., "[Link].*").
session Whether the page uses HTTP session (default: true).
isErrorPage Indicates if this is an error page (true or false).
errorPage URL of the error page for exception handling.
buffer Buffer size (e.g., "8kb").
autoFlush Whether the buffer is automatically flushed.

Example:
<%@ page language="java" contentType="text/html" import="[Link].*, [Link].*" %>

2. <%@ include ... %> — Include Directive

BY, PALLAVI P ASSISTANT LECTURER Page 6


JAVA Lecturer Notes, S.J.V.P college, Harihar

The include directive includes a static resource at translation time (before the JSP is
compiled). This is different from the <jsp:include> action, which happens at runtime.

Syntax:
<%@ include file="relativeURL" %>

Example:
<%@ include file="[Link]" %>

This means that the content of [Link] is inserted directly into the main JSP before it is
compiled.

3. <%@ taglib ... %> — Tag Library Directive

The taglib directive is used to include a custom tag library, such as JSTL (JavaServer Pages
Standard Tag Library).

Syntax:
<%@ taglib prefix="prefixName" uri="tagLibraryURI" %>

Example:
<%@ taglib prefix="c" uri="[Link] %>

This enables you to use JSTL core tags like <c:forEach>, <c:if>, etc.

Summary Table
Directive Purpose Example
page Sets page-specific <%@ page import="[Link].*" %>
properties
include Includes static content at <%@ include file="[Link]" %>
translation time
taglib Declares tag libraries <%@ taglib prefix="c"
uri="[Link] %>

JSP Actions(include, setproperty, getproperty, forward, text)

In JSP (JavaServer Pages), JSP actions are special XML-like tags that control the runtime
behavior of the JSP page. Unlike directives, which operate at translation time, actions are
executed at runtime when the page is requested.

1. <jsp:include> — Include Action

 Purpose: Includes the output of another JSP/Servlet at runtime.


 Dynamic inclusion, unlike <%@ include %> which is static.

Syntax:
<jsp:include page="relativeURL" />

Example:
<jsp:include page="[Link]" />

BY, PALLAVI P ASSISTANT LECTURER Page 7


JAVA Lecturer Notes, S.J.V.P college, Harihar

Useful when the included content can change or depends on runtime data.

2. <jsp:setProperty> — Set JavaBean Property

 Purpose: Sets a property value in a JavaBean (POJO).


 The bean must be defined with <jsp:useBean>.

Syntax:
<jsp:setProperty name="beanName" property="propertyName" value="someValue" />

Example:
<jsp:useBean id="user" class="[Link]" scope="session" />
<jsp:setProperty name="user" property="name" value="Supriya" />

Can also automatically set properties from request parameters:


<jsp:setProperty name="user" property="*" />

3. <jsp:getProperty> — Get JavaBean Property

 Purpose: Retrieves the value of a bean property and outputs it in the response.

Syntax:
<jsp:getProperty name="beanName" property="propertyName" />

Example:
<jsp:getProperty name="user" property="name" />

Displays the value of [Link]() on the page.

4. <jsp:forward> — Forward Request

 Purpose: Forwards the current request to another resource (JSP, servlet, HTML).
 Control is transferred; no content after the forward is processed.

Syntax:
<jsp:forward page="relativeURL" />

Example:
<jsp:forward page="[Link]" />

Useful for redirecting based on conditions.

5. <jsp:text> — Raw Text Output

 Purpose: Outputs raw text as template data.


 Typically used inside tag files or with custom tags.

Syntax:
<jsp:text>

BY, PALLAVI P ASSISTANT LECTURER Page 8


JAVA Lecturer Notes, S.J.V.P college, Harihar

This will be rendered as raw text.


</jsp:text>

Example:
<jsp:text>Hello from JSP!</jsp:text>

Summary Table
Action Description Example
<jsp:include> Includes a resource at <jsp:include page="[Link]" />
runtime
<jsp:setProperty> Sets JavaBean property <jsp:setProperty name="user"
value property="name" value="Supriya" />
<jsp:getProperty> Gets and displays <jsp:getProperty name="user"
JavaBean property property="name" />
<jsp:forward> Forwards request to <jsp:forward page="[Link]" />
another page
<jsp:text> Outputs raw text <jsp:text>Hello</jsp:text>
(mainly in tag files)

Implicit objects(request, response, out, page, exception)

In JSP (JavaServer Pages), implicit objects are predefined objects created by the JSP
container. They are automatically available to every JSP page—no need to declare or
instantiate them.

1. request — HttpServletRequest Object

 Represents the client’s request to the server.


 Used to retrieve form data, request parameters, headers, cookies, etc.

Key Methods:
[Link]("username");
[Link](); // "GET", "POST", etc.
[Link]("User-Agent");

Example:
<%= [Link]("name") %>

2. response — HttpServletResponse Object

 Represents the response sent to the client.


 Used to set response headers, redirect the browser, set content type, etc.

Key Methods:
[Link]("[Link]");
[Link]("text/html");

Example:
<%

BY, PALLAVI P ASSISTANT LECTURER Page 9


JAVA Lecturer Notes, S.J.V.P college, Harihar

[Link]("Cache-Control", "no-cache");
%>

3. out — JspWriter Object

 Used to send output to the client.


 Similar to [Link] but optimized for JSP response stream.

Key Methods:
[Link]("Hello");
[Link]("World");

Example:
<%
[Link]("Welcome to JSP!");
%>

4. page — Current JSP Page (as Object)

 Refers to the current instance of the JSP page.


 Equivalent to this in Java.

Example:
<%
[Link]("This page is: " + [Link]().getName());
%>

5. exception — Throwable Object

 Available only on error pages (when isErrorPage="true" is set in <%@ page %>
directive).
 Represents the uncaught exception thrown on the JSP page.

Example:
<%@ page isErrorPage="true" %>
<%
[Link]("Error Message: " + [Link]());
%>

Summary Table
Implicit Object Class Purpose
request HttpServletRequest Get client request data
response HttpServletResponse Set response to client
out JspWriter Send content to client
page Object (this JSP page) Refers to current JSP instance
exception Throwable Exception for error pages only

Including HTML in JSP

BY, PALLAVI P ASSISTANT LECTURER Page 10


JAVA Lecturer Notes, S.J.V.P college, Harihar

Including HTML in JSP (JavaServer Pages) is very common and helps modularize the UI by
separating reusable components like headers, footers, or navigation menus.

There are two main ways to include HTML in a JSP:

1. Static Include — Using <%@ include file="..." %> (Directive)

 The content of the HTML file is copied at translation time (before JSP compilation).
 Best for static content (no dynamic logic inside the HTML).

Syntax:
<%@ include file="[Link]" %>

Example:

If you have [Link]:


<!-- [Link] -->
<h1>Welcome to My Site</h1>
<hr>

Then in your JSP:


<%@ include file="[Link]" %>
<p>This is the main content of the page.</p>

Note: The content is physically included in the JSP file before compilation.

2. Dynamic Include — Using <jsp:include page="..." /> (JSP Action)

 The content is included at runtime.


 You can include dynamic or static content.
 Useful when the included file changes often or depends on user input.

Syntax:
<jsp:include page="[Link]" />

Example:
<html>
<body>
<jsp:include page="[Link]" />
<p>Product details go here.</p>
<jsp:include page="[Link]" />
</body>
</html>

The HTML file will be processed at runtime, so updates are reflected immediately without
recompiling the JSP.

Difference Between Static and Dynamic Include


Feature <%@ include %> (Static) <jsp:include> (Dynamic)

BY, PALLAVI P ASSISTANT LECTURER Page 11


JAVA Lecturer Notes, S.J.V.P college, Harihar

Time of inclusion Translation time Request/runtime


File type Only static Can include dynamic JSP/HTML
Performance Slightly faster (compiled) Slightly slower (runtime call)
Changes reflected Requires JSP recompile Changes seen immediately

Introduction to JDBC

What is JDBC?

JDBC (Java Database Connectivity) is an API (Application Programming Interface) in


Java that allows Java programs to connect to, interact with, and perform operations on
databases.

It provides a standard interface for accessing different relational databases (like MySQL,
Oracle, PostgreSQL, etc.) using SQL.

Why Use JDBC?

 To connect Java applications to databases.


 To execute SQL queries (SELECT, INSERT, UPDATE, DELETE).
 To retrieve and process results from databases.
 To manage database transactions from Java code.

JDBC Architecture

There are two main layers:

1. JDBC API (Java side)


o Interfaces like Connection, Statement, ResultSet, etc.
2. JDBC Driver (Database side)
o Translates Java calls into database-specific calls.

Common JDBC Classes/Interfaces


Component Description
DriverManager Manages a list of database drivers.
Connection Represents a connection to the database.
Statement Used to execute SQL statements.
PreparedStatement Precompiled SQL statement (faster and secure).
ResultSet Represents the result of a query.

Steps to Use JDBC in Java

1. Load the driver class


[Link]("[Link]");

2. Establish a connection
Connection con = [Link](

BY, PALLAVI P ASSISTANT LECTURER Page 12


JAVA Lecturer Notes, S.J.V.P college, Harihar

"jdbc:mysql://localhost:3306/mydb", "root", "password");

3. Create a statement
Statement stmt = [Link]();

4. Execute SQL query


ResultSet rs = [Link]("SELECT * FROM students");

5. Process the results


while([Link]()) {
[Link]([Link]("name"));
}

6. Close connection
[Link]();

Simple Example:
import [Link].*;

public class JdbcExample {


public static void main(String[] args) {
try {
// Step 1: Load the JDBC driver
[Link]("[Link]");

// Step 2: Connect to database


Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "password");

// Step 3: Create Statement


Statement stmt = [Link]();

// Step 4: Execute Query


ResultSet rs = [Link]("SELECT * FROM users");

// Step 5: Process Results


while([Link]()) {
[Link]([Link]("id") + " " + [Link]("name"));
}

// Step 6: Close Connection


[Link]();

} catch(Exception e) {
[Link](e);
}
}
}

JDBC Driver Types

BY, PALLAVI P ASSISTANT LECTURER Page 13


JAVA Lecturer Notes, S.J.V.P college, Harihar

Type Description
Type 1 JDBC-ODBC bridge (obsolete)
Type 2 Native-API driver
Type 3 Network Protocol driver
Type 4 Pure Java driver (most common)

Summary

 JDBC is Java’s way to interact with databases using SQL.


 It provides classes and interfaces to connect, query, and update databases.
 It is platform-independent and works with any relational DB using the correct driver.

BY, PALLAVI P ASSISTANT LECTURER Page 14

You might also like