SlideShare a Scribd company logo
JSP-Java Server Pages
Prepared By
Yogaraja C A
Ramco Institute of Technology
Introduction
Java Server Pages (JSP) is a server-side programming
technology that enables the creation of dynamic,
platform-independent method for building Web-
based applications.
JSP have access to the entire family of Java APIs,
including the JDBC API to access enterprise
databases.
Introduction
Developers can insert java code in HTML pages by
making use of special JSP tags, most of which start
with <% and end with %>.
A JavaServer Pages component is a type of Java
servlet that is designed to fulfill the role of a user
interface for a Java web application.
Web developers write JSPs as text files that
combine HTML or XHTML code, XML elements, and
embedded JSP actions and commands.
Architecture
 The web server needs a JSP engine, i.e, a container to process
JSP pages. The JSP container is responsible for intercepting
requests for JSP pages.
 A JSP container works with the Web server to provide the
runtime environment and other services a JSP needs.
JSP Processing
 As with a normal page, browser sends an HTTP request to
the web server.
 The web server recognizes that the HTTP request is for a
JSP page and forwards it to a JSP engine. This is done by
using the URL or JSP page which ends with .jsp instead of
.html.
 The JSP engine loads the JSP page from disk and converts
it into a servlet content. This conversion is very simple in
which all template text is converted to println( )
statements and all JSP elements are converted to Java
code. This code implements the corresponding dynamic
behavior of the page.
JSP Processing
 The JSP engine compiles the servlet into an executable class
and forwards the original request to a servlet engine.
 A part of the web server called the servlet engine loads the
Servlet class and executes it. During execution, the servlet
produces an output in HTML format. The output is further
passed on to the web server by the servlet engine inside an
HTTP response.
 The web server forwards the HTTP response to your browser
in terms of static HTML content.
 Finally, the web browser handles the dynamically-generated
HTML page inside the HTTP response exactly as if it were a
static page.
JSP- JAVA SERVER PAGES
JSP Life Cycle
 The major phases of a JSP life cycle are very similar to
the Servlet Life Cycle.
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to
see whether it needs to compile the page. If the page has
never been compiled, or if the JSP has been modified since
it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps −
 Parsing the JSP.
 Turning the JSP into a servlet.
 Compiling the servlet.
JSP Initialization
 When a container loads a JSP it invokes the jspInit() method
before servicing any requests. If you need to perform JSP-
specific initialization, override the jspInit() method −
public void jspInit()
{
// Initialization code...
}
 Typically, initialization is performed only once and as with the
servlet init method, you generally initialize database
connections, open files, and create lookup tables in the
jspInit method.
JSP Execution
 Whenever a browser requests a JSP and the page has
been loaded and initialized, the JSP engine invokes the
_jspService() method in the JSP.
 The _jspService() method takes an HttpServletRequest
and an HttpServletResponse as its parameters as
follows −
void _jspService(HttpServletRequest request,
HttpServletResponse response)
{
// Service handling code...
}
JSP Execution
 The _jspService() method of a JSP is invoked on
request basis.
 This is responsible for generating the response for
that request and this method is also responsible for
generating responses to all seven of the HTTP
methods, i.e, GET, POST, DELETE, etc.
JSP Cleanup
 The destruction phase of the JSP life cycle represents
when a JSP is being removed from use by a container.
 The jspDestroy() method is the JSP equivalent of the
destroy method for servlets. Override jspDestroy
when you need to perform any cleanup, such as
releasing database connections or closing open files.
public void jspDestroy()
{
// Your cleanup code goes here.
}
Elements of JSP
The Scriptlet
 A scriptlet can contain any number of JAVA language
statements, variable or method declarations, or
expressions that are valid in the page scripting
language.
 syntax
<% code fragment %>
JSP Helloworld
<html>
<head>
<title>Hello World</title>
</head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
JSP Declarations
 A declaration declares one or more variables or
methods that you can use in Java code later in the
JSP file.
 You must declare the variable or method before you
use it in the JSP file.
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
JSP Expression
 A JSP expression element contains a scripting language
expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file.
<html>
<head>
<title>Test</title>
</head>
<body>
<p>Today's date: <%= (new
java.util.Date()).toLocaleString()%></p>
</body> </html>
JSP Comments
JSP comment marks text or statements that the
JSP container should ignore.
 A JSP comment is useful when you want to hide
or "comment out", a part of your JSP page.
Syntax
<%-- This is JSP comment --%>
JSP Implicit Objects
Object Description
request This is the HttpServletRequest object associated with the request.
response
This is the HttpServletResponse object associated with the response to the
client.
out This is the PrintWriter object used to send output to the client.
session This is the HttpSession object associated with the request.
application This is the ServletContext object associated with the application context.
config This is the ServletConfig object associated with the page.
page
This is simply a synonym for this, and is used to call the methods defined by
the translated servlet class.
Exception
The Exception object allows the exception data to be accessed by
designated JSP.
if...else
<%! int day = 3; %>
<html> <head>
<title>IF...ELSE Example</title>
</head> <body>
<% if (day == 1 || day == 7)
{ %>
<p> Today is weekend</p>
<% }
else
{ %>
<p> Today is not weekend</p>
<% } %>
</body> </html>
JSP - Directives
Directives provide directions and instructions to the
container, telling it how to handle certain aspects of the
JSP processing.
Syntax: <%@ directive attribute = "value" %>
 Directives can have a number of attributes which you
can list down as key-value pairs and separated by
commas.
 The blanks between the @ symbol and the directive
name, and between the last attribute and the closing
%>, are optional.
Types of directive
Directive Description
<%@ page ... %>
Defines page-dependent attributes, such
as scripting language, error page, and
buffering requirements.
<%@ include ... %> Includes a file during the translation
phase.
<%@ taglib ... %> Declares a tag library, containing custom
actions, used in the page
Page Directive
The page directive is used to provide instructions
to the container.
These instructions pertain to the current JSP
page.
You may code page directives anywhere in your
JSP page. By convention, page directives are
coded at the top of the JSP page.
<%@ page attribute = "value" %>
<%@ page import = "java.io.*,java.util.*" %>
Include Directive
The include directive is used to include a file
during the translation phase.
This directive tells the container to merge the
content of other external files with the
current JSP during the translation phase.
You may code the include directives anywhere
in your JSP page.
<%@ include file = "relative url" >
Taglib Directive
 The JavaServer Pages API allow you to define custom
