0% found this document useful (0 votes)
21 views188 pages

Java EE Programming Overview Guide

The document provides an introduction to Java EE programming, covering topics such as JSP architecture, building blocks, and session tracking. It explains the need for Java EE, its APIs, and the role of containers and servers in application development. Additionally, it outlines the specifications of Java EE, compares Java SE and Java EE, and details the lifecycle of JSP and Servlets.

Uploaded by

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

Java EE Programming Overview Guide

The document provides an introduction to Java EE programming, covering topics such as JSP architecture, building blocks, and session tracking. It explains the need for Java EE, its APIs, and the role of containers and servers in application development. Additionally, it outlines the specifications of Java EE, compares Java SE and Java EE, and details the lifecycle of JSP and Servlets.

Uploaded by

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

NMITD, DR.

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

5 Why do we need Java EE


• Faster
• More Secure
• More Reliable

• AIM to Implement JAVA EE


• Shorten development
• Reduce complexity
• Improve application performance
NMITD, DR. RUCHI, AP

6 APIs(Application Programming Interface).


• An API (Application Programming Interface) is a set of
rules and protocols that allows different software
applications to communicate with each other.
• It defines how requests for data or functionality should be
structured, and it dictates how a service will respond to
those requests.
• APIs enable developers to access the functionalities or
data of an application, operating system, library, or other
services without knowing the inner workings of that
system.
• Java Transaction API (JTA)
• Java Messaging Service (JMS)
• Java Persistence API (JPA)
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

9 Web Server Name

Apache HTTP Server (Apache)


Nginx
Microsoft Internet Information
Services (IIS)
LiteSpeed
[Link]
Apache Tomcat
Caddy
OpenLiteSpeed
lighttpd
Jetty
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

12 Examples of Application Servers

Apache
[Link]
Tomcat

JBoss EAP
GlassFish
/ WildFly

IBM WebLogic
WebSphere Server
NMITD, DR. RUCHI, AP

13 Distributed Multi Layer Architecture


NMITD, DR. RUCHI, AP

14

•Presentation Layer (Client Layer) •Business Logic Layer (Application


•Role: The user interface layer that Layer)
interacts directly with the user. •Role: Handles the core functionality
•Components: Web browsers, mobile and business rules of the application.
apps, or desktop applications. •Components: Application servers,
•Responsibilities: Displaying data to services, and APIs.
the user, accepting user inputs, and •Responsibilities: Processing client
sending requests to the business logic requests, executing business logic, and
layer. calling the data layer for information.
•Technology: HTML, CSS, JavaScript, •Technology: Java (Spring, J2EE),
React, Angular, [Link], Swift, JavaFX. .NET, [Link], Python (Django, Flask),
Ruby on Rails.
NMITD, DR. RUCHI, AP

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

• Java EE has several specifications which are


17 Specifications of Java EE
useful in making web pages, reading and
writing from database in a transactional way,
managing distributed queues.
• The Java EE contains several APIs(Application
Programming Interface).which have the
functionalities of base Java SE APIs such as
Enterprise JavaBeans, connectors, Servlets, Java
Server Pages and several web service
technologies.
NMITD, DR. RUCHI, AP

• Web Specifications of Java EE • Web Service Specifications of Java EE


18
• Servlet- This specification defines how you can • Java API for RESTful Web Services- It helps in
manage HTTP requests either in a synchronous providing services having Representational State
or asynchronous way. It is low level, and other Transfer schema.

specifications depend on it • Java API for JSON Processing- It is a set of


specifications to manage the information provided in
• WebSocket- WebSocket is a computer
JSON format.
communication protocol, and this API provides a
• Java API for JSON Binding- It is a set of
set of APIs to facilitate WebSocket connections.
specifications provide for binding or parsing a JSON
• Java Server Faces- It is a service which helps in file into Java classes.
building GUI out of components. • Java Architecture for XML Binding- It allows
• Unified Expression Language- It is a simple binding of xml into Java objects.
language which was designed to facilitate web • Java API for XML Web Services- SOAP is an xml
application developers. based protocol to access web services over http. This
API allows you to create SOAP web services.
NMITD, DR. RUCHI, AP

• Enterprise Specifications of Java EE


19
• Contexts and Dependency Injection- It provides a container to inject dependencies
as in Swing.
• Enterprise JavaBean- It is a set of lightweight APIs that an object container
possesses in
order to provide transactions, remote procedure calls, and concurrency control.
• Java Persistence API- These are the specifications of object-relational mapping
between relational database tables and Java classes.
• Java Transaction API- It contains the interfaces and annotations to establish
interaction between transaction support offered by Java EE. The APIs in this abstract
from low-level details and the interfaces are also considered low-level.
• Java Message Service- It provides a common way to Java program to create, send
and read enterprise messaging system messages.
NMITD, DR. RUCHI, AP

20 Other Specifications of Java EE


• Validation- This package contains various interfaces and annotations for
declarative validation support offered by Bean Validation
API(Application Programming Interface).
• Batch applications- It provides the means to run long running
background tasks which involve a large volume of data and which need
to be periodically executed.
• Java EE Connector Architecture- This is a Java-based technological
solution for connecting Java servers to Enterprise Information System.
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.

