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

Unit Iv

JavaServer Pages (JSP) is a server-side technology that allows developers to create dynamic web applications by embedding Java code in HTML pages. JSP offers advantages over traditional CGI, such as improved performance, easier maintenance, and faster development, making it suitable for various applications including e-commerce, content management systems, and enterprise applications. The JSP lifecycle includes phases like translation, compilation, initialization, request processing, and destruction, with various JSP elements such as declarations, scriptlets, and expressions used to generate dynamic content.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views60 pages

Unit Iv

JavaServer Pages (JSP) is a server-side technology that allows developers to create dynamic web applications by embedding Java code in HTML pages. JSP offers advantages over traditional CGI, such as improved performance, easier maintenance, and faster development, making it suitable for various applications including e-commerce, content management systems, and enterprise applications. The JSP lifecycle includes phases like translation, compilation, initialization, request processing, and destruction, with various JSP elements such as declarations, scriptlets, and expressions used to generate dynamic content.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

UNIT IV

Introduction to JSP:
The Anatomy of a JSP
Page, JSP Processing,
Declarations,
Directives,
Expressions,
Code Snippets,
implicit
objects,
Using Beans in JSP Pages,
Using Cookies and session for session
tracking, connecting to database in JSP.

Introduction to JSP
Java Server Pages (JSP) is a server-side programming technology
that enables the creation of dynamic, platform-independent method
for building Web-based applications. JSP have access to the entire
family of Java APls, including the JDBC APl to access enterprise
databases.
JavaServer Pages (JSP) is a technology for developing Webpages
that supports dynamic content. This helps developers insert java
code in HTML pages by making use of special JSP tags, most of
which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is
designed to fulfill the role of a user interface for a Java web
application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP
actions and commands.
Using JSP, you can collect input from users through Webpage forms,
present records from a database or another source, and create
Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving
information from a database or registering user preferences,
accessing JavaBeans components, passing control between pages,
and sharing information between requests, pages etc.

Downloaded by Deepthi P
Why to Learn JSP?

JavaServer Pages often serve the same purpose as programs


implemented using the Common Gateway Interface (CGI). But
JSP offers several advantages in comparison with the CGl.

Downloaded by Deepthi P
 Performance is significantly better because JSP allows
embedding Dynamic Elements in HTML Pages itself instead of
having separate CGl files.
 JSP are always compiled before they are processed by the server
unlike CGl/Perl which requires the server to load an interpreter
and the target script each time the page is requested.
 JavaServer Pages are built on top of the Java Servlets APl, so
like Servlets, JSP also has access to all the powerful
Enterprise Java APls, including JDBC, JNDI, EJB, JAXP,
etc.
 JSP pages can be used in combination with servlets that
handle the business logic, the model supported by Java servlet
template engines.
Finally, JSP is an integral part of Java EE, a complete platform for
enterprise class applications. This means that JSP can play a part in
the simplest applications to the most complex and demanding.

Applications of JSP

As mentioned before, JSP is one of the most widely used language


over the web.
1. Dynamic Web Content
JSP is commonly used to create web pages that display dynamic content
based on user input or backend data (e.g., database content).
Example: Displaying user profile information after login.
2. Form Handling
JSP can capture and process data submitted from HTML forms.
Example: Login, registration, feedback forms.
3. E-Commerce Applications
JSP can be used to build the front-end of e-commerce sites that interact with databases
and show product listings, shopping carts, and user orders.
Example: Adding items to a cart and checking out.
4. Content Management Systems (CMS)
JSP is suitable for developing custom CMS systems where content is updated
dynamically.
Example: Blog platforms or news websites.
5. Enterprise Applications
JSP is used in enterprise web applications along with frameworks like Spring and
Hibernate.
Example: Employee portals, CRM systems, or HR management systems.
Downloaded by Deepthi P
6. Dashboard and Reporting Tools
JSP can be used to create dashboards that display data visualizations, analytics, and
reports by integrating with backend systems.
Example: Admin dashboards with charts and data tables.
7. API Front-Ends
JSP can serve as a UI layer that consumes RESTful APIs and displays the data to users.
Example: Weather apps, stock trackers.
8. Educational Platforms
Many e-learning systems use JSP for user interaction, quizzes, content delivery, etc.
Example: Online course platforms or student portals.
9. Session Management and Authentication
JSP supports session tracking and can manage user login/logout, roles, and permissions.
Example: Admin and user account segregation.
10. Email and Notification Systems
JSP can be used in systems that generate dynamic email content or send alerts based on
user actions.
Example: Confirmation emails, alerts for account activity.

Advantages of JSP over Servlet

There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use
all the features of the Servlet in JSP. ln addition to, we can use
implicit objects, predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.

2) Easy to maintain
JSP can be easily managed because we can easily separate our
business logic with presentation logic. ln Servlet technology, we mix
our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy


lf JSP page is modified, we don't need to recompile and redeploy the
project. The Servlet code needs to be updated and recompiled if we have
to change the look and feel of the application.

4) Less code than Servlet


ln JSP, we can use many tags such as action tags, JSTL, custom
tags, etc. that reduces the code. Moreover, we can use EL, implicit
Downloaded by Deepthi P
objects, etc.

The Lifecycle of a JSP Page