JSP tags that look like HTML or XML tags and a tag
library is a set of user-defined tags that implement
custom behavior.
 <%@ taglib uri="uri" prefix = "prefixOfTag" >
uri attribute value resolves to a location the container
understands
prefix attribute informs a container what bits of markup
are custom actions.
Form Processing
The browser uses two methods to pass this
information to the web server.
These methods are the GET Method and the
POST Method.
GET method
 The GET method sends the encoded user information
appended to the page request.
 The page and the encoded information are separated by
the ? character as follows −
 http://www.test.com/hello?key1=value1&key2=value2
 The GET method is the default method to pass
information from the browser to the web server and it
produces a long string that appears in your browser's
Location:box.
GET method
 It is recommended that the GET method is better not
used, if you have password or other sensitive
information to pass to the server.
 The GET method has size limitation: only 1024
characters can be in a request string.
POST method
 A generally more reliable method of passing information
to a backend program is the POST method.
 This method packages the information in exactly the
same way as the GET method, but instead of sending it
as a text string after a ? in the URL it sends it as a
separate message.
Reading Form Data using JSP
 getParameter() − You call request.getParameter()
method to get the value of a form parameter.
 getParameterValues() − Call this method if the
parameter appears more than once and returns
multiple values, for example checkbox.
 getParameterNames() − Call this method if you want a
complete list of all parameters in the current request.
 getInputStream() − Call this method to read binary
data stream coming from the client.
GET Method Example Using URL
<html> <head>
<title>Using GET Method to Read Form Data</title>
</head> <body>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last")%>
</p></li>
</ul>
</body> </html>
http://localhost:8080/
main.jsp?first=arun&la
st=raj
GET Method Example Using Form
<html>
<body>
<form action = "main.jsp" method = "GET">
First Name: <input type = "text" name = "first"> <br />
Last Name: <input type = "text" name = "last” />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
main.jsp
<html> <head>
<title>Using GET and POST Method to Read Form Data</title>
</head> <body> <center>
<h1>Using POST Method to Read Form Data</h1>
<ul>
<li><p>
<b>First Name:</b> <%= request.getParameter("first")%> </p></li>
<li><p>
<b>Last Name:</b> <%= request.getParameter("last")%> </p></li>
</ul>
</body> </html>
JSP COOKIES
Creating a Cookie object
Setting the maximum age
Sending the Cookie into the HTTP response headers
Reading Cookies with JSP
Delete Cookies with JSP
Creating a Cookie object
You call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.
 Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should
contain white space or any of the following characters −
[ ] ( ) = , " / ? @ : ;
Setting the maximum age
You use setMaxAge to specify how long (in
seconds) the cookie should be valid. The
following code will set up a cookie for 24
hours.
cookie.setMaxAge(60*60*24);
Sending the Cookie into the HTTP response
You use response.addCookie to add cookies
in the HTTP response header as follows
response.addCookie(cookie);
Example
<%
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
response.addCookie( firstName );
response.addCookie( lastName );
%>
Example
<html> <head>
<title>Setting Cookies</title>
</head>
<body> <center> <h1>Setting Cookies</h1>
</center> <ul>
<li><p><b>First Name:</b> <%=
request.getParameter("first_name")%> </p></li>
<li><p><b>Last Name:</b> <%=
request.getParameter("last_name")%> </p></li>
</ul>
</body> </html>
Example
<html> <body>
<form action = "main.jsp" method = "GET">
First Name: <input type = "text" name = "first_name"> <br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body> </html>
Reading Cookies with JSP
 To read cookies, you need to create an array of
javax.servlet.http.Cookie objects by calling the
getCookies( ) method of HttpServletRequest.
 Then cycle through the array, and use getName() and