It does not provide user authentication. It provides user authentication.


NMITD, DR. RUCHI, AP

22

JSP- Java Server Pages


NMITD, DR. RUCHI, AP

23 Java Server Pages- JSP


• It stands for Java Server Pages.
• It is a server side technology.
• It is a Language for developing JSP Pages , Which are text –based document the describe how to
process a request and construct a response.
• It is used to create dynamic web content.
• In this JSP tags are used to insert JAVA code into HTML pages.
• It is an advanced version of Servlet Technology.
• It is a Web based technology helps us to create dynamic and platform-independent web pages.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into servlet by JSP container before processing the client’s request.
• A JSP page consists of HTML tags and JSP tags.
NMITD, DR. RUCHI, AP

KEY POINTS ABOUT JSP:


24
• Server-Side Technology: JSP is a server-side technology, which means that the Java code
embedded within JSP pages is executed on the web server rather than in the web
browser.
• Mix of Java and HTML: JSP pages typically consist of a mixture of HTML and Java
code. Java code can be enclosed within <% %> tags, allowing you to include dynamic
content and logic in your web pages.
• Servlet-Based: Under the hood, JSP pages are compiled into Java servlets by the web
container (e.g., Apache Tomcat). These servlets handle the dynamic aspects of web
applications.
• Reusable Components: JSP allows for the creation of reusable components called
custom tags or tag libraries, which can simplify the development of complex web
NMITD, DR. RUCHI, AP

KEY POINTS ABOUT JSP:


25
• MVC Architecture: JSP is often used in conjunction with the Model-View-Controller (MVC) design
pattern. It separates the application into three parts:
• The Model (business logic and data)
• The View (the user interface, often implemented with JSP)
• The Controller (handles user input and controls the flow of the application).

• 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

26 Life cycle of JSP


• A Java Server Page life cycle is defined as the process that started with its
creation which later translated to a servlet and afterward servlet
lifecycle comes into play.
• Translation of JSP page to Servlet
• Compilation of JSP page(Compilation of JSP into [Link])
• Classloading ([Link] to [Link])
• Instantiation(Object of the generated Servlet is created)
• Initialization(jspInit() method is invoked by the container)
• Request processing(_jspService()is invoked by the container)
• JSP Cleanup (jspDestroy() method is invoked by the container)
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

29 Servlet Life Cycle


• The entire life cycle of a Servlet is managed
by the Servlet container which uses
the [Link] interface to
understand the Servlet object and manage it.
• Servlets are build from two packages:
• [Link](Basic)
• [Link](Advance)

• Process
• Loading a Servlet.
• Initializing the Servlet.
• Request handling.
• Destroying the Servlet
NMITD, DR. RUCHI, AP

30 lifecycle of a Java Servlet


• It refers to the various stages a servlet goes • Request Handling:
through from its initialization to its destruction.
• Once the servlet is initialized, it is ready to
Understanding the servlet lifecycle is crucial for
handle client requests.
developing and managing servlets effectively.
• When a client sends an HTTP request to the
Servlet Class Loading and URL mapped to the servlet, the servlet
Initialization: container routes the request to the
• When the web server starts or when the appropriate servlet instance.
servlet container deploys the web • The servlet's service() method is called to
application, it loads and initializes the process the request. This method determines
servlet class. This process involves creating the HTTP method (GET, POST, etc.) and
an instance of the servlet class. dispatches the request to the appropriate
• The init() method of the servlet is called doXXX() method (e.g., doGet(), doPost()) or
during this phase. This method is typically directly processes the request within the
used for one-time setup tasks, such as service() method itself.
NMITD, DR. RUCHI, AP

31 lifecycle of a Java Servlet


• Thread Safety and Concurrency:
• Servlets are inherently multi-threaded. Each client request typically
results in a separate thread being spawned to handle that request.
• Developers need to ensure that their servlets are thread-safe, especially
if they share resources or maintain mutable state.
• Response Generation:
• The servlet generates the dynamic response, often by generating HTML
content, XML, JSON, or other types of data.
• The response is sent back to the client as an HTTP response. The servlet
sets response headers, status codes, and content using the
HttpServletResponse object.
NMITD, DR. RUCHI, AP

32 lifecycle of a Java Servlet


• Request and Response Destruction:
• After the service() method completes its execution and the response is sent to the client,
the servlet container may release the resources associated with the request and response
objects.
• The request and response objects may be eligible for garbage collection.

• 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.

• Servlet Reloading (Optional):


• Some servlet containers support hot reloading, which allows you to update a servlet's
code without restarting the server. In such cases, the servlet's class may be reloaded, and
the init() method is called again.
NMITD, DR. RUCHI, AP

33 Why JSP is preferred over servlets?


• 1) Extension to Servlet
• JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in JSP. In 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. In Servlet
technology, we mix our business logic with the presentation logic.
• 3) Fast Development: No need to recompile and redeploy
• If 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
• In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code. Moreover, we can
use EL, implicit objects, etc.
NMITD, DR. RUCHI, AP

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.