The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o lnstantiation (Object of the Generated Servlet is created).
o lnitialization ( the container invokes jsplnit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Downloaded by Deepthi P
Translation of JSP Page

As depicted in the above diagram, JSP page is translated into Servlet by


the help of JSP translator. The JSP translator is a part of the web
server which is responsible for translating the JSP page into Servlet.
After that, Servlet page is compiled by the compiler and gets
converted into the class file. Moreover, all the processes that happen
in Servlet are performed on JSP later like initialization, committing
response to the browser and destroy.
Example
A JSP file index.jsp is translated into a Servlet index_jsp.java (by the JSP engine).

JSP Compilation Phase:

The generated Servlet (index_jsp.java) is compiled into a .class file (bytecode).

Downloaded by Deepthi P
Downloaded by Deepthi P
When a browser asks for a JSP, the JSP engine first checks to see
whether it needs to compile the page. lf the page has never been
compiled, or if the JSP has been modified since it was last
compiled, the JSP engine compiles the page.
The compilation process involves three steps −

 Parsing the JSP.


 Turning the JSP into a servlet.
 Compiling the servlet.
Class Loading & Instantiation
The .class file (index_jsp.class) is loaded into memory and an instance is created.
Happens Automatically using the Servlet container.

JSP Initialization
When a container loads a JSP it invokes the jspInit() method before
servicing any requests.
The JSP container calls the jspInit() method once (like init() in Servlets).

<%!
public void jspInit() {
System.out.println("JSP Initialized!");
}
%>

Typically, initialization is performed only once and as with the servlet


init method, you generally initialize database connections, open files,
and create lookup tables in the jspInit method.
Request Processing (_jspService())
This phase of the JSP life cycle represents all interactions with
requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded
and initialized, the JSP engine invokes the _jspService() method in
the JSP.
Downloaded by Deepthi P
The jspService() method takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows −
<%
String user = request.getParameter("name");
out.println("Welcome, " + user);
%>

The jspService() method of a JSP is invoked on request basis. This is


responsible for generating the response for that request and this
method is also responsible for generating responses to all seven of
the HTTP methods, i.e, GET, POST, DELETE, etc.
JSP Destruction (jspDestroy())
The destruction phase of the JSP life cycle represents when a JSP is
being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method
for servlets. Override jspDestroy when you need to perform any
cleanup, such as releasing database connections or closing open files.
The jspDestroy() method has the following form −
<%!
public void jspDestroy() {
System.out.println("JSP Destroyed!");
}
%>

Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below,
and save it by .jsp extension. We have saved this file as index.jsp.
Put it in a folder and paste the folder in the web-apps directory in
apache tomcat to run the JSP page.

index.jsp
Let's see the simple example of JSP where we are using the scriptlet
tag to put Java code in the JSP page. We will learn scriptlet tag later.

<html>
<body>
<% out.print(2*5); %>
Downloaded by Deepthi P
</body>
</html>

Downloaded by Deepthi P
Output:
lO

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL
http://localhost:portno/contextRoot/jspfile, for
example,
http://localhost:8888/myapplication/index.jsp

The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We


contain the JSP page outside the WEB-lNF folder or in any
directory.

The Anatomy of a JSP Page

A JSP page is simply a regular web page with JSP elements for
generating the parts of the page that differ for each request.

Everything in the page that is not a JSP element is called template text .
Template text can really be any text: HTML, WML, XML, or even plain
text. Since HTML is by far the most common web page language in use
Downloaded by Deepthi P
today, most of the descriptions and examples in this book are HTML-
based, but keep in mind that JSP has no dependency on HTML; it can
be used with any markup language. Template text is always passed
straight through to the browser.

Downloaded by Deepthi P
When a JSP page request is processed, the template text and the
dynamic content generated by the JSP elements are merged, and the
result is sent as the response to the browser.

<%@ page import="java.io.*" %> //directive


<!DOCTYPE html>
<html>
<head>
<title>JSP Addition Example</title>
</head>
<body>
<form method="post">
Enter First Number: <input type="text" name="num1"><br><br>
Enter Second Number: <input type="text" name="num2"><br><br>
<input type="submit" value="Add">
</form>

<%!
// Declaration
int k = 0;
%>
<%
// Scriptlet: Business logic inside JSP
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");

if (num1 != null && num2 != null && !num1.isEmpty() && !


num2.isEmpty()) {
int i = Integer.parseInt(num1);
int j = Integer.parseInt(num2);
k = i + j;
}
%>
Downloaded by Deepthi P
<h3>Result: <%= k %></h3> <!-- Expression to display result -->
</body></html>s

Figure: Template text and JSP elements

Architecture

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

Downloaded by Deepthi P
JSP Processing

The following steps explain how the web server creates the Webpage using
JSP −
All the mentioned steps can be seen in the following diagram −

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 status.jsp 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.

Downloaded by Deepthi P
Typically, the JSP engine checks to see whether a servlet for a JSP
file already exists and whether the modification date on the JSP is
older than the servlet. lf the JSP is older than its generated servlet,
the JSP container assumes that the JSP hasn't changed and that the
generated servlet still matches the JSP's contents. This makes the
process more efficient than with the other scripting languages (such
as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet
without having to be a Java programming wiz. Except for the
translation phase, a JSP page is handled exactly like a regular
servlet.

Downloaded by Deepthi P
Elements of JSP/ JSP Code Snippets

JSP supports different types of code snippets to embed Java inside HTML.
The key types include:
1. JSP Declarations (<%! ... %>) → Define class-level variables/methods.
2. JSP Scriptlets (<% ... %>) → Write Java logic inside JSP.
3. JSP Expressions (<%= ... %>) → Output values dynamically.
4. JSP Directives (<%@ ... %>) → Configure JSP behavior.
5. JSP Actions (<jsp:... />) → Use predefined JSP elements.

JSP Code Snippet Purpose


JSP Declarations (<%! ..%>) Declare class-level variables/methods
JSP Scriptlet (<% ... %>) Write Java logic inside JSP
JSP Expression (<%= ... %>) Output dynamic values
JSP Directive (<%@ ... %>) Configure JSP settings
JSP Action (<jsp:... />) Use predefined JSP elements

The elements of JSP have been described below −

The Scriptlet

Downloaded by Deepthi P
A scriptlet can contain any number of JAVA language statements,
variable or method declarations, or expressions that are valid in the
page scripting language.
Following is the syntax of Scriptlet −
<% code fragment %>
You can write the XML equivalent of the above syntax as follows −
<jsp:scriptlet>
code
fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the
scriptlet. Following is the simple and first example for JSP −

Downloaded by Deepthi P
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP Scriptlet Example</title>
</head>
<body>

<%
int a = 10, b = 20;
int sum = a + b;
%>

<h2>Sum of 10 and 20 is: <%= sum %></h2>

</body>
</html>

JSP Declarations
A declaration declares one or more variables or methods that you
can use in Java code later in the JSP file. You must declare the
variable or method before you use it in the JSP file.
Following is the syntax for JSP Declarations −
<%! declaration; [ declaration; ]+ ... %>
You can write the XML equivalent of the above syntax as follows −
<jsp:declaratio
n> code
fragment
</jsp:declaration>
Following is an example for JSP Declarations −
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

Downloaded by Deepthi P
JSP Expression
A JSP expression element contains a scripting language expression
that is evaluated, converted to a String, and inserted where the
expression appears in the JSP file.
Because the value of an expression is converted to a String, you can
use an expression within a line of text, whether or not it is tagged
with HTML, in a JSP file.
The expression element can contain any expression that is valid
according to the Java Language Specification but you cannot use a
semicolon to end an expression.
Following is the syntax of JSP Expression −
<%= expression %>
You can write the XML equivalent of the above syntax as follows –
<jsp:expression>
expression
</jsp:expression>

Following example shows a JSP Expression −


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP Expression Example</title>
</head>
<body>

<h2>Current Date and Time:</h2>


<p><%= new java.util.Date() %></p> <!-- Expression to print current date/time -->

<h2>Sum of Two Numbers:</h2>


<p><%= 10 + 20 %></p> <!-- Expression calculating and displaying sum -->

</body>
</html>

JSP Comments

Downloaded by Deepthi P
JSP comment marks text or statements that the JSP container should
ignore. A JSP comment is useful when you want to hide or
"comment out", a part of your JSP page. Not visible in the client’s
browser (processed at the server-side).
Following is the syntax of the JSP comments −
<%-- This is JSP comment --%>
Following example shows the JSP Comments −

<%@ page language="java" contentType="text/html; charset=UTF-8" %>


<!DOCTYPE html>
<html>
<head>
<title>JSP Comments Example</title>
</head>
<body>

<%-- This is a JSP comment. It will not be visible in the page source. --%>

<!-- This is an HTML comment. It will be visible in the page source. -->

<h2>JSP Comments Example</h2>

<%-- JSP comment inside scriptlet --%>


<%
int num1 = 10; // Java comment (inside scriptlet)
int num2 = 20;
int sum = num1 + num2;
%>

<p>The sum of 10 and 20 is: <%= sum %></p>

</body>
</html>

Downloaded by Deepthi P
S.No. Syntax Purpose

1 <%-- comment --%> A JSP comment. lgnored by the JSP engine.

2 <!-- comment --> An HTML comment. lgnored by the browser.

3 <\% Represents static <% literal.

4 %\> Represents static %> literal.

5 \' A single quote in an attribute that uses single


quotes.
6 \" A double quote in an attribute that uses double
quotes.

There are a small number of special constructs you can use in various
cases to insert comments or characters that would otherwise be treated
specially. Here's a summary −

JSP Directives

JSP Directives are instructions to the JSP container that control the processing of JSP
pages. Directives do not produce output but affect the entire JSP page.
Directives are basically wont to configure the code that’s generated by the container
during a Servlet. JSP directives are JSP components that are used to give the
instructions to the JSP compiler. JSP directives will simplify writing JSP files. These
tags are used to give directions to the JSP page compiler. In web applications, JSP
Directives can be used to define present JSP page characteristics, to include the target
resource content into the present JSP page, and to make available user-defined tag
library into this JSP page. All the JSPdirectives are going to be resolved at the time of
translating the JSP page to the servlet. The majority of JSP Directives will not give a
direct effect to response generation.

A JSP directive affects the overall structure of the servlet class. lt usually
has

Downloaded by Deepthi P
the following form −
<%@ directive attribute="value" %>
There are three types of directive tag −

S.No. Directive & Description

<%@ page ... %> Defines page settings (language, session,


1 error handling, etc.) to import packages

2 <%@ include ... lncludes a file during the translation phase.


%>

<%@ taglib ... %> Declares a tag library, containing


3
custom actions, used in the page

JSP Page Directive


Used to set page-specific attributes, such as:
o Importing Java classes (import)
o Enabling/disabling sessions (session)
o Defining error pages (errorPage)

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

<%@ page language="java" contentType="text/html; charset=UTF-8"


session="true" %>
<%@ page import="java.util.Date" %>

<h2>Current Date & Time: <%= new Date() %></h2>

Key Attributes:

Downloaded by Deepthi P
JSP Include Directive

Used to insert a file (JSP, HTML) at compile-time.

Syntax
<%@ include file="header.jsp" %>

Example

header.jsp (Reusable Header)


<h1>Welcome to My Website</h1>
<hr>
index.jsp (Including header.jsp)
<%@ include file="header.jsp" %>
<p>Home Page Content</p>

Output:
Welcome to My Website
---------------------
Home Page Content

Example of Include Directive in JSP


logo.jsp

Downloaded by Deepthi P
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<table width="100%" height="20%" bgcolor="red">
<tr>
<td colspan="2"><center>
<b><font size="7" color="white"> Hello World </font></b>
</center></td>
</tr>
</table>
</center>
</body>
</html>

body.jsp W
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">

<title>Insert title here</title>


</head>
<body bgcolor="yellow">
<center>
<b><font size="7">
<p>
<br> Welcome!!!<br>
<br>
</p>
</font></b>
</center>
</body>

Downloaded by Deepthi P
</html>

footer.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<table width="100%" height="15%" bgcolor="blue">
<tr>
<td colspan="2"><center>
<b><font size="6" color="white"> This is footer</font></b>
</center></td>
</tr>
</table>
</center>
</body>
</html>

mainpage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-


8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@include file="logo.jsp"%>
<%@include file="body.jsp"%>
<%@include file="footer.jsp"%>
</body>
</html>

Downloaded by Deepthi P
JSP Taglib Directive(JavaServer Pages Standard Tag Library)

Used to import custom tag libraries (JSTL, custom tags).


Syntax

<%@ taglib uri="tag_library_uri" prefix="prefix_name" %>


Example (Using JSTL)
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<c:set var="message" value="Hello, JSTL!" />


<h2><c:out value="${message}" /></h2>

Example of Taglib Directives in JSP


<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>JSP Taglib Directives</title>
</head>
<body>
<c:out value="${'Welcome!!!'}" />
</body>
</html>

Addition.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Addition of Two Numbers</title>
</head>
<body>

Downloaded by Deepthi P
<h2>Addition of Two Numbers</h2>

<form method="post">
Enter First Number: <input type="text" name="num1"><br><br>
Enter Second Number: <input type="text" name="num2"><br><br>
<input type="submit" value="Add">
</form>

<%
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");

if (num1 != null && num2 != null && !num1.isEmpty() && !


num2.isEmpty()) {
try {
int number1 = Integer.parseInt(num1);
int number2 = Integer.parseInt(num2);
int sum = number1 + number2;
%>
<h3>Result: <%= sum %></h3>
<%
} catch (NumberFormatException e) {
%>
<h3 style="color: red;">Please enter valid numbers!</h3>
<%
}
}
%>
</body>
</html>

Palindrome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Palindrome Checker</title>
</head>
<body>
<h2>Palindrome Checker</h2>

Downloaded by Deepthi P
<form method="post">
Enter a Number or String: <input type="text"
name="inputText"><br><br>
<input type="submit" value="Check">
</form>

<%
// Retrieve input from the form
String inputText = request.getParameter("inputText");

if (inputText != null && !inputText.isEmpty()) {


String reversedText = new
StringBuilder(inputText).reverse().toString();

if (inputText.equalsIgnoreCase(reversedText)) {
%>
<h3 style="color: green;">"<%= inputText %>" is a
Palindrome!</h3>
<%
} else {
%>
<h3 style="color: red;">"<%= inputText %>" is NOT a
Palindrome!</h3>
<%
}
}
%>

</body>
</html>

JSP Actions
JSP actions use constructs in XML syntax to control the
behavior of the servlet engine.
Actions are used during request Processing Phase but directives
are used during translation phase.
Actions are re-evaluated every timethe Jsp is accessed.
You can dynamically insert a file, reuse JavaBeans components,
forward the user to another page, or generate HTML for the Java
plugin.

Downloaded by Deepthi P
JavaBeans are reusable Java classes that follow a specific convention and are
used in JSP applications to separate business logic from the presentation
layer.
Features of JavaBeans
Encapsulation – Private fields with public getters/setters
Serializable – Implements java.io.Serializable (optional but recommended)
No-argumentConstructor – Required for instantiation
Getter & Setter Methods – To access private properties

There is only one syntax for the Action element, as it conforms to the XML
standard −
<jsp:action_name attribute="value" />
Action elements are basically predefined functions. Following table lists out
the available JSP Actions −

S.No. Syntax Purpose

1 jsp:include lncludes a file at the time the page is requested.

2 jsp:useBean Creates or retrieves a JavaBean.

3 jsp:setProperty Sets the property of a JavaBean.

4 jsp:getProperty Retrieves a property from a JavaBean..

jsp:forward Forwards the request to another page..


5

jsp:plugin Used to embed Java applets or plugins.


6

7 jsp:element Defines XML elements dynamically.

8 <jsp:param> Passes parameters to included or forwarded pages.

9 jsp:body Defines the body content of a custom tag..

Downloaded by Deepthi P
jsp:text Used to write template text in JSP pages
10
and documents.

jsp:include

<%@ page language="java" contentType="text/html; charset=UTF-8" %>


<jsp:include page="header.jsp"/>
<p>Welcome to my website!</p>

<jsp:include page = "relative URL" flush = "true" />


Following table lists out the attributes associated with the include action −

S.No Attribut Description


. e

1 Page The relative URL of the page to be included.

Flush The boolean attribute determines whether the


2
included resource has its buffer flushed before it is
included.

<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html>

jsp:forward

index.jsp

Downloaded by Deepthi P
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<jsp:forward page="welcome.jsp"/>

welcome.jsp
<h2>Welcome to the site!</h2>

<jsp:param>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<jsp:forward page="greeting.jsp">
<jsp:param name="username" value="Alice"/>
</jsp:forward>

greeting.jsp

<h2>Welcome, <%= request.getParameter("username") %>!</h2>

<jsp:plugin>
Syntax: <jsp:plugin code=”-” width=”-” height=”-” type=”-“/>

Attributes:
1. Code: It will take the fully qualified name of the applet.
2. Width: It is used to specify the width of the applet.
3. Height: It is used to specify the height of the applet.
4. Type: It can be used to specify which one we are going to include whether it applet or bean.

<jsp:plugin type="applet" code="MyApplet.class" width="200" height="200">


<jsp:params>
<jsp:param name="message" value="Hello from JSP"/>
</jsp:params>
</jsp:plugin>

Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){

addMouseMotionListener(this);
setBackground(Color.red);

Downloaded by Deepthi P
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),20,20);
}
public void mouseMoved(MouseEvent me){}
}