getValue() methods to access each cookie and
associated value.
Example
<%
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null )
{
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++)
{
cookie = cookies[i];
Example
for (int i = 0; i < cookies.length; i++)
{
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}
else
{ out.println("<h2>No cookies founds</h2>"); }
%>
Delete Cookies with JSP
To delete cookies is very simple. If you want to delete a
cookie, then you simply need to follow these three steps −
 Read an already existing cookie and store it in Cookie
object.
 Set cookie age as zero using the setMaxAge() method to
delete an existing cookie.
 Add this cookie back into the response header.
JSP - Standard Tag Library (JSTL)
 JSTL is a collection of useful JSP tags which encapsulates
the core functionality common to many JSP applications.
 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 the existing
custom tags with the JSTL tags.
Classification of The JSTL Tags
The JSTL tags can be classified, according to their
functions, into the following JSTL tag library groups
that can be used when creating a JSP page −
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions
Core Tags
The core group of tags are the most commonly
used JSTL tags. Following is the syntax to include
the JSTL Core library in your JSP −
<%@ taglib prefix = "c" uri =
"http://java.sun.com/jsp/jstl/core" %>
Core Tags
<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>.
Core Tags
<c:when> Subtag of <choose> that includes its body if its
condition evalutes to 'true'.
<c:otherwise > Subtag of <choose> that follows the
<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 .
The <c:out> tag has the following attributes −
Attribute Description Required Default
Value
Information to
output
Yes None
default Fallback
information to
output
No
body
escapeXml True if the tag
should escape
special XML
characters
No
true
The <c:set>tag has the following attributes −
Attribute Description Required Default
Value Information to save No body
target
Name of the variable whose
property should be
modified
No None
property Property to modify No None
var
Name of the variable to
store information
No None
scope
Scope of variable to store
information
No Page
The <c:if>tag has the following attributes −
Attribute Description Required Default
test Condition to evaluate Yes None
var
Name of the variable to
store the condition's result
No None
scope
Scope of the variable to
store the condition's result
No page
The <c:when>tag has the following attributes −
Attribute Description Required Default
test Condition to evaluate Yes None
The <c:redirect>tag has the following attributes −
Attribute Description Required Default
url URL to redirect the user's
browser to
Yes None
context
/ followed by the name of a
local web application
No
Current
application
The <c:import>tag has the following attributes −
Attribute Description Required Default
url URL to retrieve and import into
the page
Yes None
context
/ followed by the name of a local
web application
No
Current
application
charEncoding
Character set to use for imported
data
No ISO-8859-1
var
Name of the variable to store
imported text
No Print to page
scope
Scope of the variable used to
store imported text
No Page
varReader
Name of an alternate variable to
expose java.io.Reader
No None
The <c:forEach>tag has the following attributes −
Attribute Description Required Default
items Information to loop over No None
begin
Element to start with (0 = first
item, 1 = second item, ...)
No 0
end
Element to end with (0 = first
item, 1 = second item, ...)
No Last element
step Process every step items No 1
var
Name of the variable to expose
the current item
No None
varStatus
Name of the variable to expose
the loop status
No None
Example-1
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html> <head>
<title> c:removeTag Example</title>
</head> <body>
<c:set var = "salary" scope = "session" value = "${2000*2}"/>
<p>Before Remove Value: <c:out value = "${salary}"/></p>
<c:remove var = "salary"/>
<p>After Remove Value: <c:out value = "${salary}"/></p>
</body> </html>
Example-2
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html> <head>
<title> c:if Tag Example</title>
</head> <body>
<c:set var = "salary" scope = "session" value = "${2000*2}"/>
<c:if test = "${salary > 2000}">
<p>My salary is: <c:out value = "${salary}"/><p>
</c:if>
</body> </html>
Example-3
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html> <head>
<title><c:choose> Tag Example</title> </head> <body>
<c:set var = "salary" scope = "session" value = "${2000*2}"/>
<p>Your salary is : <c:out value = "${salary}"/></p>
<c:choose>
<c:when test = "${salary <= 0}">
Salary is very low to survive.
</c:when>
Example-3
<c:when test = "${salary > 1000}">
Salary is very good.
</c:when>
<c:otherwise>
No comment sir...
</c:otherwise>
</c:choose>
</body>
</html
Formatting Tags
The JSTL formatting tags are used to format and
display text, the date, the time, and numbers for
internationalized Websites.
Following is the syntax to include Formatting library
in your JSP −
<%@ taglib prefix = "fmt" uri =
"http://java.sun.com/jsp/jstl/fmt" %>
Formatting Tags
<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.
Formatting Tags
<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> Displays an internationalized message.
<fmt:requestEncoding> Sets the request character encoding
The <fmt:formatDate>tag has the following attributes −
Attribute Description Required Default
Value Date value to display Yes None
type DATE, TIME, or BOTH No date
dateStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No default
timeStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No default
pattern Custom formatting pattern No None
timeZone
Time zone of the displayed date
No
Default time
zone
var
Name of the variable to store the formatted
date
No Print to page
scope
Scope of the variable to store the formatted
date
No page
The <fmt:parseNumber>tag has the following attributes −
Attribute Description Required Default
Value Numeric value to read (parse) No Body
type NUMBER, CURRENCY, or PERCENT No number
parseLocale Locale to use when parsing the number No Default locale
integerOnly
Whether to parse to an integer (true) or floating-
point number (false)
No false
pattern Custom parsing pattern No None
timeZone Time zone of the displayed date
No
Default time zone
var
Name of the variable to store the parsed number
No Print to page
scope
Scope of the variable to store the formatted
number
No page
Example-1
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html> <head>
<title>JSTL fmt:parseNumber Tag</title>
</head> <body>
<h3>Number Parsing:</h3>
<c:set var = "balance" value = "1250003.350" />
<fmt:parseNumber var = "i" type = "number" value = "${balance}" />
<p>Parsed Number (1) : <c:out value = "${i}" /></p>
Example-1
<fmt:parseNumber var = "i" integerOnly = "true" type = "number"
value = "${balance}" />
<p>Parsed Number (2) : <c:out value = "${i}" /></p>
</body> </html>
OUTPUT
Number Parsing:
Parsed Number (1) : 1250003.35
Parsed Number (2) : 1250003
Example-2
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html> <head>
<title>JSTL fmt:dateNumber Tag</title>
</head> <body>
<h3>Number Format:</h3>
<c:set var = "now" value = "<% = new java.util.Date()%>" />
<p>Formatted Date (1): <fmt:formatDate type = "time" value =
"${now}" /></p>
Example-2
<p>Formatted Date (2): <fmt:formatDate type = "date" value =
"${now}" /></p>
<p>Formatted Date (3): <fmt:formatDate type = "both" value =
"${now}" /></p>
<p>Formatted Date (4): <fmt:formatDate type = "both" dateStyle =
"short" timeStyle = "short" value = "${now}" /></p>
<p>Formatted Date (5): <fmt:formatDate type = "both" dateStyle =
"medium" timeStyle = "medium" value = "${now}" /></p>
Example-2
<p>Formatted Date (6): <fmt:formatDate type = "both" dateStyle =
"long" timeStyle = "long" value = "${now}" /></p>
<p>Formatted Date (7): <fmt:formatDate pattern = "yyyy-MM-dd"
value = "${now}" /></p>
</body>
</html>
Example-2
OUTPUT:
Date Format:
Formatted Date (1): 14:27:18
Formatted Date (2): 23-Sep-2010
Formatted Date (3): 23-Sep-2010 14:27:18
Formatted Date (4): 23/09/10 14:27
Formatted Date (5): 23-Sep-2010 14:27:18
Formatted Date (6): 23 September 2010 14:27:18 GST
Formatted Date (7): 2010-09-23
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 =
"http://java.sun.com/jsp/jstl/sql" %>
SQL Tags
<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
java.util.Date value.
<sql:transaction > Provides nested database action elements with a shared
Connection, set up to execute all statements as one transaction.
The <sql:setDataSource>tag has the following attributes −
Attribute Description Required Default
driver Name of the JDBC driver class to be
registered
No None
url JDBC URL for the database connection No None
user Database username No None
password Database password No None
dataSource Database prepared in advance No None
var
Name of the variable to represent the
database
No
Set default
scope
Scope of the variable to represent the
database
No Page
The <sql:query>tag has the following attributes −
Attribute Description Required Default
sql SQL command to execute (should return
a ResultSet)
No
Body
dataSource Database connection to use (overrides
the default)
No
Default
database
maxRows Maximum number of results to store in
the variable
No
Unlimited
startRow Number of the row in the result at which
to start recording
No
0
var
Name of the variable to represent the
database
No
Set default
The <sql:update>tag has the following attributes −
Attribute Description Required Default
sql SQL command to execute (should not
return a ResultSet)
No
Body
dataSource Database connection to use (overrides
the default)
No
Default
database
var
Name of the variable to store the count
of affected rows
No None
scope
Scope of the variable to store the count
of affected rows
No Page
Example-1
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
<html> <head>
<title>JSTL sql:setDataSource Tag</title>
</head> <body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST" user = "user_id" password =
"mypassword"/>
<sql:query dataSource = "${snapshot}" var = "result" >
SELECT * from Employees; </sql:query>
Example-1
<table> <tr>
<th>Emp ID</th> <th>First Name</th>
<th>Last Name</th> <th>Age</th> </tr>
<c:forEach var = "row" items = "${result.rows}">
<tr> <td><c:out value = "${row.id}"/></td>
<td><c:out value = "${row.first}"/></td>
<td><c:out value = "${row.last}"/></td>
<td><c:out value = "${row.age}"/></td> </tr>
</c:forEach>
</table></body></html>
XML tags
 The JSTL XML tags provide a JSP-centric way of creating and
manipulating the XML documents.
 The JSTL XML tag library has custom tags for interacting with
the XML data.
 This includes parsing the XML, transforming the XML data, and
the flow control based on the XPath expressions.
 <%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml"
%>
XML tags
<x:out> Like <%= ... >, but for XPath expressions.
<x:parse> Used to parse the XML data specified either via an
attribute or in the tag body.
<x:set > Sets a variable to the value of an XPath expression.
<x:if > Evaluates a test XPath expression and if it is true, it
processes its body. If the test condition is false, the body is
ignored.
<x:forEach> To loop over nodes in an XML document.
XML tags
<x:choose> Simple conditional tag that establishes a context for
mutually exclusive conditional operations, marked by <when>
and <otherwise> tags.
<x:when > Subtag of <choose> that includes its body if its
expression evalutes to 'true'.
<x:otherwise > Subtag of <choose> that follows the <when> tags
and runs only if all of the prior conditions evaluates to 'false'.
<x:transform > Applies an XSL transformation on a XML
document
<x:param > Used along with the transform tag to set a parameter
in the XSLT stylesheet
The <x:out>tag has the following attributes −
Attribute Description Required Default
select XPath expression to evaluate as a string,
often using XPath variables
Yes None
escapeXml True if the tag should escape special XML
characters
No true
The <x:parse>tag has the following attributes −
Attribute Description Required Default
var A variable that contains the parsed XML data No None
xml Text of the document to parse (String or
Reader)
No
Body
systemId The system identifier URI for parsing the
document
No None
filter The filter to be applied to the source
document
No None
doc XML document to be parsed No Page
scope
Scope of the variable specified in the var
attribute
No Page
varDom A variable that contains the parsed XML data
No Page
scopeDom Scope of the variable specified in the varDom
attribute
No Page
The <x:set>tag has the following attributes −
Attribute Description Required Default
var
A variable that is set to the value of the
XPath expression
Yes
Body
select The XPath expression to be evaluated No None
scope
Scope of the variable specified in the var
attribute
No Page
Example-1
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>JSTL x:out Tags</title>
</head>
<body>
<h3>Books Info:</h3>
<c:set var = "xmltext">
Example-1
<books>
<book>
<name>History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
Example-1
</book>
</books>
</c:set>
<x:parse xml = "${xmltext}" var = "output"/>
<b>The title of the first book is</b>:
<x:out select = "$output/books/book[1]/name" />
<br>
<b>The price of the second book</b>:
<x:out select = "$output/books/book[2]/price" />
</body> </html>
Example-1
OUTPUT:
Books Info:
The title of the first book is: History The price of the second book:
2000
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 =
"http://java.sun.com/jsp/jstl/functions" %>
JSTL Functions
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 can be
interpreted as XML markup.
fn:indexOf() Returns the index withing a string of the
first occurrence of a specified substring.
JSTL Functions
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.
fn:startsWith() Tests if an input string starts with the
specified prefix.
JSTL Functions
fn:substring() Returns a subset of a string.
fn:substringAfter() Returns a subset of a string following a
specific substring.
fn:substringBefore() Returns a subset of a string before a specific
substring.
fn:toLowerCase() Converts all of the characters of a string to
lower case.
fn:toUpperCase() Converts all of the characters of a string to
upper case.
Example-1 fn:contains()
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn"
%>
<html> <head>
<title>Using JSTL Functions</title>
</head> <body>
<c:set var = "S" value = "I am a test String"/>
<c:if test = "${fn:contains(S, 'test')}">
<p>Found test string<p>
</c:if>
Example-1fn:contains()
<c:if test = "${fn:contains(S, 'TEST')}">
<p>Found TEST string<p>
</c:if>
</body>
</html>
OUTPUT:
Found test string
Example-2
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<html> <head>
<title>Using JSTL Functions</title>
</head> <body>
<c:set var = "string1" value = "This is first String."/>
<p>Index (1) : ${fn:indexOf(string1, "first")}</p>
<c:set var = "string2" value = "${fn:toUpperCase(string1)}" />
<p>Final string : ${string2}</p>
</body> </html>
Example-2
OUTPUT:
Index (1) : 8
Final string : THIS IS FIRST STRING.
Ad

More Related Content

What's hot (20)

Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Java script
Java scriptJava script
Java script
reddivarihareesh
 
Enterprise java unit-3_chapter-1-jsp
Enterprise  java unit-3_chapter-1-jspEnterprise  java unit-3_chapter-1-jsp
Enterprise java unit-3_chapter-1-jsp
sandeep54552
 
Introduction to thymeleaf
Introduction to thymeleafIntroduction to thymeleaf
Introduction to thymeleaf
NexThoughts Technologies
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
Hema Prasanth
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
People Strategists
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Svelte the future of frontend development
Svelte   the future of frontend developmentSvelte   the future of frontend development
Svelte the future of frontend development
twilson63
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
Eyal Vardi
 
Jsp
JspJsp
Jsp
Pooja Verma
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 
Javascript
JavascriptJavascript
Javascript
Momentum Design Lab
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
Hitesh-Java
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Enterprise java unit-3_chapter-1-jsp
Enterprise  java unit-3_chapter-1-jspEnterprise  java unit-3_chapter-1-jsp
Enterprise java unit-3_chapter-1-jsp
sandeep54552
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 
Svelte the future of frontend development
Svelte   the future of frontend developmentSvelte   the future of frontend development
Svelte the future of frontend development
twilson63
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
Eyal Vardi
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
Hitesh-Java
 

Similar to JSP- JAVA SERVER PAGES (20)

JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
Kalpana T
 
Unit 4 1 web technology uptu
Unit 4 1 web technology uptuUnit 4 1 web technology uptu
Unit 4 1 web technology uptu
Abhishek Kesharwani
 
Unit 4 web technology uptu
Unit 4 web technology uptuUnit 4 web technology uptu
Unit 4 web technology uptu
Abhishek Kesharwani
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
NishaRohit6
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdf
Arumugam90
 
Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jsp
Atul Giri
 
Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
ManishaPatil932723
 
Java server pages
Java server pagesJava server pages
Java server pages
Abhishek Kesharwani
 
Jsp
JspJsp
Jsp
Maheshit Jtc
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
Vipin Yadav
 
Module 3.pptx.............................
Module 3.pptx.............................Module 3.pptx.............................
Module 3.pptx.............................
Betty333100
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
MathivananP4
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorial
shiva404
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
Geethu Mohan
 
JSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODSJSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODS
bharathiv53
 
J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
Biswabrata Banerjee
 
Jsp
JspJsp
Jsp
Rahul Goyal
 
Jsp
JspJsp
Jsp
Rahul Goyal
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
Kalpana T
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdf
Arumugam90
 
Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jsp
Atul Giri
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
Vipin Yadav
 
Module 3.pptx.............................
Module 3.pptx.............................Module 3.pptx.............................
Module 3.pptx.............................
Betty333100
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
MathivananP4
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorial
shiva404
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
Geethu Mohan
 
JSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODSJSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODS
bharathiv53
 
Ad

More from Yoga Raja (10)

Ajax
AjaxAjax
Ajax
Yoga Raja
 
Php
PhpPhp
Php
Yoga Raja
 
Xml
XmlXml
Xml
Yoga Raja
 
Database connect
Database connectDatabase connect
Database connect
Yoga Raja
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
JSON
JSONJSON
JSON
Yoga Raja
 
Java script
Java scriptJava script
Java script
Yoga Raja
 
Think-Pair-Share
Think-Pair-ShareThink-Pair-Share
Think-Pair-Share
Yoga Raja
 
Minute paper
Minute paperMinute paper
Minute paper
Yoga Raja
 
Decision support system-MIS
Decision support system-MISDecision support system-MIS
Decision support system-MIS
Yoga Raja
 
Ad

Recently uploaded (20)

UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 

JSP- JAVA SERVER PAGES

  • 1. JSP-Java Server Pages Prepared By Yogaraja C A Ramco Institute of Technology
  • 2. Introduction Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web- based applications. JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases.
  • 3. Introduction Developers can insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>. A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.
  • 4. Architecture  The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages.  A JSP container works with the Web server to provide the runtime environment and other services a JSP needs.
  • 5. JSP Processing  As with a normal page, browser sends an HTTP request to the web server.  The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.  The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code. This code implements the corresponding dynamic behavior of the page.
  • 6. JSP Processing  The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.  A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format. The output is further passed on to the web server by the servlet engine inside an HTTP response.  The web server forwards the HTTP response to your browser in terms of static HTML content.  Finally, the web browser handles the dynamically-generated HTML page inside the HTTP response exactly as if it were a static page.
  • 8. JSP Life Cycle  The major phases of a JSP life cycle are very similar to the Servlet Life Cycle.
  • 9. JSP Compilation When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. The compilation process involves three steps −  Parsing the JSP.  Turning the JSP into a servlet.  Compiling the servlet.
  • 10. JSP Initialization  When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP- specific initialization, override the jspInit() method − public void jspInit() { // Initialization code... }  Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.
  • 11. JSP Execution  Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.  The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows − void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... }
  • 12. JSP Execution  The _jspService() method of a JSP is invoked on request basis.  This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.
  • 13. JSP Cleanup  The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.  The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files. public void jspDestroy() { // Your cleanup code goes here. }
  • 14. Elements of JSP The Scriptlet  A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.  syntax <% code fragment %>
  • 15. JSP Helloworld <html> <head> <title>Hello World</title> </head> <body> Hello World!<br/> <% out.println("Your IP address is " + request.getRemoteAddr()); %> </body> </html>
  • 16. JSP Declarations  A declaration declares one or more variables or methods that you can use in Java code later in the JSP file.  You must declare the variable or method before you use it in the JSP file. <%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>
  • 17. JSP Expression  A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. <html> <head> <title>Test</title> </head> <body> <p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p> </body> </html>
  • 18. JSP Comments JSP comment marks text or statements that the JSP container should ignore.  A JSP comment is useful when you want to hide or "comment out", a part of your JSP page. Syntax <%-- This is JSP comment --%>
  • 19. JSP Implicit Objects Object Description request This is the HttpServletRequest object associated with the request. response This is the HttpServletResponse object associated with the response to the client. out This is the PrintWriter object used to send output to the client. session This is the HttpSession object associated with the request. application This is the ServletContext object associated with the application context. config This is the ServletConfig object associated with the page. page This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. Exception The Exception object allows the exception data to be accessed by designated JSP.
  • 20. if...else <%! int day = 3; %> <html> <head> <title>IF...ELSE Example</title> </head> <body> <% if (day == 1 || day == 7) { %> <p> Today is weekend</p> <% } else { %> <p> Today is not weekend</p> <% } %> </body> </html>
  • 21. JSP - Directives Directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing. Syntax: <%@ directive attribute = "value" %>  Directives can have a number of attributes which you can list down as key-value pairs and separated by commas.  The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional.
  • 22. Types of directive Directive Description <%@ page ... %> Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. <%@ include ... %> Includes a file during the translation phase. <%@ taglib ... %> Declares a tag library, containing custom actions, used in the page
  • 23. Page Directive The page directive is used to provide instructions to the container. These instructions pertain to the current JSP page. You may code page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page. <%@ page attribute = "value" %> <%@ page import = "java.io.*,java.util.*" %>
  • 24. Include Directive The include directive is used to include a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code the include directives anywhere in your JSP page. <%@ include file = "relative url" >
  • 25. Taglib Directive  The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.  <%@ taglib uri="uri" prefix = "prefixOfTag" > uri attribute value resolves to a location the container understands prefix attribute informs a container what bits of markup are custom actions.
  • 26. Form Processing The browser uses two methods to pass this information to the web server. These methods are the GET Method and the POST Method.
  • 27. GET method  The GET method sends the encoded user information appended to the page request.  The page and the encoded information are separated by the ? character as follows −  http://www.test.com/hello?key1=value1&key2=value2  The GET method is the default method to pass information from the browser to the web server and it produces a long string that appears in your browser's Location:box.
  • 28. GET method  It is recommended that the GET method is better not used, if you have password or other sensitive information to pass to the server.  The GET method has size limitation: only 1024 characters can be in a request string.
  • 29. POST method  A generally more reliable method of passing information to a backend program is the POST method.  This method packages the information in exactly the same way as the GET method, but instead of sending it as a text string after a ? in the URL it sends it as a separate message.
  • 30. Reading Form Data using JSP  getParameter() − You call request.getParameter() method to get the value of a form parameter.  getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.  getParameterNames() − Call this method if you want a complete list of all parameters in the current request.  getInputStream() − Call this method to read binary data stream coming from the client.
  • 31. GET Method Example Using URL <html> <head> <title>Using GET Method to Read Form Data</title> </head> <body> <h1>Using GET Method to Read Form Data</h1> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last")%> </p></li> </ul> </body> </html> http://localhost:8080/ main.jsp?first=arun&la st=raj
  • 32. GET Method Example Using Form <html> <body> <form action = "main.jsp" method = "GET"> First Name: <input type = "text" name = "first"> <br /> Last Name: <input type = "text" name = "last” /> <input type = "submit" value = "Submit" /> </form> </body> </html>
  • 33. main.jsp <html> <head> <title>Using GET and POST Method to Read Form Data</title> </head> <body> <center> <h1>Using POST Method to Read Form Data</h1> <ul> <li><p> <b>First Name:</b> <%= request.getParameter("first")%> </p></li> <li><p> <b>Last Name:</b> <%= request.getParameter("last")%> </p></li> </ul> </body> </html>
  • 34. JSP COOKIES Creating a Cookie object Setting the maximum age Sending the Cookie into the HTTP response headers Reading Cookies with JSP Delete Cookies with JSP
  • 35. Creating a Cookie object You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.  Cookie cookie = new Cookie("key","value"); Keep in mind, neither the name nor the value should contain white space or any of the following characters − [ ] ( ) = , " / ? @ : ;
  • 36. Setting the maximum age You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code will set up a cookie for 24 hours. cookie.setMaxAge(60*60*24);
  • 37. Sending the Cookie into the HTTP response You use response.addCookie to add cookies in the HTTP response header as follows response.addCookie(cookie);
  • 38. Example <% Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); response.addCookie( firstName ); response.addCookie( lastName ); %>
  • 39. Example <html> <head> <title>Setting Cookies</title> </head> <body> <center> <h1>Setting Cookies</h1> </center> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> </body> </html>
  • 40. Example <html> <body> <form action = "main.jsp" method = "GET"> First Name: <input type = "text" name = "first_name"> <br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> </body> </html>
  • 41. Reading Cookies with JSP  To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest.  Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.
  • 42. Example <% Cookie cookie = null; Cookie[] cookies = null; cookies = request.getCookies(); if( cookies != null ) { out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i];
  • 43. Example for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } } else { out.println("<h2>No cookies founds</h2>"); } %>
  • 44. Delete Cookies with JSP To delete cookies is very simple. If you want to delete a cookie, then you simply need to follow these three steps −  Read an already existing cookie and store it in Cookie object.  Set cookie age as zero using the setMaxAge() method to delete an existing cookie.  Add this cookie back into the response header.
  • 45. JSP - Standard Tag Library (JSTL)  JSTL is a collection of useful JSP tags which encapsulates the core functionality common to many JSP applications.  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 the existing custom tags with the JSTL tags.
  • 46. Classification of The JSTL Tags The JSTL tags can be classified, according to their functions, into the following JSTL tag library groups that can be used when creating a JSP page − Core Tags Formatting tags SQL tags XML tags JSTL Functions
  • 47. Core Tags The core group of tags are the most commonly used JSTL tags. Following is the syntax to include the JSTL Core library in your JSP − <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
  • 48. Core Tags <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>.
  • 49. Core Tags <c:when> Subtag of <choose> that includes its body if its condition evalutes to 'true'. <c:otherwise > Subtag of <choose> that follows the <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 .
  • 50. The <c:out> tag has the following attributes − Attribute Description Required Default Value Information to output Yes None default Fallback information to output No body escapeXml True if the tag should escape special XML characters No true
  • 51. The <c:set>tag has the following attributes − Attribute Description Required Default Value Information to save No body target Name of the variable whose property should be modified No None property Property to modify No None var Name of the variable to store information No None scope Scope of variable to store information No Page
  • 52. The <c:if>tag has the following attributes − Attribute Description Required Default test Condition to evaluate Yes None var Name of the variable to store the condition's result No None scope Scope of the variable to store the condition's result No page
  • 53. The <c:when>tag has the following attributes − Attribute Description Required Default test Condition to evaluate Yes None The <c:redirect>tag has the following attributes − Attribute Description Required Default url URL to redirect the user's browser to Yes None context / followed by the name of a local web application No Current application
  • 54. The <c:import>tag has the following attributes − Attribute Description Required Default url URL to retrieve and import into the page Yes None context / followed by the name of a local web application No Current application charEncoding Character set to use for imported data No ISO-8859-1 var Name of the variable to store imported text No Print to page scope Scope of the variable used to store imported text No Page varReader Name of an alternate variable to expose java.io.Reader No None
  • 55. The <c:forEach>tag has the following attributes − Attribute Description Required Default items Information to loop over No None begin Element to start with (0 = first item, 1 = second item, ...) No 0 end Element to end with (0 = first item, 1 = second item, ...) No Last element step Process every step items No 1 var Name of the variable to expose the current item No None varStatus Name of the variable to expose the loop status No None
  • 56. Example-1 <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <html> <head> <title> c:removeTag Example</title> </head> <body> <c:set var = "salary" scope = "session" value = "${2000*2}"/> <p>Before Remove Value: <c:out value = "${salary}"/></p> <c:remove var = "salary"/> <p>After Remove Value: <c:out value = "${salary}"/></p> </body> </html>
  • 57. Example-2 <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <html> <head> <title> c:if Tag Example</title> </head> <body> <c:set var = "salary" scope = "session" value = "${2000*2}"/> <c:if test = "${salary > 2000}"> <p>My salary is: <c:out value = "${salary}"/><p> </c:if> </body> </html>
  • 58. Example-3 <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <html> <head> <title><c:choose> Tag Example</title> </head> <body> <c:set var = "salary" scope = "session" value = "${2000*2}"/> <p>Your salary is : <c:out value = "${salary}"/></p> <c:choose> <c:when test = "${salary <= 0}"> Salary is very low to survive. </c:when>
  • 59. Example-3 <c:when test = "${salary > 1000}"> Salary is very good. </c:when> <c:otherwise> No comment sir... </c:otherwise> </c:choose> </body> </html
  • 60. Formatting Tags The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Websites. Following is the syntax to include Formatting library in your JSP − <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
  • 61. Formatting Tags <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.
  • 62. Formatting Tags <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> Displays an internationalized message. <fmt:requestEncoding> Sets the request character encoding
  • 63. The <fmt:formatDate>tag has the following attributes − Attribute Description Required Default Value Date value to display Yes None type DATE, TIME, or BOTH No date dateStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No default timeStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No default pattern Custom formatting pattern No None timeZone Time zone of the displayed date No Default time zone var Name of the variable to store the formatted date No Print to page scope Scope of the variable to store the formatted date No page
  • 64. The <fmt:parseNumber>tag has the following attributes − Attribute Description Required Default Value Numeric value to read (parse) No Body type NUMBER, CURRENCY, or PERCENT No number parseLocale Locale to use when parsing the number No Default locale integerOnly Whether to parse to an integer (true) or floating- point number (false) No false pattern Custom parsing pattern No None timeZone Time zone of the displayed date No Default time zone var Name of the variable to store the parsed number No Print to page scope Scope of the variable to store the formatted number No page
  • 65. Example-1 <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %> <html> <head> <title>JSTL fmt:parseNumber Tag</title> </head> <body> <h3>Number Parsing:</h3> <c:set var = "balance" value = "1250003.350" /> <fmt:parseNumber var = "i" type = "number" value = "${balance}" /> <p>Parsed Number (1) : <c:out value = "${i}" /></p>
  • 66. Example-1 <fmt:parseNumber var = "i" integerOnly = "true" type = "number" value = "${balance}" /> <p>Parsed Number (2) : <c:out value = "${i}" /></p> </body> </html> OUTPUT Number Parsing: Parsed Number (1) : 1250003.35 Parsed Number (2) : 1250003
  • 67. Example-2 <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %> <html> <head> <title>JSTL fmt:dateNumber Tag</title> </head> <body> <h3>Number Format:</h3> <c:set var = "now" value = "<% = new java.util.Date()%>" /> <p>Formatted Date (1): <fmt:formatDate type = "time" value = "${now}" /></p>
  • 68. Example-2 <p>Formatted Date (2): <fmt:formatDate type = "date" value = "${now}" /></p> <p>Formatted Date (3): <fmt:formatDate type = "both" value = "${now}" /></p> <p>Formatted Date (4): <fmt:formatDate type = "both" dateStyle = "short" timeStyle = "short" value = "${now}" /></p> <p>Formatted Date (5): <fmt:formatDate type = "both" dateStyle = "medium" timeStyle = "medium" value = "${now}" /></p>
  • 69. Example-2 <p>Formatted Date (6): <fmt:formatDate type = "both" dateStyle = "long" timeStyle = "long" value = "${now}" /></p> <p>Formatted Date (7): <fmt:formatDate pattern = "yyyy-MM-dd" value = "${now}" /></p> </body> </html>
  • 70. Example-2 OUTPUT: Date Format: Formatted Date (1): 14:27:18 Formatted Date (2): 23-Sep-2010 Formatted Date (3): 23-Sep-2010 14:27:18 Formatted Date (4): 23/09/10 14:27 Formatted Date (5): 23-Sep-2010 14:27:18 Formatted Date (6): 23 September 2010 14:27:18 GST Formatted Date (7): 2010-09-23
  • 71. 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 = "http://java.sun.com/jsp/jstl/sql" %>
  • 72. SQL Tags <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 java.util.Date value. <sql:transaction > Provides nested database action elements with a shared Connection, set up to execute all statements as one transaction.
  • 73. The <sql:setDataSource>tag has the following attributes − Attribute Description Required Default driver Name of the JDBC driver class to be registered No None url JDBC URL for the database connection No None user Database username No None password Database password No None dataSource Database prepared in advance No None var Name of the variable to represent the database No Set default scope Scope of the variable to represent the database No Page
  • 74. The <sql:query>tag has the following attributes − Attribute Description Required Default sql SQL command to execute (should return a ResultSet) No Body dataSource Database connection to use (overrides the default) No Default database maxRows Maximum number of results to store in the variable No Unlimited startRow Number of the row in the result at which to start recording No 0 var Name of the variable to represent the database No Set default
  • 75. The <sql:update>tag has the following attributes − Attribute Description Required Default sql SQL command to execute (should not return a ResultSet) No Body dataSource Database connection to use (overrides the default) No Default database var Name of the variable to store the count of affected rows No None scope Scope of the variable to store the count of affected rows No Page
  • 76. Example-1 <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%> <html> <head> <title>JSTL sql:setDataSource Tag</title> </head> <body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "user_id" password = "mypassword"/> <sql:query dataSource = "${snapshot}" var = "result" > SELECT * from Employees; </sql:query>
  • 77. Example-1 <table> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = "row" items = "${result.rows}"> <tr> <td><c:out value = "${row.id}"/></td> <td><c:out value = "${row.first}"/></td> <td><c:out value = "${row.last}"/></td> <td><c:out value = "${row.age}"/></td> </tr> </c:forEach> </table></body></html>
  • 78. XML tags  The JSTL XML tags provide a JSP-centric way of creating and manipulating the XML documents.  The JSTL XML tag library has custom tags for interacting with the XML data.  This includes parsing the XML, transforming the XML data, and the flow control based on the XPath expressions.  <%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>
  • 79. XML tags <x:out> Like <%= ... >, but for XPath expressions. <x:parse> Used to parse the XML data specified either via an attribute or in the tag body. <x:set > Sets a variable to the value of an XPath expression. <x:if > Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is false, the body is ignored. <x:forEach> To loop over nodes in an XML document.
  • 80. XML tags <x:choose> Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise> tags. <x:when > Subtag of <choose> that includes its body if its expression evalutes to 'true'. <x:otherwise > Subtag of <choose> that follows the <when> tags and runs only if all of the prior conditions evaluates to 'false'. <x:transform > Applies an XSL transformation on a XML document <x:param > Used along with the transform tag to set a parameter in the XSLT stylesheet
  • 81. The <x:out>tag has the following attributes − Attribute Description Required Default select XPath expression to evaluate as a string, often using XPath variables Yes None escapeXml True if the tag should escape special XML characters No true
  • 82. The <x:parse>tag has the following attributes − Attribute Description Required Default var A variable that contains the parsed XML data No None xml Text of the document to parse (String or Reader) No Body systemId The system identifier URI for parsing the document No None filter The filter to be applied to the source document No None doc XML document to be parsed No Page scope Scope of the variable specified in the var attribute No Page varDom A variable that contains the parsed XML data No Page scopeDom Scope of the variable specified in the varDom attribute No Page
  • 83. The <x:set>tag has the following attributes − Attribute Description Required Default var A variable that is set to the value of the XPath expression Yes Body select The XPath expression to be evaluated No None scope Scope of the variable specified in the var attribute No Page
  • 84. Example-1 <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %> <html> <head> <title>JSTL x:out Tags</title> </head> <body> <h3>Books Info:</h3> <c:set var = "xmltext">
  • 86. Example-1 </book> </books> </c:set> <x:parse xml = "${xmltext}" var = "output"/> <b>The title of the first book is</b>: <x:out select = "$output/books/book[1]/name" /> <br> <b>The price of the second book</b>: <x:out select = "$output/books/book[2]/price" /> </body> </html>
  • 87. Example-1 OUTPUT: Books Info: The title of the first book is: History The price of the second book: 2000
  • 88. 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 = "http://java.sun.com/jsp/jstl/functions" %>
  • 89. JSTL Functions 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 can be interpreted as XML markup. fn:indexOf() Returns the index withing a string of the first occurrence of a specified substring.
  • 90. JSTL Functions 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. fn:startsWith() Tests if an input string starts with the specified prefix.
  • 91. JSTL Functions fn:substring() Returns a subset of a string. fn:substringAfter() Returns a subset of a string following a specific substring. fn:substringBefore() Returns a subset of a string before a specific substring. fn:toLowerCase() Converts all of the characters of a string to lower case. fn:toUpperCase() Converts all of the characters of a string to upper case.
  • 92. Example-1 fn:contains() <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %> <html> <head> <title>Using JSTL Functions</title> </head> <body> <c:set var = "S" value = "I am a test String"/> <c:if test = "${fn:contains(S, 'test')}"> <p>Found test string<p> </c:if>
  • 93. Example-1fn:contains() <c:if test = "${fn:contains(S, 'TEST')}"> <p>Found TEST string<p> </c:if> </body> </html> OUTPUT: Found test string
  • 94. Example-2 <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %> <html> <head> <title>Using JSTL Functions</title> </head> <body> <c:set var = "string1" value = "This is first String."/> <p>Index (1) : ${fn:indexOf(string1, "first")}</p> <c:set var = "string2" value = "${fn:toUpperCase(string1)}" /> <p>Final string : ${string2}</p> </body> </html>
  • 95. Example-2 OUTPUT: Index (1) : 8 Final string : THIS IS FIRST STRING.