• This separation of concerns allows for better


maintainability and scalability of the application.
NMITD, DR. RUCHI, AP

35
NMITD, DR. RUCHI, AP

36 Servlet Vs JSP
NMITD, DR. RUCHI, AP

37 Servlet Vs JSP
NMITD, DR. RUCHI, AP

38 The Directory structure of JSP


• The directory structure of JSP page is same
as Servlet.
• We contain the JSP page outside the WEB-
INF folder or in any directory.
NMITD, DR. RUCHI, AP

39 JSP Building Block


• JSP Elements: JSP pages are primarily composed of HTML content, but they also contain JSP
elements that allow you to embed Java code and control logic within the page. The main JSP
elements are:
• Scriptlets <% ... %>: These are used to embed Java code within a JSP page. For example, you can use
scriptlets to define variables, perform calculations, or execute conditional statements.
• Directives <%@ ... %>: JSP directives provide instructions to the JSP container about how to process
the page. Common directives include page, include, and taglib.
• Expressions ${ ... }: JSP expressions are used to embed the result of a Java expression directly into
the HTML content. They are enclosed in ${}. For example, ${variable} will insert the value of the Java
variable into the page.
• Custom Tags and Tag Libraries: JSP allows you to create and use custom tags using tag libraries.
Custom tags are reusable components that encapsulate complex logic. Tag libraries can be defined in
tag library descriptor (TLD) files.
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:

Note: In above example – <demotag: welcome> has a prefix demotag.


NMITD, DR. RUCHI, AP

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

63 JSP provide you Total 9 implicit objects


1. request: This is the object of the HttpServletRequest class associated with the request.
2. response: This is the object of HttpServletResponse class associated with the response to the client.
3. config: This is the object of the ServletConfig class associated with the page.
4. Application: This is the object of the ServletContext class associated with the application context.
5. Session: This is the object of the HttpSession class associated with the request.
6. Page context: This is the object of the PageContext class that encapsulates the use of server-specific features. This
object can be used to find, get, or remove an attribute.
7. Page object: The manner we use the keyword this for the current object, The page object is used to refer to the
current translated servlet class.
8. exception: The exception object represents all errors and exceptions which is accessed by the respective jsp. The
exception implicit object is of type [Link].

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>

■ For writing any data to the buffer, JSP provides <body>