index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Mouse Drag</title>
</head>
<body bgcolor="khaki">
<jsp:plugin align="middle" height="500" width="500" type="applet"
code="MouseDrag.class" name="clock" codebase="." />
</body>
</html>

JSP Implicit Objects

JSP provides 9 built-in implicit objects that do not require explicit


declaration.

These Objects are created by Web container or Web Server.

These objects help in handling requests, responses, sessions, and more.

S.No. Object Description

Request This is the HttpServletRequest object associated


1
with the request.

Downloaded by Deepthi P
Response This is the HttpServletResponse object
2
associated with the response to the client.

Out This is the PrintWriter object used to send output to


3
the client.

Session This is the HttpSession object


4
associated with the
request.

Application This is the ServletContext object associated with


5
the application context.

Config This is the ServletConfig object associated with


6
the page.

pageContex This encapsulates use of server-specific features


7 t like higher performance JspWriters.

Page This is simply a synonym for this, and is used to


8
call the methods defined by the translated servlet
class.

Exception The Exception object allows the exception data


9
to be accessed by designated JSP.

1️.request Object (Client Request Handling)

Example: Getting User Input from a Form

<form action="welcome.jsp" method="post">

Name: <input type="text" name="username">

<input type="submit" value="Submit">

</form>

welcome.jsp (Using request)

