Java EE Programming Overview Guide
Java EE Programming Overview Guide
RUCHI, AP
Introduction Java EE
Programming
MODULE 2
NMITD, DR. RUCHI, AP
2 Table of content
• Introduction Java EE Programming
• JSP Architecture
• JSP building blocks
• Scripting Tags
• implicit object
• Introduction to Bean
• standard actions
• session tracking types and methods
• Custom Tags
• Introduction to JSP Standard Tag Library (JSTL) and JSTL Tags.
• Self-learning topics Simple Application using Servlet
NMITD, DR. RUCHI, AP
3 Reference books
■ Core Servlets and Java Server Pages :Vol I: Core
Technologies 2/e , Marty Hall and Larry Brown, Pearson
,ISBN: 9788131701638, 8131701638
■ Java Server Programming java EE6, Black book, Dreamtech
press. ISBN-10: 8177229362 / ISBN-13: 978-8177229363
■ Java Enterprise in a Nutshell, 3rd Edition A Practical Guide,
Jim Farley, William Crawford, O'Reilly ISBN-13: 978-
0596101428 / ISBN-10: 0596101422
■ Web reference: [Link]
NMITD, DR. RUCHI, AP
4 Java EE
• The Java EE stands for Java Enterprise Edition, earlier known as J2EE and is currently known as
Jakarta EE.
• J2EE, also known as Java EE (Java Enterprise Edition), is an extension of Java SE, tailored for
developing large-scale, distributed, and multi-tiered enterprise applications.
• It includes additional libraries and APIs for web and server-side applications, such as servlets, Java
Server Pages (JSP), Enterprise JavaBeans (EJB), and Java Message Service (JMS).
• J2EE builds upon the core J2SE libraries, supporting features like web services, transactions, and
distributed computing.
• It provides support for multi-tier applications: presentation layer (web interface), business logic
layer (EJB), and data layer (JPA for persistence).
NMITD, DR. RUCHI, AP
7 Containers
• Containers are the interface
between a component and the low-
level platform-specific functionality
that supports the component.
• Before a web, enterprise bean, or
application client component can be
executed, it must be assembled into
a Java EE module and deployed into
its container.
NMITD, DR. RUCHI, AP
8
web server
• A web server is a software or hardware
system that serves web content to clients
over the internet or an intranet.
• Its main function is to deliver HTML
pages and other types of files (such as
images, CSS, and JavaScript) in response
to requests from web browsers or
applications.
• Web servers are essential for hosting
websites, APIs, and web applications.
NMITD, DR. RUCHI, AP
10
NMITD, DR. RUCHI, AP
11 Application Server
• An application server is a software framework that
provides an environment for running and
managing applications.
• Unlike a web server, which primarily handles HTTP
requests for static and simple dynamic content, an
application server is responsible for executing
business logic, managing transactions, and providing
additional services needed by complex, data-driven
applications.
• It enables applications to communicate with
databases, web services, and other external systems to
deliver content and perform complex processing.
NMITD, DR. RUCHI, AP
Apache
[Link]
Tomcat
JBoss EAP
GlassFish
/ WildFly
IBM WebLogic
WebSphere Server
NMITD, DR. RUCHI, AP
14
15
•Data Layer (Persistence Layer) •Integration Layer (Optional)
•Role: Manages data storage and •Role: Manages communication
retrieval. between different systems or services.
•Components: Database servers •Components: APIs, message queues,
(SQL/NoSQL), file systems, or other integration platforms.
storage systems. •Responsibilities: Handling
•Responsibilities: Storing data, communication between the business
executing queries, and providing data to logic layer and external systems, such as
the business logic layer. third-party services or microservices.
•Technology: MySQL, PostgreSQL, •Technology: REST APIs, SOAP,
Oracle, MongoDB, Redis, file systems. Kafka, RabbitMQ, GraphQL.
NMITD, DR. RUCHI, AP
16
NMITD, DR. RUCHI, AP
21 Java SE vs Java EE
Java SE Java EE
Java SE provide basic functionalities such as Java EE facilitates development of large scale
defining types and objects. applications.
SE is a normal Java specification EE is built upon Java SE. It provides
functionalities like web applications, and Servlets.
It has features like class libraries, deployment Java EE is a structured application with a
environments, etc. separate client, business, and Enterprise layers.
It is mostly used to develop APIs for Desktop It is mainly used for developing web applications.
Applications like antivirus software, game, etc.
Suitable for beginning Java developers. Suitable for experienced Java developers who
build enterprise-wide applications.
22
• JavaBeans: JSP can work with JavaBeans, which are reusable, encapsulated Java objects used to
store and manage data. JavaBeans can be easily accessed and manipulated in JSP pages.
• Expression Language (EL): JSP also supports an Expression Language (EL), which simplifies the
process of accessing Java objects, properties, and methods within JSP pages. EL expressions are
enclosed in ${}.
• Tag Libraries: JSP supports custom tag libraries, which are collections of pre-built tags that provide
high-level functionality for common tasks, such as database access, iteration, and conditional
statements.
NMITD, DR. RUCHI, AP
27
NMITD, DR. RUCHI, AP
28 Java Servlet
• Servlet is a technology which is used to create a web application.
• Servlet is an API that provides many interfaces and classes including documentation.
• Servlets are the Java programs that run on the Java-enabled web server or application server.
• They are used to handle the request obtained from the webserver, process the request, produce
the response, then send a response back to the webserver.
• Servlet is a class that extends the capabilities of the servers and responds to the incoming requests.
It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a dynamic web page.
• Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
• Java Servlets often serve the same purpose as programs implemented using the Common Gateway
Interface (CGI).
NMITD, DR. RUCHI, AP
• Process
• Loading a Servlet.
• Initializing the Servlet.
• Request handling.
• Destroying the Servlet
NMITD, DR. RUCHI, AP
• Servlet De-Initialization:
• If the servlet container decides to unload the servlet (e.g., during application shutdown or
if the servlet has been idle for a long time), it calls the destroy() method of the servlet.
• The destroy() method is typically used for cleanup tasks, such as closing database
connections or releasing other resources acquired during initialization.
34 JSP Architecture
• JSP architecture is a 3-tier architecture that separates
a web application's presentation, logic, and data
layers.
• The presentation layer, or client side, is responsible
for displaying the user interface and handling user
interaction.
• The logic layer, or server-side, is responsible for
processing user requests and handling business logic.
• The data layer is responsible for storing and
retrieving data from a database or other storage
system.
35
NMITD, DR. RUCHI, AP
36 Servlet Vs JSP
NMITD, DR. RUCHI, AP
37 Servlet Vs JSP
NMITD, DR. RUCHI, AP
• <body> • <%
40
• <!-- Declaration Tag Example --> • Date date = new Date();
• <%! • [Link]("Current Time is "+date);
• int i = 15; • %>
• String name = "Jwalant"; • </body>
• %>
• <!-- Expression Tag Example -->
• Name: <%=name %>
•
• <!-- Scriptlet Example -->
NMITD, DR. RUCHI, AP
41
Directives
JSP Directives
JSP directives are used for controlling the processing of a JSP page.
Directives provide information to the server on how the page should be
processed.
JSP directive affects the overall structure of the servlet that results from the JSP
page.
<%@ directive attribute="value" %>
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
1) Page Directive
2) Include Directive
3) TagLib Directive
Page directive
■ The page directive lets you control the structure of the servlet by importing
classes, customizing the servlet superclass, setting the content type, and the like.
■ A page directive can be placed anywhere within the document
■ There are several attributes, which are used along with Page Directives and these are –
*Import *Session
*isErrorPage *errorPage
*ContentType *isThreadSafe
*extends *info
*language *autoflush
*buffer
NMITD, DR. RUCHI, AP
44 example
• <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%> // UTF-8," which stands for "Unicode Transformation Format - 8-bit."
• <!DOCTYPE html>
• <html>
• <head>
• <title>Page Directive Example</title>
• </head>
• <body>
• <!-- JSP content here -->
• </body>
• </html>
import:
• This attribute is used to import packages. While doing coding you may
need to include more than one packages, In such scenarios this page
directive’s attribute is very useful as it allows you to mention more than
one packages at the same place separated by commas (,).
• Syntax of import attribute –
<%@page import="value"%>
Here value is package name.
For Example
<%@page import="[Link].*"%>
<%@page import="[Link].*"%>
<%--Comment: OR Below Statement: Both are Same--
%> <%@page import="[Link].*, [Link].*"%>
session:
• session attribute defines whether the JSP page is participating in
an HTTP session. The value is either true or false.
• Default value for session attribute is true, which means if you do not
mention this attribute, server may assume that HTTP session is
required for this page.
• Syntax of session attribute:
<%@ page session="value"%>
Fore Example
<%@ page session="true"%>
isErrorPage:
• isErrorPage attribute declares whether the current
JSP Page represents another JSP's error page.
• Syntax of isErrorPage attribute:
<%@ page isErrorPage="value"%>
Here value is either true OR false. For example
<%@ page isErrorPage="true"%>
errorPage
• errorPage attribute indicates another JSP page that will handle all the run time
exceptions thrown by current JSP page. It specifies the URL path of another page to
which a request is to be dispatched to handle run time exceptions thrown by current JSP
page.
The errorPage attribute specifies a JSP page that should process any exceptions (i.e., something of type
Throwable) thrown but not caught in the current page
• Syntax of errorPage attribute:
<%@ page errorPage="value"%>
• Here value is a JSP page name which has exception handling code (and isErrorPage set
to true).For example
<%@ page errorPage="[Link]"%>
The exception thrown will be automatically available to the designated error page by means of the
exception variable.
contentType:
This attribute is used to set the content type of a JSP page. Default value:
text/html
Syntax of contentType attribute:
<%@ page contentType="value"%>
here value of content type can be anything such as: text/html, text/xml etc.
<%@ page contentType="text/html"%>
for text/xml based pages:
<%@ page contentType="text/xml"%>
isThreadSafe:
• isThreadSafe attribute declares whether the JSP is thread- safe. The value is
either true or false
Default value for isThreadSafe attribute: true. Syntax of
isThreadSafe attribute:
<%@ page isThreadSafe="value"%>
here value can be true OR [Link] example
<%@ page isThreadSafe="false"%>
• With normal servlets, simultaneous user requests result in multiple threads concurrently
accessing the service method of the same servlet instance.
• This behavior assumes that the servlet is thread safe; that is, that the servlet synchronizes
access to data in its fields so that inconsistent values will not result from an unexpected
ordering of thread execution
• The isThreadSafe attribute controls whether or not the
servlet that results from the JSP page will implement the
SingleThreadModel interface.
• If a servlet implements the SingleThreadModel
interface, the system guarantees that there will not be
simultaneous access to the same servlet instance.
• The system can satisfy this guarantee either by
queuing up all requests and passing them to the same
servlet instance or by creating a pool of instances, each
of which handles a single request at a time.
buffer:
This attribute is used to specify the buffer size. If you specify this to none
during coding then the output would directly written to Response object by
JSPWriter. And, if you specify a buffer size then the output first written to
buffer then it will be available for response object.
Syntax of buffer attribute:
<%@ page buffer="value"%>
value is size in kb or none. For Example No buffer for this
page:
<%@ page buffer="none"%>
5 kb buffer size for the page, which has below code:
<%@ page buffer="5kb"%>
extends:
Like java, here also this attribute is used to extend(inherit) the
class.
Syntax of extends attribute:
<%@ page extends="value"%>
Value is package_name.class_name. For Example
The below code will inherit the SampleClass from package:
mypackage
<%@ page extends="[Link]"%>
<%@ page extends="[Link]"%>
info:
It provides a description to a JSP page. The string specified
in info will return when we will call getServletInfo()
method.
Syntax of info:
<%@ page info="value"%>
here value is Message or Description for Example
<%@ page info="This code is given by TIMSCDR"%>
language:
It specifies the scripting language( underlying language) being
used in the page.
Syntax of language:
<%@ page language="value"%>
value is scripting language For Example
<%@ page language="java"%>
autoFlush:
If it is true it means the buffer should be flushed whenever it is full. false will
throw an exception when buffer overflows.
Default value: True Syntax of
autoFlush:
<%@ page autoFlush="value"%>
value can be true or false. For Example Buffer will be
flushed out when it is full –
<%@ page autoFlush="true"%>
It will throw an exception when buffer is full due to overflow condition
<%@ page autoFlush=“false"%>
2) Include Directive
Include directive is used to copy the content of one JSP page to
another. It’s like including the code of one file into another.
Syntax of Include Directive:
<%@include file ="value"%>
here value is the JSP file name which needs to be included. If the
file is in the same directory then just specify the file name otherwise
complete URL(or path) needs to be mentioned in the value field.
Note: It can be used anywhere in the page.
<%@include file="[Link]"%>
NMITD, DR. RUCHI, AP
58 Example
• <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%>
• <!DOCTYPE html>
• <html>
• <head>
• <title>Include Directive Example</title>
• </head>
• <body>
• <%@ include file="[Link]" %>
• <!-- Rest of the content -->
• </body>
• </html>
3) Taglib Directive
This directive basically allows user to use Custom tags in JSP. It helps
you to declare custom tags in JSP page.
Syntax of Taglib Directive:
<%@taglib uri ="taglibURI" prefix="tag prefix"%>
Where URI is uniform resource Identifier, which is used to identify the location of custom
tag and tag prefix is a string which can identify the custom tag in the location identified by
uri.
Example of Targlib:
60 Example
• <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
• <%@ taglib uri="[Link] prefix="custom" %>
• <!DOCTYPE html>
• <html>
• <head>
• <title>Taglib Directive Example</title>
• </head>
• <body>
• <custom:myCustomTag attribute1="value1" attribute2="value2" />
• <!-- Rest of the content -->
• </body>
• </html>
NMITD, DR. RUCHI, AP
61
Implicit Object
NMITD, DR. RUCHI, AP
62 Implicit Object
• These Objects are the Java objects that the JSP Container makes
available to the developers in each page.
• The developer can call them directly without being explicitly
declared.
• JSP Implicit Objects are also called pre-defined variables.
• These objects may be accessed as built-in variables via scripting
elements and can also be accessed programmatically by
JavaBeans and Servlets.
NMITD, DR. RUCHI, AP
9. out: This is the PrintWriter object where methods like print and println help display the content to the client.
Using servlet
Using JSP
out <html>
72 RESPONSE METHOD
• Setting Response Headers: • %>
• [Link](String name, String • Sending Data to the Client:
value): Sets an HTTP response header with
• [Link](): Returns a PrintWriter
the given name and value.
that can be used to send character data (e.g.,
• <% HTML) to the client.
• [Link]("Content-Type", • [Link](): Returns an
"text/html"); OutputStream that can be used to send binary
data to the client.
• %>
• <%
• Setting the Character Encoding:
• PrintWriter out = [Link]();
• [Link](String
charset): Sets the character encoding of the • [Link]("Hello, World!");
response.
• %>
• <%
• [Link]("UTF-8");
NMITD, DR. RUCHI, AP
[Link]
<html>
<body>
<%
String name=(String)[Link]
bute(“UName“,
pageContext.SESSION_SCOPE,);
[Link]("Hello "+name);
%>
</body>
</html>
Page
91
Why we need JSTL
• Separation of Concerns: JSTL helps in maintaining a clear separation of concerns within web
applications. It encourages developers to separate the presentation logic (JSP) from the business
logic, making the code more organized and easier to maintain. JSTL tags allow you to embed
presentation-related logic directly in JSP pages without mixing it with Java code.
• Code Reusability: JSTL promotes code reusability. You can use standard JSTL tags in multiple JSP
pages, reducing duplication of code and effort.
• Readability: JSTL tags make JSP pages more readable and understandable, especially for those
who might not be as familiar with Java code. This can help in team collaboration and ease of
maintenance.
• Reduction in Scriptlets: Without JSTL, JSP pages often contain scriptlets, which are blocks of Java
code embedded within the JSP. Using scriptlets can make JSP pages less maintainable and
harder to read. JSTL reduces the need for scriptlets by providing tag-based constructs for common
tasks.
92
• Security: JSTL helps mitigate security risks associated with unvalidated user inputs. It
provides tag libraries for escaping output, which can help protect against Cross-Site
Scripting (XSS) attacks.
• Internationalization and Localization: JSTL provides formatting tags for numbers, dates,
and times. This is important for creating web applications that need to be accessible in
different languages and regions, as it allows for locale-sensitive formatting.
• Simplifies Database Operations: JSTL SQL tags simplify database operations, making it
easier to interact with databases directly from JSP pages.
• Ease of Maintenance: JSTL promotes a cleaner code structure that's easier to maintain. This
is important for long-term development and enhancement of web applications.
• Performance: JSTL tags can improve performance by optimizing tag processing and
memory usage compared to scriptlets. They are often implemented efficiently by JSP
container libraries.
• Consistency: JSTL provides a consistent way to perform common tasks in JSP, reducing the
need for custom, non-standard Java code in your pages.
93
COUNT TO TEN EXAMPLE USING SCRIPTLET:
94
COUNT TO TEN EXAMPLE USING JSTL:
The following code shows <%@ taglib uri="[Link]
prefix="c" %>
how the count to ten <html>
<head>
example would be written <title>Count to 10 Example (using JSTL)</title>
using JSTL. As you can </head>
example.
95
COUNT TO TEN EXAMPLE USING JSTL:
• When you examine the preceding source code, you can see that the
JSP page consists entirely of tags.
• The code makes use of HTML tags such as <head> and <br>. The use
of tags is not confined just to HTML tags. We can modify that code
to print numbers from 1 to n. The code is given in the next slide.
• This code also makes use of JSTL tags such as <c:forEach> and
<c:out>.
96
PRINT 1 TO N EXAMPLE USING JSTL:
<%@ taglib prefix="c" uri="[Link] %>
The following code shows how <HTML>
the count to n example would <HEAD>
be written using JSTL. </HEAD>
As you can see, this code listing <BODY>
<c:set var="n" value="${[Link]}" />
is much more constant, as only Hello ...Printing numbers till N=
tags are used. <c:out value="${n}"/>
<br/>
HTML and JSTL tags are mixed <br/>
to produce the example. <c:forEach var="i" begin="1" end="${n}" step="1">
You can just use [Link] <c:out value="${i}"/>
</c:forEach>
file>?number=10 to see the </BODY>
result.
97
THE JSTL TAG LIBRARIES
• The JavaServer Pages Standard Tag Library (JSTL) is a
collection of useful JSP tags which encapsulates core
functionality common to many JSP applications.
• JSTL is often spoken of as a single-tag library.
• JSTL has support for common, structural tasks such as
iteration and conditionals, tags for manipulating XML
documents, internationalization tags, and SQL tags.
• It also provides a framework for integrating existing
custom tags with JSTL tags.
• The JSTL tags can be classified, according to their
functions, into following JSTL tag library groups that can
be used when creating a JSP page:
98
THE JSTL TAG LIBRARIES
The JSTL tags can be classified, according to their
functions, into following JSTL tag library groups that
can be used when creating a JSP page:
– Core Tags
– Formatting tags
– SQL tags
– XML tags
– JSTL Functions
99
THE JSTL TAG LIBRARIES
• Core Tag Library—Contains tags that are essential to nearly any Web application. Examples of
core tag libraries include looping, expression evaluation, and basic input and output.
• Formatting/Internationalization Tag Library—Contains tags that are used to parse data. Some of
these tags will parse data, such as dates, differently based on the current locale.
• Database Tag Library—Contains tags that can be used to access SQL databases. These tags are
normally used only to create prototype programs. This is because most programs will not handle
database access directly from JSP pages. Database access should be embedded in EJBs that are
accessed by the JSP pages.
• XML Tag Library—Contains tags that can be used to access XML elements. Because XML is used in
many Web applications, XML processing is an important feature of JSTL.
• JSTL Functions --JSTL includes a number of standard functions, most of which are common string
manipulation functions.
100
Core Tags:
• The core group of tags are the most frequently used
JSTL tags.
• Following is the syntax to include JSTL Core library in
your JSP:
<%@ taglib
uri="[Link] prefix="c"
%>
101
Tag Description
<c:out > Like <%= ... >, but for expressions.
<c:catch> Catches any Throwable that occurs in its body and optionally exposes it.
<c:if> Simple conditional tag which evalutes its body if the supplied condition is true.
<c:choose> Simple conditional tag that establishes a context for mutually exclusive conditional operations,
marked by <when> and <otherwise>
<c:when> Subtag of <choose> that includes its body if its condition evalutes to 'true'.
<c:otherwise > Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated
to 'false'.
<c:import> Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var',
or a Reader in 'varReader'.
<c:forEach > The basic iteration tag, accepting many different collection types and supporting subsetting and
other functionality .
<c:forTokens> Iterates over tokens, separated by the supplied delimeters.
• <body> • </c:choose>
• <c:forEach
Formatting tags:
The JSTL formatting tags are used to format and display text, the date, the
time, and numbers for internationalized Web sites. Following is the syntax to
include Formatting library in your JSP:
<%@ taglib prefix="fmt" uri="[Link] %>
Tag Description
<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern
<fmt:parseDate> Parses the string representation of a date and/or time
<fmt:bundle> Loads a resource bundle to be used by its tag body.
<fmt:setLocale> Stores the given locale in the locale configuration variable.
<fmt:setBundle> Loads a resource bundle and stores it in the named scoped variable or the bundle
configuration variable.
<fmt:timeZone> Specifies the time zone for any time formatting or parsing actions nested in its body.
<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable
<fmt:message> To display an internationalized message.
<fmt:requestEncoding> Sets the request character encoding 104
<%@ page language="java" contentType="text/html; <fmt:formatNumber value="12345.6789"
charset=UTF-8"NMITD,
pageEncoding="UTF-8%>
DR. RUCHI, AP type="currency" currencyCode="USD" />
<%@ taglib prefix="fmt" </p>
uri="[Link]
105 %>
<!DOCTYPE html> <h2>Formatting Dates and Times</h2>
<html> <p>Original Date: <fmt:parseDate value="2023-10-20"
<head> pattern="yyyy-MM-dd" var="myDate" />
<meta charset="UTF-8"> <fmt:formatDate value="${myDate}"
<title>JSTL Formatting Tags Example</title> pattern="dd/MM/yyyy" />
</head> </p>
<body>
<h1>JSTL Formatting Tags Example</h1> <p>Original Time: <fmt:parseDate value="15:30:45"
pattern="HH:mm:ss" var="myTime" />
<h2>Formatting Numbers</h2> <fmt:formatTime value="${myTime}"
<p>Original Number: 12345.6789</p> pattern="hh:mm a" />
</p>
<p>Formatted Number with Two Decimal Places: </body>
<fmt:formatNumber value="12345.6789" </html>
pattern="#,##0.00" />
</p>
Tag Description
<sql:setDataSource> Creates a simple DataSource suitable only for prototyping
<sql:query> Executes the SQL query defined in its body or through the sql
attribute.
<sql:update> Executes the SQL update defined in its body or through the sql
attribute.
<sql:param> Sets a parameter in an SQL statement to the specified value.
• The JSTL XML tag library has custom tags for interacting with XML data. This
includes parsing XML, transforming XML data, and flow control based on XPath
expressions.
Before you proceed with the examples, you would need to copy following two
XML and XPath related libraries into your <Tomcat Installation Directory>\lib:
108
Following is the list of XML JSTL Tags:
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.
<x:parse> Use to parse XML data specified either via an attribute or in the tag body.
Evaluates a test XPath expression and if it is true, it processes its body. If the
<x:if >
test condition is false, the body is ignored.
<x:when > Subtag of <choose> that includes its body if its expression evalutes to 'true'
Subtag of <choose> that follows <when> tags and runs only if all of the prior
<x:otherwise >
conditions evaluated to 'false'
<x:param > Use along with the transform tag to set a parameter in the XSLT stylesheet
109
<%@ page language="java" </data>" var="xmlData" /> ansform' version='1.0'>
contentType="text/html;
NMITD, [Link]=UTF-8"
RUCHI, AP <xsl:template match='product'>
pageEncoding="UTF-8"%> <x:forEach select="$xmlData/user" <div>
<%@ taglib prefix="x" var="user"> <xsl:apply-templates />
110
uri="[Link] <p>Name: <x:out select="$user/name" </div>
<!DOCTYPE html> /></p> </xsl:template>
<html> <p>Email: <x:out select="$user/email" <xsl:template match='name'>
<head> /></p> <h3><xsl:value-of select='.' /></h3>
<meta charset="UTF-8"> <hr> </xsl:template>
<title>JSTL XML Tags Example</title> </x:forEach> <xsl:template match='price'>
</head> <p>Price: $<xsl:value-of select='.'
<body> <h2>XML Transformation</h2> /></p>
<h1>JSTL XML Tags Example</h1> <x:parse xml="<data> </xsl:template>
<product> </xsl:stylesheet>" var="transformedData"
<h2>XML Parsing and Display</h2> <name>Laptop</name> />
<x:parse xml="<data> <price>800</price>
<user> </product> <x:out select="$transformedData" />
<name>John Doe</name> <product> </body>
<name>Smartphone</name> </html>
<email>johndoe@[Link]</email> <price>400</price>
</user> </product>
<user> </data>" var="xmlData2" />
<name>Jane Smith</name>
<x:transform xml="${xmlData2}"
<email>janesmith@[Link]</email> xslt="<xsl:stylesheet
</user> xmlns:xsl='[Link]
JSTL Functions:
JSTL includes a number of standard functions, most of which are common string
manipulation functions. Following is the syntax to include JSTL Functions library
in your JSP:
<%@ taglib prefix="fn" uri="[Link] %>
Function Description
fn:contains() Tests if an input string contains the specified substring.
fn:containsIgnoreCase() Tests if an input string contains the specified substring in a case insensitive way.
fn:indexOf() Returns the index within a string of the first occurrence of a specified substring.
fn:replace() Returns a string resulting from replacing in an input string all occurrences with a
given string.
fn:split() Splits a string into an array of substrings. 111
<%@ page language="java" contentType="text/html; <p>Power: ${fn:pow(2, 3)}</p>
charset=UTF-8"NMITD,
pageEncoding="UTF-8"%>
DR. RUCHI, AP
<h2>Math Functions</h2>
<p>Absolute Value: ${fn:abs(-10)}</p>
<p>Maximum: ${fn:max(5, 8)}</p>
<p>Minimum: ${fn:min(5, 8)}</p>
NMITD, DR. RUCHI, AP
115 To create custom JSTL tags, you typically follow these steps:
• Define the Tag Handler Class: You create a Java class that defines the tag's behavior. This class must
extend a standard JSTL tag handler class (e.g., TagSupport or BodyTagSupport) and override
methods like doStartTag, doEndTag, and doAfterBody to specify what the tag should do.
• Create the Tag Library Descriptor (TLD): The TLD is an XML file that provides metadata about your
custom tag library, including the tag names, the Java class that implements the tag, and other
attributes. It describes how the tags are used and maps them to the corresponding Java classes.
• Package and Deploy: Package your custom tag handler classes and TLD file into a JAR file or directory
structure. Deploy this file or structure to your web application.
• Declare the Custom Tag Library: In your JSP pages, declare your custom tag library using the
<%@taglib> directive. The directive specifies the prefix you'll use to reference your tags and the URI
that maps to your TLD.
• Use the Custom Tags: You can now use your custom tags in your JSP pages using the prefix and tag
names defined in the TLD.
NMITD, DR. RUCHI, AP
116
Java Bean
JSP – JavaBeans
• Bean means component. Components mean reusable objects.
• JavaBean is a reusable component.
• A JavaBean is a specially constructed Java class written in the
Java and coded according to the JavaBeans API specifications.
• Following are the unique characteristics that distinguish a
JavaBean from other Java classes −
– It provides a default, no-argument constructor.
– It should be serializable and that which can implement
the Serializable interface.
– It may have a number of properties which can be read or written.
– It may have a number of "getter" and "setter" methods for the
properties.
Serializable Interface in Java
• The Serializable interface is present in [Link] package.
• Classes implement it if they want their instances to be Serialized or Deserialized.
Once Bean class is instantiated using above statement, you have to use
jsp:setProperty and jsp:getProperty actions to use the bean’s parameters.
NMITD, DR. RUCHI, AP
123
Action Tag
JSP Action Tags
• There are many JSP action tags or elements. Each JSP action tag is used to
perform some specific tasks.
• The action tags are used to control the flow between JSP pages and to use
Java Bean.
• JSP actions use the construct in XML syntax to control the behavior of the
servlet engine.
• We can dynamically insert a file, reuse the beans components, forward user
to another page, etc. through JSP Actions like include and forward.
• Unlike directives, actions are re-evaluated each time the page is accessed.
NMITD, DR. RUCHI, AP
• There are many JSP action tags or elements. Each JSP action tag is used to
125 perform some specific tasks.
• The action tags are used to control the flow between pages and to use Java Bean.
The Jsp action tags are given below.
• Syntax:
• <jsp:action_name attribute="value" />
• There are 12 types of Standard Action Tags in JSP.
Standard Action Tags available in JSP
•jsp:useBean •jsp:body
•jsp:include •jsp:text
•jsp:setProperty •jsp:param
•jsp:getProperty •jsp:attribute
•jsp:forward •jsp:output
•jsp:plugin
•jsp:attribute
jsp:forward action tag
• <jsp:forward> is used for redirecting the
request.
• When this action is encountered on a JSP page the
control gets transferred to the page mentioned in
this action.
• The jsp:forward action tag is used to forward the
request to another resource it may be jsp, html
or another resource.
NMITD, DR. RUCHI, AP
128
• Syntax of jsp:forward action tag without parameter
• <jsp:forward page="relativeURL | <%= expression %>" />
<html> • Note: You must have [Link] file (an applet class file)
in the current folder where jsp file resides.
<head>
<meta http-equiv="Content-
Type" content="text/html; charset=UTF-8">
<title>Mouse Drag</title>
</head>
<body bgcolor="khaki">
</body>
</html>
<jsp:fallback>
• This action is an optional, direct child of the <jsp:plugin> action.
• Its purpose is to specify some content which is used by the client browser in case the plugin
cannot be started.
• Common usage is to show some text that indicates there’s a problem of loading the component.
• For example:
<jsp:plugin type="applet"
code="[Link]"
width="475" height="350">
<jsp:fallback>
<B>Error: this example requires Java.</B>
</jsp:fallback>
</jsp:plugin>
NMITD, DR. RUCHI, AP
141 <jsp:element>,
<jsp:attribute> and <jsp:body>
• These actions are used to define XML elements dynamically.
• The word dynamically is important, because it means that the XML
elements can be generated at request time rather than statically at compile
time.
NMITD, DR. RUCHI, AP
142
<%@page language = "java" contentType = "text/html"%>
<html xmlns = "[Link]
<html xmlns = "[Link]
xmlns:jsp = "[Link]
xmlns:jsp = "[Link]
<head><title>Generate XML
Element</title></head>
<head><title>Generate XML Element</title></head>
<body>
<body>
<xmlElement xmlElementAttr = "Value for the
<jsp:element name = "xmlElement">
attribute">
<jsp:attribute name = "xmlElementAttr">
Body for XML element
Value for the attribute
</xmlElement>
</jsp:attribute>
</body>
</html>
<jsp:body>
Body for XML element
</jsp:body>
</jsp:element>
</body>
</html>
NMITD, DR. RUCHI, AP
<head><title>jsp:text action</title></head>
<body>
<books><book><jsp:text>
Welcome to JSP Programming
</jsp:text></book></books>
</body>
</html>
<jsp:setProperty> Action
This action tag is used to set the property of a Bean, while using this action
tag, you may need to specify the Bean’s unique name (it is nothing but the id
value of useBean action tag).
<jsp:getProperty> Action
It is used to retrieve or fetch the value of Bean’s property.
Example: java bean
Example: javabean
[Link] return(message);
package coreservlets; }
/** A simple bean that has a single String public void setMessage(String message) {
property [Link] = message;
* called message. }
*/ }
public class StringBean {
private String message = "No message
specified";
public String getMessage() {
[Link]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Using JavaBeans with JSP</TITLE>
<LINK REL=STYLESHEET
HREF="[Link]"
TYPE="text/css">
</HEAD>
<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
Using JavaBeans with JSP</TABLE>
<jsp:useBean id="stringBean" class="[Link]" />
[Link] continued
<OL> setProperty:
<LI>Initial value (getProperty): <I><jsp:getProperty name="stringBean"
<I><jsp:getProperty name="stringBean" property="message" /></I>
property="message" /></I> <LI><% [Link]("My
favorite: Kentucky Wonder"); %>
<LI>Initial value (JSP expression):
Value after setting property with scriptlet:
<I><%= [Link]() %></I>
<I><%= [Link]() %></I>
<LI><jsp:setProperty name="stringBean"
</OL>
property="message"
</BODY>
value="Best string bean: Fortex" />
</HTML>
Value after setting property with
Result of [Link]
Session Tracking in JSP
• In a web application, server may be responding to several clients at
a time so session tracking is a way by which a server can identify
the client.
• As we know HTTP protocol is stateless which means client needs to
open a separate connection every time it interacts with server and
server treats each request as a new request.
• There are four techniques which can be used to identify a user
session.
a) Cookies
b) Hidden Fields
c) URL Rewriting
d) Session Object
JSP Cookies Handling
• Cookies are the text files which are stored on the client
machine.
• They are used to track the information for various
purposes.
• It supports HTTP cookies using servlet technology
• The cookies are set in the HTTP Header.
• If the browser is configured to store cookies, it will keep
information until expiry date.
• Cookie object can be created using a name value pair.
• For example we can create a cookie with name sessionId with a
unique value for each client and then can add it in a resposne so that
it will be sent to client:
Cookie cookie = new Cookie(“sessionID”, “some unique value”);
[Link](cookie);
•If our application uses cookies for session management and our users
disable the cookie , then we will be in a big trouble.
Action_cookie.jsp
Action_cookie_main.jsp
Reading cookies in JSP
[Link] [Link]("<h2> Found Cookies Name and
Value</h2>");
<html>
for (int i = 0; i < my_cookies.length; i++) {
<head> <title>Read Cookies</title>
my_cookie = my_cookies[i];
</head>
[Link]("Name : " + my_cookie.getName( ) + ", ");
<body>
[Link]("Value: " + my_cookie.getValue( )+" <br/>");
<h1>Reading Cookies that we set</h1>
}
<%
}
Cookie my_cookie = null;
else {
Cookie[] my_cookies = null;
[Link]("<h2>No cookies founds</h2>");
// Get an array of Cookies associated with the this
domain }
{ </html>
Session tracking using Hidden fields
• Hidden fields are similar to other input fields with the only difference is that these
fields are not displayed on the page but its value is sent as other input fields.
• For example
<input type=”hidden” name=”sessionId” value=”unique value”/>
• The hidden form field will not displayed to the user but its value will be send to the
server and can be retrieved using [Link](“sessionId”) .
• With this approach ,we have to have a logic to generate unique value and it has the
major disadvantage that it only works if every page is dynamically generated, since
the whole point is that each session has a unique identifier.
• we cannot use this approach for static pages.
• In short with this approach, HTML pages cannot participate in session tracking.
Session tracking using URL Rewriting
• URL Rewriting is the approach in which a session (unique) identifier gets appended
with each request URL so server can identify the user session.
• For example if we apply URL rewriting on [Link] ,
it will become something like [Link]
tutorial/[Link]?sessionid=12345 where ?sessionid=12345 is the attached session
identifier and value 12345 will be used by server to identify the user session.
• There are several advantages of URL rewriting over above discussed approaches like it
is browser independent and even if user’s browser does not support cookie or in case
user has disabled cookies, this approach will work.
• Another advantage is , we need not to submit extra hidden parameter.
• As other approaches, this approach also has some disadvantages like we need to
regenerate every url to append session identifier and this need to keep track of this
identifier until the conversation completes.
Session tracking using session object
• For JSPs, by default a session is automatically created for the request if one does
not exist.
• So if your starting page is a JSP, a session would have already been created when
you get the first request.
• The information can be stored in the session for the current session by
setAttribute() and then retrieve by getAttribute() method, whenever needed.
• Setting Session :[Link]("username", name);
• Getting Session : [Link]("username");
Example
action="[Link]">
[Link] <font size=5>Enter your name<input
type="text"
name="name"></font><br><br>
<%@ page isErrorPage="true" %>
<font size=5>Enter your password<input
<html> type="password" name="password">
<head> </font><br><br>
<title>Session Management Example</title> <input type="submit" name="submit"
</head> value="submit">
<body> </form>
<form method="post" </body>
[Link]
<% ;
String name = }
[Link]("name");
else {
String password = [Link](“[Link]");
[Link]("password");
}
if ([Link]("monisa") &&
[Link](“monisa")) { %>
[Link]("username", name);
[Link](“[Link]")
[Link]
<html>
<head>
<title>Welcome in the program of session</title>
</head>
<body>
<font size = 5>Hello <%= [Link]("username") %></font>
</body>
</html>
NMITD, DR. RUCHI, AP
168
Custom Tags
NMITD, DR. RUCHI, AP
• The custom tag is useful because of its rich set of features. They are:
• They can be altered through properties passed from the calling page.
• They approach all the articles accessible to JSP pages.
• They can adjust the reaction produced by the calling page.
• They can speak with one another. You can make and instate a JavaBeans
segment, make a variable that alludes to that bean in one tag, and afterward
utilize the bean in another tag.
• They can settle inside each other, considering complex communications inside a
JSP page.
NMITD, DR. RUCHI, AP
172 Perform the following steps to create and use custom tags:
• When you use a custom tag in your JSP, write a tag handler class that will execute the functionality of the tag. A tag
handler class implements one of three interfaces:
• [Link]
• [Link]
• [Link]
• First way
• <prefix:tagname attr1=value1....attrn=valuen />
• SECOND WAY
• <prefix:tagname attr1=value1....attrn=valuen >
• body code
• </prefix:tagname>
NMITD, DR. RUCHI, AP
176
• JSP Custom Tag API
• The [Link] package
contains classes and interfaces for JSP
custom tag API.
• The JspTag is the root interface in the
Custom Tag hierarch
• JspTag interface
• The JspTag is the root interface for all the
interfaces and classes used in custom tag.
• It is a marker interface.
NMITD, DR. RUCHI, AP
<tag>
<name>today</name>
<tag-class>[Link]</tag-class>
</tag>
</taglib>
NMITD, DR. RUCHI, AP
• We can use the custom URI, to tell the web container about
the tld file.
• In such case, we need to define the taglib element in the
[Link].
• The web container gets the information about the tld file from
the [Link] file for the specified URI.
NMITD, DR. RUCHI, AP
184
EXAMPLE OF
CUSTOM TAG
NMITD, DR. RUCHI, AP
xmlns:xsi="[Link] <tag>
instance"
<name>helloWorld</name>
<tag-
xsi:schemaLocation="[Link]
class>[Link]</tag-
aee [Link]
class>
jsptaglibrary_2_1.xsd"
<body-content>empty</body-content>
version="2.1">
</tag>
</taglib>
<tlib-version>1.0</tlib-version>
NMITD, DR. RUCHI, AP Create a Tag Handler Class:
186 Create a Java class that handles the custom tag. In this example, the class is named
HelloWorldTagHandler and it extends [Link]:
Compile the Java Class: Compile the HelloWorldTagHandler class and package it into a JAR file if necessary.
NMITD, DR. RUCHI, AP
Create a JSP Page
Create a JSP page where you want to use the custom tag. In this example, create a file named
187 [Link]:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="custom" uri="/WEB-INF/[Link]" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World Page</title>
</head>
<body>
<custom:helloWorld/>
</body>
</html>
NMITD, DR. RUCHI, AP
188
Deploy the Files: Place the TLD file in the WEB-INF directory of your
web application, and place the compiled Java class and JSP file in the
appropriate locations.
Access the JSP Page: Deploy your web application and access the
[Link] page in a web browser. You should see the "Hello, World!"
message generated by the custom tag.