an implicit object named out. <% [Link]("Today is:"+[Link]
■ For writing any data to the buffer, JSP provides tance().getTime()); %>
an implicit object named out. It is the object of
</body>
JspWriter.
■ In case of servlet you need to write: </html>
■ PrintWriter out=[Link]();
■ But in JSP, you don't need to write this code.
out example
request [Link]
1.<form action="[Link]">
2.<input type="text" name="uname">
• The JSP request is an implicit object of
3.<input type="submit" value="go"><br/>
type HttpServletRequest i.e. created for
4.</form>
each jsp request by the web container.
[Link]
• It can be used to get request information 1.<%
such as parameter, header information, [Link] name=[Link]("uname
remote address, server name, server port, ");
content type, character encoding etc. [Link]("welcome "+name);
• It can also be used to set, get and remove 4.%>
attributes from the jsp request scope.
NMITD, DR. RUCHI, AP

• Accessing Request Parameters:


69 • To access parameters passed in the HTTP request, you can use the
[Link]("parameterName") method.
• For example:
• <% String username = [Link]("username"); %>

• Accessing Request Attributes:


• You can access request attributes set in a servlet or another part of the application using the
[Link]("attributeName") method. For example:
• <% String attributeValue = (String) [Link]("myAttribute"); %>

• Working with the Request Object:


• The request object also provides methods to work with sessions, headers, cookies, and
more. Here are a few examples:
• [Link](): Retrieves the session associated with this request.
• [Link]("headerName"): Gets the value of a specific HTTP header.
• [Link](): Returns an array of cookies included with the request.
Response Object

• In JSP, the response is an implicit object of type


HttpServletResponse.
• The instance of HttpServletResponse is created by the web
container for each jsp request.
• It can be used to add or manipulate responses such as redirecting
responses to another resource, sending error etc.
• response object is an implicit object that represents the HTTP
response being sent to the client's web browser.
• It provides methods to control and manipulate the response that is
sent back to the client.
response example
[Link]
<html>
<head> <% String
<title>ResponseObject</title> url=[Link]("url");respon
</head> [Link]("[Link] %>
<body>
<formaction="[Link]">
URL:<inputtype="text"name="url">
<inputtype="submit"value="go">
<br/>
</form>
</body>
</html>
NMITD, DR. RUCHI, AP

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

• Setting the Status Code: • %>


73
• [Link](int sc): Sets the HTTP status code for • Setting Cookies:
the response.
• [Link](Cookie cookie): Adds a cookie to the
• <% response.
• [Link](200); // OK • <%
• %> • Cookie myCookie = new Cookie("user", "john");
• Setting Content Type: • [Link](myCookie);
• [Link](String type): Sets the content • %>
type of the response.
• Flushing the Response:
• <%
• [Link](): Forces any content in the response
• [Link]("text/html"); buffer to be sent to the client immediately.
• %> • <%
• Redirecting the Client: • [Link]().println("This will be sent
immediately.");
• [Link](String location): Redirects the
client to a different URL. • [Link]();
• <% • %>
• [Link]("[Link]
Config Object [Link] file
1.<web-app>
17.</web-app>

• In JSP, config is an implicit object of 2. [Link]


type ServletConfig. 3.<servlet> 1.<%
• This object can be used to get 4.<servlet- [Link]("Welcome "+[Link]
initialization parameter for a particular name>sonoojaiswal</servlet-name> ameter("uname"));
5.<jsp-file>/[Link]</jsp-file> 3.
JSP page.
6.<init-param> [Link] driver=[Link]
• The config object is created by the 7.<param-name>dname</param- ("dname");
web container for each jsp page. name> [Link]("driver name is="+driver);
• Generally, it is used to get the 8.<param- 6.%>
initialization parameter from the value>[Link]<
[Link] file. /param-value>
9.</init-param>
10.
11.</servlet>
12.
[Link] 13.<servlet-mapping>
1.<form action="welcome"> 14.<servlet-
2.<input type="text" name="uname"> name>sonoojaiswal</servlet-name>
3.<input type="submit" value="go"><br/> 15.<url-pattern>/welcome</url-
pattern>
4.</form> 16.</servlet-mapping>
Application Object

• In JSP, the application is an implicit object of type ServletContext.


• The instance of ServletContext is created only once by the web container
when an application or project is deployed on the server.
• This object can be used to get the initialization parameter from the configuration
file ([Link]).
• It can also be used to get, set, or remove attributes from the application scope.
• This initialization parameter can be used by all jsp pages.
• This object is a representation of the JSP page through its entire
lifecycle.
• This object is created when the JSP page is initialized and will be
removed when the JSP page is removed by the jspDestroy() method.
• By adding an attribute to the application, you can ensure that all JSP
files that make up your web application have access to it.
application example
[Link]
<form action="welcome">
<input type="text" name="uname"> [Link] file
<input type="submit" value="go"><br/<web-app>
> <servlet>
</form> <servlet-name>NMITD</servlet-
name> [Link]
<jsp-file>/[Link]</jsp-file> <%
</servlet> [Link]("Welcome "+[Link]
<servlet-mapping> meter("uname"));
<servlet-name>NMITD</servlet- String driver=[Link]
name> ter("dname");
<url-pattern>/welcome</url- [Link]("driver name is="+driver);
pattern> %>
</servlet-mapping>
<context-param>
<param-name>dname</param-
name>
<param-value>
[Link]
</param-value>
Session Object
■ In JSP, session is an implicit object of type HttpSession.
■ The Java developer can use this object to set,get or remove
attribute or to get session information.
■ The session object is an instance
of [Link] and behaves exactly the
same way that session objects behave under Java Servlets.
■ The session object is used to track client sessions
between client requests.
session example
[Link] [Link] [Link]
1.<html> 1.<html> 1.<html>
2.<body> 2.<body> 2.<body>
3.<form action="[Link]"> 3.<% 3.<%
4.<input type="text" name="uname"> [Link] name=[Link](4.
"uname"); [Link] name=(String)[Link]
5.<input type="submit" value="go"><[Link]("Welcome "+name); ibute("user");
br/> [Link]("user",name); [Link]("Hello "+name);
6.</form> 7.<a href="[Link]">second jsp pa7.
7.</body> ge</a> 8.%>
8.</html> 8.%> 9.</body>
9.</body> 10.</html>
10.</html>
pageContext implicit object of JSP
It is an instance of [Link].
Using this object you can find attribute, get attribute,
set attribute and remove attribute at any of the below
levels –

[Link] Page – Scope: PAGE_CONTEXT


[Link] Request – Scope: REQUEST_CONTEXT
[Link] Session – Scope: SESSION_CONTEXT
[Link] Level – Scope:
APPLICATION_CONTEXT
pageContext example

[Link]
<html>
<body>
<%

String name=(String)[Link]
bute(“UName“,
pageContext.SESSION_SCOPE,);
[Link]("Hello "+name);

%>
</body>
</html>
Page

■ In JSP, page is an implicit object of type Object [Link] object is


assigned to the reference of auto generated servlet class.
■ It is written as:Object page=this;
■ For using this object it must be cast to Servlet type.
■ For example:<% (HttpServlet)[Link]("message"); %>
■ Since, it is of type Object it is less used because you can use this
object directly in jsp.
■ For example:<% [Link]("message"); %>
exception
■ In JSP, exception is an implicit object of type [Link]
class.
■ This object can be used to print the exception.
■ But it can only be used in error pages.
exception example
Exception handling in JSP

Methods of handling exceptions:


We can handle exceptions using the below two methods.
1) Exception handling using exception implicit object
2) Exception handling using try catch blocks within scriptlets

1) Exception handling using exception implicit object


• In the below example – we have specified the exception handling page
using errorPage attribute of Page directive
• If any exception occurs in the main JSP page the control will be transferred to
the page mentioned in errorPage attribute.
2. Exception handling using try catch
blocks within scriptlets

• We have handled the exception using try catch blocks in the


below example.
• Since try catch blocks are java code so it must be placed inside
sciptlet
• In the below example I have declared an array of length 5 and
tried to access the 7th element which doesn’t exist. It caused
Array Index out of bounds exception.
JSTL (JSP Standard Tag
Libraries)
What is JSTL?
• JSTL (JSP Standard Tag Libraries) is a collection of JSP custom tags
developed by Java Community Process, [Link]. The reference
implementation is developed by the Jakarta project,
[Link].
• Full JSTL
– Contains many common and useful JSP custom tags
• JSTL allows you to program your JSP pages using tags, rather than the
scriptlet code that most JSP programmers are already accustomed to.
• JSTL can do nearly everything that regular JSP scriptlet code can do.

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:

• JSTL was introduced to allow JSP <html>


programmers to program using tags <head>
rather than Java code. <title>Count to 10 in JSP scriptlet</title>
</head>
• To show why this is preferable, a quick <body>
example is in order. We will examine a <% for(int i=1;i<=10;i++)
{%>
very simple JSP page that counts to ten. <%=i%><br/>
• We will examine this page both as <%
regular scriptlet-based JSP, and then as }
%>
JSTL. When the count to ten example is </body>
programmed using scriptlet based JSP, </html>
the JSP page appears as follows.`

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>

see, this code listing is <body>


<c:forEach var="i" begin="1" end="10" step="1">
much more constant, as <c:out value="${i}" />
only tags are used. <br />
HTML and JSTL tags are </c:forEach>
</body>
mixed to produce the </html>

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:set > Sets the result of an expression evaluation in a 'scope'

<c:remove > Removes a scoped variable (from a particular scope, if specified).

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

<c:param> Adds a parameter to a containing 'import' tag's URL.

<c:redirect > Redirects to a new URL.


102
Creates a URL with optional query parameters
NMITD, DR. RUCHI, AP

• <%@ page language="java" • <h1>JSTL Core Tags items="${programmingLanguage


contentType="text/html; Example</h1> s}" var="language">
103
charset=UTF-8"
• <p>${language}</p>
pageEncoding="UTF-8"%>
• <c:set var="userAge" value="25" • </c:forEach>
• <%@ taglib prefix="c"
/>
uri="[Link] • <c:url var="searchUrl"
core"%> • <c:choose> value="/[Link]">

• <!DOCTYPE html> • <c:when test="${userAge >= • <c:param name="q"


18}"> value="JSTL Examples" />
• <html>
• <p>You are an adult.</p> • </c:url>
• <head>
• </c:when> • <a href="${searchUrl}">Search
• <meta charset="UTF-8">
JSTL Examples</a>
• <c:otherwise>
• <title>JSTL Core Tags
• </body>
Example</title> • <p>You are a minor.</p>
• </html>
• </head> • </c:otherwise>

• <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:formatNumber> To render numerical value with specific precision or format.


<fmt:parseNumber> Parses the string representation of a number, currency, or percentage.

<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>

<p>Formatted Number as Currency:


SQL tags:
• The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as
Oracle, mySQL, or Microsoft SQL Server.
• Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql" uri="[Link] %>

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.

<sql:dateParam> Sets a parameter in an SQL statement to the specified


[Link] value.
<sql:transaction > Provides nested database action elements with a shared
Connection, set up to execute all statements as one transaction.
106
<%@ page language="java" contentType="text/html; charset=UTF- <p>First Name: ${row.FIRST_NAME}</p>
8" pageEncoding="UTF-8"%> <p>Last Name: ${row.LAST_NAME}</p>
NMITD, DR. RUCHI, AP
<%@ taglib prefix="sql" uri="[Link] <p>Email: ${[Link]}</p>
<!DOCTYPE html> <hr>
107
<html> </c:forEach>
<head>
<meta charset="UTF-8"> <h2>Executing SQL Updates</h2>
<title>JSTL SQL Tags Example</title> <sql:update dataSource="${myDataSource}">
</head> UPDATE employees SET SALARY = 55000 WHERE
<body> EMPLOYEE_ID = 101;
<h1>JSTL SQL Tags Example</h1> </sql:update>

<h2>Setting Up a DataSource</h2> <h2>Executing SQL Transactions</h2>


<sql:setDataSource var="myDataSource" <sql:transaction dataSource="${myDataSource}">
driver="[Link]" <sql:update>
url="jdbc:mysql://localhost:3306/yourdatabase" INSERT INTO employees (EMPLOYEE_ID,
user="yourusername" FIRST_NAME, LAST_NAME, EMAIL) VALUES (110, 'John',
password="yourpassword" /> 'Doe', 'johndoe@[Link]');
</sql:update>
<h2>Executing SQL Queries</h2> <sql:update>
<sql:query dataSource="${myDataSource}" var="result"> DELETE FROM employees WHERE EMPLOYEE_ID =
SELECT * FROM employees; 109;
</sql:query> </sql:update>
</sql:transaction>
<h2>Displaying Query Results</h2> </body>
<c:forEach var="row" items="${[Link]}"> </html>
<p>Employee ID: ${row.EMPLOYEE_ID}</p>
XML TAGS:
• The JSTL XML tags provide a JSP-centric way of creating and manipulating XML
documents. Following is the syntax to include JSTL XML library in your JSP:

<%@ taglib prefix="x" uri="[Link] %>

• 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:

– [Link]: Download it from [Link]


– [Link]: Download it from [Link]

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.

<x:set > Sets a variable to the value of an XPath expression.

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:forEach> To loop over nodes in an XML document.

Simple conditional tag that establishes a context for mutually exclusive


<x:choose>
conditional operations, marked by <when> and <otherwise>

<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:transform > Applies an XSL transformation on a XML document

<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:endsWith() Tests if an input string ends with the specified suffix.


fn:escapeXml() Escapes characters that could be interpreted as XML markup.

fn:indexOf() Returns the index within a string of the first occurrence of a specified substring.

fn:join() Joins all elements of an array into a string.


fn:length() Returns the number of items in a collection, or the number of characters in a string.

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

<%@ taglib prefix="fn"


uri="[Link]
112 <h2>Collection Functions</h2>
<!DOCTYPE html> <c:set var="numbers" value="${fn:split('1,2,3,4,5', ',')}" />
<html> <p>Original Collection: [1, 2, 3, 4, 5]</p>
<head> <p>Size: ${fn:length(numbers)}</p>
<meta charset="UTF-8"> <p>Contains 3? ${fn:contains(numbers, 3)}</p>
<title>JSTL Function Tags Example</title> <p>Join as String: ${fn:join(numbers, ',')}</p>
</head>
<body> <h2>Encoding Functions</h2>
<h1>JSTL Function Tags Example</h1> <p>URL Encode: ${fn:escapeXml("<a
href='/page'>Link</a>")}</p>
<h2>String Functions</h2> </body>
<p>Original String: "Hello, JSTL"</p> </html>
<p>Uppercase: ${fn:toUpperCase("Hello, JSTL")}</p>
<p>Lowercase: ${fn:toLowerCase("Hello, JSTL")}</p>
<p>Trimmed: "${fn:trim(" Hello, JSTL ")}"</p>

<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

113 Advantages of JSTL


• Simplifies Code: JSTL reduces the need for embedded Java code in JSP pages, which makes code cleaner, more
readable, and easier to maintain.
• Separation of Concerns: JSTL enforces a clear separation of presentation logic (JSP) and business logic. This
promotes best practices in web application development.
• Code Reusability: JSTL allows you to reuse tag-based constructs across multiple JSP pages, reducing code duplication
and enhancing maintainability.
• Standardization: JSTL is a standard library, which means that developers across different projects and organizations
can use the same set of tags, fostering consistency and best practices.
• Reduced Scriptlets: By reducing the use of scriptlets in JSP pages, JSTL helps minimize complexity and enhances
code maintainability.
• Security: JSTL provides tags for escaping output, which helps protect against Cross-Site Scripting (XSS) attacks and
enhances security.
• Internationalization and Localization: JSTL includes formatting tags for numbers, dates, and times, making it easier
to build web applications that can be used in different locales.
• Database Operations: The SQL tags in JSTL simplify database interactions, reducing the need to write complex Java
code for database operations.
• Performance: JSTL tags are often optimized for performance by JSP container libraries, improving runtime efficiency
compared to custom Java code.
NMITD, DR. RUCHI, AP

114 Disadvantages of JSTL:


• Learning Curve: JSTL introduces a learning curve for developers who are new to JSP.
Understanding how to use the various JSTL tags effectively can take time.
• Limited Functionality: While JSTL provides many useful tags, it does not cover all possible
scenarios. In some cases, you may still need to use custom Java code.
• Version Compatibility: JSTL is available in different versions (1.0, 1.1, etc.), and the availability
and features of JSTL may vary depending on the version supported by your JSP container.
Compatibility issues can arise if you switch between different versions of JSTL.
• Inflexibility: JSTL tags can be somewhat inflexible, and customizing their behavior may be
challenging or impossible in some cases.
• Maintainability Concerns: JSTL can make it easy to introduce complexity into JSP pages if
developers are not careful. It's possible to overuse JSTL tags and make pages overly complex.
• Incompatibility with Some IDEs: Some Integrated Development Environments (IDEs) may not
provide robust support for JSTL, which can make it harder to work with in certain development
environments
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.

• Serialization is a mechanism of converting the state of an object into a byte stream.


• Deserialization is the reverse process where the byte stream is used to recreate the
actual Java object in memory.
Working of JavaBeans in JSP

• 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.
A read-only attribute will have only a getPropertyName() method.

A write-only attribute will have only a setPropertyName() method.


JavaBeans Example
Consider a student class with few properties in myPack
Accessing JavaBeans
• The useBean action declares a JavaBean for use in a JSP. Once declared, the bean
becomes a scripting variable that can be accessed by both scripting elements and
other custom tags used in the JSP.
Jsp:useBean Action Tag
• This action is useful when you want to use Beans in a JSP page, through this
tag you can easily invoke a bean.
• Syntax of <jsp:useBean>:
<jsp: useBean id="unique_name_to_identify_bean"
class="package_name.class_name" />

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 %>" />

• Syntax of jsp:forward action tag with parameter


• <jsp:forward page="relativeURL | <%= expression %>">
• <jsp:param name="parametername" value="parameterval
ue | <%=expression%>" />
• </jsp:forward>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Action JSP1</title>
</head>
<body>
<jsp:forward page=“[Link]" />
</body>
</html>
[Link]
jsp:include Action tag
• Like include page directive this action is also used to insert a JSP file in
another file.
• The jsp:include action tag is used to include the content of another
resource it may be jsp, html or servlet.
•The jsp include action tag includes the resource at request time so it
is better for dynamic pages because there might be changes in future.
•The jsp:include tag can be used to include static as well as dynamic pages.
<jsp:include> vs include directive :
• In <jsp:include> the file is being included during request processing while in
case of include directive it has been included at translation phase.
NMITD, DR. RUCHI, AP

132 [Link]. Attribute & Description


page
1
The relative URL of the page to be included.
flush
2 The boolean attribute determines whether the included
resource has its buffer flushed before it is included.

JSP include directive JSP include action

includes resource at translation time. includes resource at request time.


better for static pages. better for dynamic pages.
includes the original content in the generated calls the include method.
servlet.
[Link]

<% [Link]("Today is:"+[Link]().getTime()); %>


<jsp:param> Action tag
• This action is useful for passing the parameters to Other
JSP action tags such as JSP include & JSP forward tag.
• This way new JSP pages can have access to those
parameters using request object itself.
<jsp:plugin>
• The plugin action is used to insert Java components into a JSP page. It determines the
type of browser and inserts the <object> or <embed> tags as needed.
• If the needed plugin is not present, it downloads the plugin and then executes the Java
component. The Java component can be either an Applet or a JavaBean.
• The plugin action has several attributes that correspond to common HTML tags used to
format Java components. The <param> element can also be used to send parameters to
the Applet or Bean.
• Syntax of jsp:plugin action tag
<jsp:plugin type= "applet | bean" code= "nameOfClassFile"
codebase= "directoryNameOfClassFile"
</jsp:plugin>
NMITD, DR. RUCHI, AP

• <jsp:plugin type = "applet" codebase = "dirname" code =


137
"[Link]" width = "60" height = "80">
• <jsp:param name = "fontcolor" value = "red" />
• <jsp:param name = "background" value = "black" />
• <jsp:fallback>
• Unable to initialize Java Plugin
• </jsp:fallback>
• </jsp:plugin>
<jsp:plugin> example
[Link]

<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">

<h1>Mouse Drag Example</h1>

<jsp:plugin align="middle" height="500" width="500"

type="applet" code="[Link]" name="clock" codebase="."/


>

</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

143 The <jsp:text> Action


• The <jsp:text> action can be used to write the template text in JSP pages and
documents. Following is the simple syntax for this action −
• <jsp:text>Template data</jsp:text>
• The body of the template cannot contain other elements; it can only contain text
and EL expressions (Note − EL expressions are explained in a subsequent
chapter). Note that in XML files, you cannot use expressions such as ${whatever
> 0}, because the greater than signs are illegal. Instead, use the gt form, such as
${whatever gt 0} or an alternative is to embed the value in a CDATA section.
• <jsp:text><![CDATA[<br>]]></jsp:text>
NMITD, DR. RUCHI, AP

144 <jsp:text><![CDATA[<!DOCTYPE html PUBLIC "-//W3C//DTD


XHTML 1.0 Strict//EN"
"DTD/[Link]">]]></jsp:text>

<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);

•The major disadvantage of cookies is browser provides a way to disable


the cookies and in that case server will not be able to identify the user.

•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 }

my_cookies = [Link](); %>

if( my_cookies != null ) </body>

{ </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

169 Custom Tags in JSP


• A custom tag may be a user-defined JSP language element.
• The JSP page contains a custom tag which is translated into a servlet, those tag is converted to operations on
a tag handler.
• When the JSP page’s servlet is executed the web container then invokes those operations.
• The standard JSP tags simplify all JSP page development and maintenance. It provides a mechanism for
encapsulating other sorts of dynamic functionality in custom tags.
• Some examples include operating on implicit objects, processing forms, accessing databases and other
enterprise services like email and directories, and implementing flow control.
• Custom tags increase productivity because they will be reused in additional than one application.
• Custom tags are distributed in a tag library, which defines a set of related custom tags and contains the
objects that implement the tags. The object that implements a custom tag is named a tag handler.
• Syntax: <prefix_Name : tag_Name>—–Body—–</prefix_Name>
NMITD, DR. RUCHI, AP

170 Why we need custom tags?

• 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

171 How to create Custom Tags?


• JSP page with Taglib directives: It is used to make available the TLD files into the present JSP page
on the basis of custom tags prefix names.
• TLD (Tag Library Descriptor) file: This tag provides the mapping between custom tag names and
respective TagHandler classes.
• TagHandler class: It is a normal Java class that is able to provide the basic functionality for the
custom tags.
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]

• The tag handler class is implemented as part of a tag library.


• Then, reference the tag library in your JSP source using the JSP <taglib> directive and include this directive at the top
of your JSP source.
• Then write the tag library descriptor (TLD) which defines the tag library and provides additional information about
each tag, such as the name of the tag handler class, attributes, and other information about the tags.
• Then refer to the TLD in your Web application deployment descriptor ([Link]).
• Use your custom tag in your JSP.
NMITD, DR. RUCHI, AP

173 Features of Custom Tags in JSP:


• 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

174 Advantages of Custom Tags


• The key advantages of Custom tags are as follows:
[Link] the need of scriptlet tag The custom tags eliminates the need of scriptlet tag which is
considered bad programming approach in JSP.
[Link] of business logic from JSP The custom tags separate the the business logic from the
JSP page so that it may be easy to maintain.
[Link]-usability The custom tags makes the possibility to reuse the same business logic again and
again.
NMITD, DR. RUCHI, AP

175 Syntax to use custom tag

• 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

177 creating any custom tag


• For creating any custom tag, we need to follow following steps:
• Create the Tag handler class and perform action at the start or at the end of the tag.
• Create the Tag Library Descriptor (TLD) file and define tags
• Create the JSP file that uses the Custom tag defined in the TLD file
NMITD, DR. RUCHI, AP

178 Create the Tag handler class


package [Link];
• To create the Tag Handler, we are
import [Link];
inheriting the TagSupport class import [Link];
and overriding its method import [Link];
import [Link];
doStartTag().
public class MyTagHandler extends TagSupport{
• To write data for the jsp, we need
public int doStartTag() throws JspException {
to use the JspWriter class. JspWriter out=[Link]();//returns the instance of JspWriter
• The PageContext class provides try{
[Link]([Link]().getTime());//printing date and time
getOut() method that returns the using JspWriter
instance of JspWriter class. }catch(Exception e){[Link](e);}
return SKIP_BODY;//will not evaluate the body content of the tag
• TagSupport class provides }
instance of pageContext }
bydefault.
NMITD, DR. RUCHI, AP

179 Create the TLD file


<?xml version="1.0" encoding="ISO-8859-1" ?>
• Tag Library Descriptor <!DOCTYPE taglib
(TLD) file contains PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
information of tag and "[Link]
Tag Hander classes. <taglib>
• It must be contained
<tlib-version>1.0</tlib-version>
inside the WEB-INF <jsp-version>1.2</jsp-version>
directory. <short-name>simple</short-name>
<uri>[Link]

<tag>
<name>today</name>
<tag-class>[Link]</tag-class>
</tag>
</taglib>
NMITD, DR. RUCHI, AP

180 Create the JSP file


• Let's use the tag in our jsp file. Here,
<%@ taglib uri="WEB-INF/[Link]" prefix="m" %>
we are specifying the path of tld file Current Date and Time is:
directly. <m:today/>

• But it is recommended to use the uri


name instead of full path of tld file.
We will learn about uri later.
• It uses taglib directive to use the tags
defined in the tld file.
NMITD, DR. RUCHI, AP

181 Attributes in JSP Custom Tag


• There can be defined too many attributes for any custom tag. To define the attribute,
you need to perform two tasks:
• Define the property in the TagHandler class with the attribute name and define the
setter method
• define the attribute element inside the tag element in the TLD file
• Let's understand the attribute by the tag given below:
<m:cube number="4"></m:cube>
• Here m is the prefix, cube is the tag name and number is the attribute.
NMITD, DR. RUCHI, AP

182 Iteration using JSP Custom Tag


• We can iterate the body content of any tag using
the doAfterBody() method of IterationTag interface.
• Here we are going to use the TagSupport class which implements the
IterationTag interface.
• For iterating the body content, we need to use
the EVAL_BODY_AGAIN constant in the doAfterBody() method.
NMITD, DR. RUCHI, AP

183 Custom URI in JSP Custom Tag

• 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

185 Create a Tag Library Descriptor (TLD) file:


This XML file defines the custom tag. Create a file named [Link]

<?xml version="1.0" encoding="UTF-8"?> <short-name>custom</short-name>


<taglib xmlns="[Link] <uri>/WEB-INF/[Link]</uri>

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]:

package [Link]; JspWriter out = [Link]();

import [Link]; // Write the "Hello, World!" message


import [Link]; [Link]("Hello, World!");
import [Link]; } catch (Exception e) {
throw new JspException(e);
public class HelloWorldTagHandler extends }
TagSupport {
@Override return SKIP_BODY;
public int doStartTag() throws JspException { }
try { }
// Get the JspWriter to write content to the
response

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.

You might also like