<%@ page language="java" contentType="text/html; charset=UTF-8" %>

Downloaded by Deepthi P
<%

String name = request.getParameter("username");

%>

<h2>Welcome, <%= name %>!</h2>

2. response Object (Sending Output & Redirects)

Example: Redirecting to Another Page

<%

response.sendRedirect("home.jsp");

%>

3. session Object (User Session Management)

Example: Storing User Data in Session

<%

session.setAttribute("user", "John Doe");

%>

Retrieve Data in Another Page

<%

String user = (String) session.getAttribute("user");

%>

<h2>Welcome, <%= user %>!</h2>

4. application Object (Global Data Sharing)

Example: Storing Application-Wide Data

<%

application.setAttribute("appName", "JSP Learning");

%>

Downloaded by Deepthi P
Retrieve Data in Any Page

<%= application.getAttribute("appName") %>

5.out Object (Printing Output)

Example: Using out.println()

<%

out.println("<h2>Hello, JSP!</h2>");

%>

6. config Object (Servlet Configuration)

Example: Get Servlet Name

<%= config.getServletName() %>

7.pageContext Object (Page Attributes & Controls)

Example: Set & Get Attributes

<%

pageContext.setAttribute("message", "Hello JSP!");

%>

<h2><%= pageContext.getAttribute("message") %></h2>

8.page Object (Refers to the Current Page)

Example: Print Page Class Name

<%= page.getClass().getName() %>

9. exception Object (Error Handling)

Example: Display Exception Message

<%@ page isErrorPage="true" %>

<h2>Error: <%= exception.getMessage() %></h2>

Downloaded by Deepthi P
Control-Flow Statements
You can use all the APls and building blocks of Java in your JSP
programming including decision-making statements, loops, etc.

Downloaded by Deepthi P
Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the
Scriptlet is closed at each line with HTML text included between the
Scriptlet tags.
<%! int day = 3; %>
<html>
<head><title>lF...ELSE Example</title></head>
<body>
<% if (day == 1 || day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body>
</html>

The above code will generate the following result −


Today is not weekend
Now look at the following switch...case block which has been written a bit
differentlty using out.println() and inside Scriptletas −
<%! int day = 3; %>
<html>
<head><title>SWlTCH...CASE Example</title></head>
<body>
<%
switch(day)
{
case 0:
out.println("lt\'s Sunday.");
break;
case 1:
out.println("lt\'s Monday.");
break;
case 2:
out.println("lt\'s Tuesday.");
break;
case 3:
out.println("lt\'s Wednesday.");
break;
case 4:
out.println("lt\'s Thursday.");
break;
Downloaded by Deepthi P
case 5:
out.println("lt\'s Friday.");
break;
default:
out.println("lt's Saturday.");
}
%>
</body>
</html>

The above code will generate the following result −


lt's Wednesday.

Loop Statements
You can also use three basic types of looping blocks in Java: for, while, and
do…while blocks in your JSP
programming. Let us look at the
<%! int fontSize; %>
<html>
<head><title>FOR LOOP Example</title></head>
<body>
<% for ( fontSize = 1; fontSize <= 3; fontSize++) { %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<% } %>
</body>
</html>
following for loop example −

The above code will generate the following result −


JSP Tutorial

JSP Tutorial

JSP Tutorial
Above example can be written using the while loop as follows −

Downloaded by Deepthi P
<%! int fontSize; %>

Downloaded by Deepthi P
<html>
<head><title>WHlLE LOOP Example</title></head>
<body>
<% while ( fontSize <= 3) { %>
<font color = "green" size = "<%= fontSize %>"> JSP Tutorial
</font><br />
<% fontSize++; %>
<% } %>
</body>
</html>

The above code will generate the following result −


JSP Tutorial

JSP Tutorial

JSP Tutorial

JSP Operators
JSP supports all the logical and arithmetic operators supported by
Java. Following table lists out all the operators with the highest
precedence appear at the top of the table, those with the lowest
appear at the bottom.
Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Downloaded by Deepthi P
Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

JSP Literals
The JSP expression language defines the following literals −
 Boolean − true and false
 Integer − as in Java
 Floating point − as in Java
 String − with single and double quotes; " is escaped as \", ' is
escaped as \', and \ is escaped as \\.
 Null − null

Using Beans in JSP Pages

What is JavaBeans in JSP? Bean means component. Components mean reusable


objects. JavaBean is a reusable component. Java Bean is a normal java class that may declare
properties, setter, and getter methods in order to represent a particular user form on the
server-side.
It's often used in JSP (JavaServer Pages) and MVC architecture to hold or transfer data
between layers (like from the JSP to a servlet or database).

JavaBean is a java class that is developed with a set of


conventions. The conventions are:

Downloaded by Deepthi P
To be considered a JavaBean, a class should:
1. Have a public no-argument constructor
2. Have private properties/fields (also called variables)
3. Have public getter and setter methods to access those fields
4. Should not contain any business logic (it's just a data holder)

Note: setter method is useful to set data to bean property whereas the getter method is useful to
read data from bean property.
Java Bean is useful to combine multiple simple values to an object and to send that object
from one resource to another resource or one layer to another layer. For example, to keep
form data into a single object we can use java bean. Java Bean is a specially constructed Java
class written in Java and coded according to the Java Beans API specification.

Why use JavaBeans in JSP?


 Clean separation of logic and presentation
 Easily integrated using <jsp:useBean>, <jsp:setProperty>, and <jsp:getProperty>
 Follows MVC design pattern
 Reusable and easy to maintain
Working of JavaBeans in JSP

First, the browser sends the request for the JSP page. Then the JSP page accesses Java Bean
and invokes the business logic. After invoking the business logic Java Bean connects to the
database and gets/saves the data. At last, the response is sent to the browser which is generated
by the JSP.

Downloaded by Deepthi P
Advantages of Java Beans
1. It is easy to reuse the software components.
2. The properties and methods of Java Bean can be exposed to another application.

Disadvantages of Java Beans


1. JavaBeans are mutable objects so it cannot take advantage of immutable objects.
2. JavaBeans will be in an inconsistent state because of creating the setter and getter method for
each property separately.

Java Bean Properties


1. getPropertyName(): This method is used to read the property which is also called accessor.
2. setPropertyName(): This method is used to write the property which is also called mutator.

How to access JavaBeans in JSP Application?

Syntax: <jsp:useBean id=”—” class”—” type”—” scope=”—”/>


Attributes:
1. Id: It will take a variable to manage generated Bean object reference.

Downloaded by Deepthi P
2. Class: This attribute will take the fully qualified name of the Bean class.
3. Type: It will take the fully qualified name of the Bean class to define the type of variable in
order to manage the Bean object reference.
4. Scope: It will take either of the JSP scopes to the Bean object.

EXAMPLE:
<jsp:useBean id="user" class="your_package.User" scope="session" />

<jsp:setProperty>
The jsp:setProperty tag is utilized to set a property in the JavaBean object. The principle
motivation
behind jsp:setProperty tag is to execute a specific setter technique to set an incentive to a
specific Bean
property.

Syntax: <jsp:setProperty name=”—” property=”—” value=”—”/>

Attributes:
1. Name: It will take a variable that is the same as the id attribute value in <jsp:useBean> tag.
2. Property: It will take a property name in order to access the respective setter method.
3. Value: It will take a value to pass as a parameter to the respective setter method.

Example:
<jsp:setProperty name="user" property="name" value="Alice" />
<jsp:setProperty name="user" property="age" value="25" />

Downloaded by Deepthi P
<jsp:getProperty>
The jsp:getProperty tag is utilized to get indicated property from the JavaBean object. The
principle
reason for <jsp:getProperty> tag is to execute a getter strategy to get an incentive from the Bean
object.

Syntax: <jsp:getProperty name=”—” property=”—”/>

Attributes:

1. Name: It will take a variable that is the same as the id attribute value in <jsp:useBean> tag.
2. Property: It will take a particular property to execute the respective getter method.

Example:

<p>Name: <jsp:getProperty name="user" property="name" /></p>


<p>Age: <jsp:getProperty name="user" property="age" /></p>

JSP JavaBeans Example


In this example, we have created a Simple Bean class Test.java and index.jsp page which loads
the bean and sets/gets a simple String Parameter.

Test.java

package Action;
public class Test {

Downloaded by Deepthi P
private String message = "No message specified";
public String getMessage() {
return (message);
}
public void setMessage(String message) {
this.message = message;
}
}

index.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id="test" class="Action.Test" />
<jsp:setProperty name="test" property="message" value="Hello JSP..." />
<p>Got message....</p>
<jsp:getProperty name="test" property="message" />
</body>
</html>

Output: Got message….


“Hello JSp…”

Downloaded by Deepthi P
StudentsBean.java

package Beans;

public class StudentsBean {


private String firstName;
private String lastName;
private int age;

public StudentsBean() {}

public String getFirstName() {


return firstName;
}

public String getLastName() {


return lastName;
}

public int getAge() {


return age;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public void setLastName(String lastName) {

Downloaded by Deepthi P
this.lastName = lastName;
}

public void setAge(int age) {


this.age = age;
}
}

Index.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>


<html>
<head><title>Student Bean Example</title></head>
<body>

<h2>Student Bean Example</h2>

<jsp:useBean id="student" class="Beans.StudentsBean" />

<jsp:setProperty name="student" property="firstName" value="saritha" />


<jsp:setProperty name="student" property="lastName" value="Kambhampati" />
<jsp:setProperty name="student" property="age" value="38" />

<p><b>First Name:</b> <jsp:getProperty name="student" property="firstName" /></p>


<p><b>Last Name:</b> <jsp:getProperty name="student" property="lastName" /></p>
<p><b>Age:</b> <jsp:getProperty name="student" property="age" /></p>

</body>
</html>

Output:

Downloaded by Deepthi P
Student Bean Example
First Name: saritha

Last Name: Kambhampati

Age: 38

Using Cookies in jsp:

Cookies are text files stored on the client computer and they are kept for various information tracking purposes.
JSP transparently supports HTTP cookies using underlying servlet technology.

There are three steps involved in identifying and returning users

 Server script sends a set of cookies to the browser. For example, name, age, or identification
number, etc.
 Browser stores this information on the local machine for future use.
 When the next time the browser sends any request to the web server then it sends those cookies
information to the server and server uses that information to identify the user or may be for some
other purpose as well.

The Anatomy of a Cookie

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A
JSP that sets a cookie might send headers that look something like this −

HTTP/1.1 200 OK
Date: Fri, 11 April 2024 21:03:38 GMT

Downloaded by Deepthi P
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Saturday, 12-april-07 22:03:38 GMT;
path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the browser
to "forget" the cookie after the given time and date.

JSP Cookies Methods

 Public void setDomain(String domain)


This JSP set cookie is used to set the domain to which the cookie applies
 Public String getDomain()
This JSP get cookie is used to get the domain to which cookie applies
 Public void setMaxAge(int expiry)
It sets the maximum time which should apply till the cookie expires
 Public intgetMaxAge()
It returns the maximum age of cookie in JSP
 Public String getName()
It returns the name of the cookie
 Public void setValue(String value)
Sets the value associated with the cookie
 Public String getValue()
Get the value associated with the cookie
 Public void setPath(String path)
This set cookie in JSP sets the path to which cookie applies
 Public String getPath()
It gets the path to which the cookie applies
 Public void setSecure(Boolean flag)
It should be sent over encrypted connections or not.
 Public void setComment(String cmt)
It describes the cookie purpose
 Public String getComment()
It the returns the cookie comments which has been described.

How to Handle Cookies in JSP

1. Creating the cookie object


2. Setting the maximum age
3. Sending the cookie in HTTP response headers

Downloaded by Deepthi P
Step 1: Creating a Cookie object

You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

Step 2: Setting the maximum age

You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code
will set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24);

Step 3: Sending the Cookie into the HTTP response headers

You use response.addCookie to add cookies in the HTTP response header as follows

response.addCookie(cookie);

Deleting a Cookie

<%
Cookie deleteCookie = new Cookie("username", "");
deleteCookie.setMaxAge(0); // Deletes it
response.addCookie(deleteCookie);
%>

Example

setCookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<%
String username = "Saritha";
Cookie userCookie = new Cookie("username", username);
userCookie.setMaxAge(60 * 60 * 24); // 1 day
response.addCookie(userCookie);
%>
<html>
<head><title>Set Cookie</title></head>
<body>
<h2>Cookie has been set for user: <%= username %></h2>
<a href="getCookie.jsp">Go to Get Cookie</a>
</body>
</html>

Downloaded by Deepthi P
getCookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<%
String username = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
username = cookie.getValue();
}
}
}
%>
<html>
<head><title>Get Cookie</title></head>
<body>
<%
if (username != null) {
%>
<h2>Welcome back, <%= username %>!</h2>
<%
} else {
%>
<h2>No username cookie found.</h2>
<%
}
%>
<a href="deleteCookie.jsp">Delete Cookie</a>
</body>
</html>

deleteCookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<%
Cookie deleteCookie = new Cookie("username", "");
deleteCookie.setMaxAge(0); // delete immediately
response.addCookie(deleteCookie);
%>
<html>
<head><title>Delete Cookie</title></head>
<body>

Downloaded by Deepthi P
<h2>Cookie has been deleted.</h2>
<a href="getCookie.jsp">Try Getting Cookie Again</a>
</body>
</html>

session for session tracking in jsp

HTTP is a "stateless" protocol which means each time a client retrieves a Webpage, the client
opens a separate connection to the Web server and the server automatically does not keep any record of
previous client request.
a common way to maintain user data across multiple pages during a user's visit (session).

What is a session in JSP?

Downloaded by Deepthi P
 Each user gets a unique session when they visit your site.
 Data stored in the session is accessible across all pages for that user.
 JSP gives access to session via the implicit session object.

Session Tracking Techniques

Cookies

A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests
from the client they can be recognized using the received cookie.

This may not be an effective way as the browser at times does not support a cookie. It is not
recommended to use this procedure to maintain the sessions.

Hidden Form Fields

A web server can send a hidden HTML form field along with a unique session ID as follows −

<input type = "hidden" name = "sessionid" value = "12345">

This entry means that, when the form is submitted, the specified name and value are automatically
included in the GET or the POST data. Each time the web browser sends the request back,
the session_id value can be used to keep the track of different web browsers.

This can be an effective way of keeping track of the session but clicking on a regular (<A HREF...>)
hypertext link does not result in a form submission, so hidden form fields also cannot support general
session tracking.

URL Rewriting

You can append some extra data at the end of each URL. This data identifies the session; the server can
associate that session identifier with the data it has stored about that session.

For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is


attached as sessionid = 12345 which can be accessed at the web server to identify the client.

URL rewriting is a better way to maintain sessions and works for the browsers when they don't support
cookies. The drawback here is that you will have to generate every URL dynamically to assign a session
ID though page is a simple static HTML page.

The session Object

Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface.
This interface provides a way to identify a user across.
 a one page request or
 visit to a website or
 store information about that user

By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each

Downloaded by Deepthi P
new client automatically. Disabling session tracking requires explicitly turning it off by setting the page
directive session attribute to false as follows −
<%@ page session = "false" %>

The JSP engine exposes the HttpSession object to the JSP author through the implicit session object.
Since session object is already provided to the JSP programmer, the programmer can immediately begin
storing and retrieving data from the object without any initialization or getSession().

Here is a summary of important methods available through the session object

Method Description

setAttribute(String name, Object value) Stores an object in the session, accessible by name.
getAttribute(String name) Retrieves an object from the session. Returns null if not found.
removeAttribute(String name) Removes an object from the session.
invalidate() Destroys the session completely. All data is lost.
getId() Returns the unique session ID assigned to the user.
getCreationTime() Returns the time when the session was created.
getLastAccessedTime() Returns the last time the client accessed the session.
isNew() Returns true if the session is newly created.
getMaxInactiveInterval() Gets the time (in seconds) the session will remain active without access.
Sets the session timeout
setMaxInactiveInterval(int seconds)
interval (in seconds).

Example:

login.jsp (Set session attribute)

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%
String username = request.getParameter("username");

if (username != null && !username.isEmpty()) {


session.setAttribute("username", username);
response.sendRedirect("dashboard.jsp");
}
%>
<html>
<head><title>Login</title></head>
<body>
<h2>Login</h2>
<form method="post" action="login.jsp">
Username: <input type="text" name="username" required />
<input type="submit" value="Login" />

Downloaded by Deepthi P
</form>
</body>
</html>

dashboard.jsp (Read session attribute)

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%
String username = (String) session.getAttribute("username");
if (username == null) {
response.sendRedirect("login.jsp");
return;
}
%>
<html>
<head><title>Dashboard</title></head>
<body>
<h2>Welcome, <%= username %>!</h2>
<p>This is your dashboard.</p>
<a href="logout.jsp">Logout</a>
</body>
</html>

logout.jsp (Invalidate session)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<%
session.invalidate(); // End the session
%>
<html>
<head><title>Logout</title></head>
<body>
<h2>You have been logged out.</h2>
<a href="login.jsp">Login Again</a>
</body>
</html>

Downloaded by Deepthi P
connecting to database in JSP

1.Import required packages


2. Load the JDBC Driver
3. Create a Connection to the Database
4. Create a Statement and Execute a Query
5. Close the Connection

Import required packages

<%@ page import="java.sql.*" %>

Load the JDBC Driver

Class.forName("com.mysql.cj.jdbc.Driver");

Create a Connection to the Database

Downloaded by Deepthi P
<%
String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
String username = "yourUsername";
String password = "yourPassword";

Connection conn = DriverManager.getConnection(url, username, password);


%>

Create a Statement and Execute a Query

<%
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
%>

Or for insert/update:
int rows = stmt.executeUpdate("INSERT INTO students(name, age) VALUES('John', 20)");

Close the Connection

<%
rs.close();
stmt.close();
conn.close();
%>

Common JDBC Driver Classes

Database JDBC Driver Class


MySQL com.mysql.cj.jdbc.Driver
PostgreSQL org.postgresql.Driver
Oracle oracle.jdbc.driver.OracleDriver
SQL Server com.microsoft.sqlserver.jdbc.SQLServerDriver

Javax.sql.* package

The javax.sql package is an extension of the java.sql package, and it provides advanced JDBC features
primarily for enterprise-level applications. It's commonly used in Java EE (Jakarta EE) applications and
provides support for connection pooling, distributed transactions, and row sets.

Downloaded by Deepthi P
Key Interfaces in javax.sql:

DataSource: An alternative to DriverManager for obtaining a connection. Supports connection pooling and is
more suitable for enterprise apps.

ConnectionPoolDataSource : Used by a connection pool manager to create pooled connections

PooledConnection : Represents a physical DB connection that can be reused (used with connection pooling).

XADataSource: Supports distributed transactions across multiple resources.

RowSet: A wrapper around ResultSet with more flexibility; can be used in disconnected mode.

JdbcRowSet, CachedRowSet: Implementations of RowSet for scrollable and updatable result sets.

Java.sql.*package

The java.sql package in Java is part of the JDBC API (Java Database Connectivity), which provides the
necessary classes and interfaces to interact with relational databases. It's commonly used for tasks like
connecting to a database, executing SQL queries, and retrieving results.

Key Components of java.sql Package:

Downloaded by Deepthi P

You might also like