0% found this document useful (0 votes)
49 views31 pages

What Is Javaserver Pages?: vs. Active Server Pages (Asp)

This document provides information about JavaServer Pages (JSP) including what JSP is, how JSP works, common JSP tags, and advantages of using JSP over other technologies like ASP, servlets, SSI, JavaScript, and static HTML. Key points include: JSP allows inserting Java code into HTML pages using special tags, JSP pages combine HTML/XHTML, XML elements, and embedded actions/commands, and JSP can collect user input, access databases, and dynamically create webpages.

Uploaded by

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

What Is Javaserver Pages?: vs. Active Server Pages (Asp)

This document provides information about JavaServer Pages (JSP) including what JSP is, how JSP works, common JSP tags, and advantages of using JSP over other technologies like ASP, servlets, SSI, JavaScript, and static HTML. Key points include: JSP allows inserting Java code into HTML pages using special tags, JSP pages combine HTML/XHTML, XML elements, and embedded actions/commands, and JSP can collect user input, access databases, and dynamically create webpages.

Uploaded by

Minal Waghmare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

What is JavaServer Pages?

JavaServer Pages (JSP) is a technology for developing Webpages that


supports dynamic content. This helps developers insert java code in HTML
pages by making use of special JSP tags, most of which start with <% and
end with %>.

A JavaServer Pages component is a type of Java servlet that is designed to


fulfill the role of a user interface for a Java web application. Web developers
write JSPs as text files that combine HTML or XHTML code, XML elements,
and embedded JSP actions and commands.

Using JSP, you can collect input from users through Webpage forms,
present records from a database or another source, and create Webpages
dynamically.

JSP tags can be used for a variety of purposes, such as retrieving


information from a database or registering user preferences, accessing
JavaBeans components, passing control between pages, and sharing
information between requests, pages etc.

Advantages of JSP
Following table lists out the other advantages of using JSP over other
technologies −

vs. Active Server Pages (ASP)


The advantages of JSP are twofold. First, the dynamic part is written in
Java, not Visual Basic or other MS specific language, so it is more powerful
and easier to use. Second, it is portable to other operating systems and
non-Microsoft Web servers.

vs. Pure Servlets


It is more convenient to write (and to modify!) regular HTML than to have
plenty of println statements that generate the HTML.

vs. Server-Side Includes (SSI)


SSI is really only intended for simple inclusions, not for "real" programs
that use form data, make database connections, and the like.

vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access
and image processing etc.

vs. Static HTML


Regular HTML, of course, cannot contain dynamic information.

JSP 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.
This tutorial makes use of Apache which has built-in JSP container to
support JSP pages development.

A JSP container works with the Web server to provide the runtime
environment and other services a JSP needs. It knows how to understand
the special elements that are part of JSPs.

Following diagram shows the position of JSP container and JSP files in a
Web application.

JSP Processing
The following steps explain how the web server creates the Webpage using
JSP −

 As with a normal page, your 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.

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

All the above mentioned steps can be seen in the following diagram −

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

JSP Standard action:


These actions use constructs in XML syntax to control the behavior of the
servlet engine. You can dynamically insert a file, reuse JavaBeans
components, forward the user to another page, or generate HTML for the
Java plugin.

There is only one syntax for the Action element, as it conforms to the XML
standard −

<jsp:action_name attribute = "value" />

Action elements are basically predefined functions. The following table lists
out the available JSP actions −

S.No. Syntax & Purpose

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

jsp:useBean
2
Finds or instantiates a JavaBean.

jsp:setProperty
3
Sets the property of a JavaBean.

jsp:getProperty
4
Inserts the property of a JavaBean into the output.

5 jsp:forward
Forwards the requester to a new page.

jsp:plugin

6 Generates browser-specific code that makes an OBJECT or EMBED tag


for the Java plugin.

jsp:element
7
Defines XML elements dynamically.

jsp:attribute
8
Defines dynamically-defined XML element's attribute.

jsp:body
9
Defines dynamically-defined XML element's body.

jsp:text
10
Used to write template text in JSP pages and documents.

Common Attributes
There are two attributes that are common to all Action elements:
the idattribute and the scope attribute.

Id attribute
The id attribute uniquely identifies the Action element, and allows the action
to be referenced inside the JSP page. If the Action creates an instance of an
object, the id value can be used to reference it through the implicit object
PageContext.

Scope attribute
This attribute identifies the lifecycle of the Action element. The id attribute
and the scope attribute are directly related, as the scope attribute
determines the lifespan of the object associated with the id. The scope
attribute has four possible values: (a) page, (b)request, (c)session,
and (d) application.

The <jsp:include> Action


This action lets you insert files into the page being generated. The syntax
looks like this −

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

Unlike the include directive, which inserts the file at the time the JSP page
is translated into a servlet, this action inserts the file at the time the page is
requested.

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

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

Example
Let us define the following two files (a)date.jsp and (b) main.jsp as
follows −

Following is the content of the date.jsp file −

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

Following is the content of the main.jsp file −

<html>

<head>

<title>The include Action Example</title>

</head>

<body>

<center>

<h2>The include action Example</h2>

<jsp:include page = "date.jsp" flush = "true" />


</center>

</body>

</html>

Let us now keep all these files in the root directory and try to
access main.jsp. You will receive the following output −

The include action Example

Today's date: 12-Sep-2010 14:54:22

The <jsp:useBean> Action


The useBean action is quite versatile. It first searches for an existing
object utilizing the id and scope variables. If an object is not found, it then
tries to create the specified object.

The simplest way to load a bean is as follows −

<jsp:useBean id = "name" class = "package.class" />

Once a bean class is loaded, you can


use jsp:setProperty andjsp:getProperty actions to modify and retrieve
the bean properties.

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

S.No. Attribute & Description

class
1
Designates the full package name of the bean.

type
2
Specifies the type of the variable that will refer to the object.

beanName
3
Gives the name of the bean as specified by the instantiate () method of
the java.beans.Beans class.

Let us now discuss the jsp:setProperty and the jsp:getProperty actions


before giving a valid example related to these actions.

The <jsp:setProperty> Action


The setProperty action sets the properties of a Bean. The Bean must have
been previously defined before this action. There are two basic ways to use
the setProperty action −

You can use jsp:setProperty after, but outside of a jsp:useBean element,


as given below −

<jsp:useBean id = "myName" ... />


...
<jsp:setProperty name = "myName" property = "someProperty" .../>

In this case, the jsp:setProperty is executed regardless of whether a new


bean was instantiated or an existing bean was found.

A second context in which jsp:setProperty can appear is inside the body of


ajsp:useBean element, as given below −

<jsp:useBean id = "myName" ... >

...

<jsp:setProperty name = "myName" property = "someProperty" .../>

</jsp:useBean>

Here, the jsp:setProperty is executed only if a new object was instantiated,


not if an existing one was found.

Following table lists out the attributes associated with


the setProperty action −

S.No. Attribute & Description

name
1
Designates the bean the property of which will be set. The Bean must
have been previously defined.
property

Indicates the property you want to set. A value of "*" means that all
2
request parameters whose names match bean property names will be
passed to the appropriate setter methods.

value

The value that is to be assigned to the given property. The the


3
parameter's value is null, or the parameter does not exist, the
setProperty action is ignored.

param

The param attribute is the name of the request parameter whose value
4
the property is to receive. You can't use both value and param, but it is
permissible to use neither.

The <jsp:getProperty> Action


The getProperty action is used to retrieve the value of a given property
and converts it to a string, and finally inserts it into the output.

The getProperty action has only two attributes, both of which are required.
The syntax of the getProperty action is as follows −

<jsp:useBean id = "myName" ... />

...

<jsp:getProperty name = "myName" property = "someProperty" .../>

Following table lists out the required attributes associated with


the getPropertyaction −

S.No. Attribute & Description

name
1
The name of the Bean that has a property to be retrieved. The Bean
must have been previously defined.

2 property
The property attribute is the name of the Bean property to be retrieved.

Example
Let us define a test bean that will further be used in our example −

/* File: TestBean.java */

package action;

public class TestBean {

private String message = "No message specified";

public String getMessage() {

return(message);

public void setMessage(String message) {

this.message = message;

Compile the above code to the generated TestBean.class file and make
sure that you copied the TestBean.class in C:\apache-tomcat-
7.0.2\webapps\WEB-INF\classes\action folder and
the CLASSPATHvariable should also be set to this folder −

Now use the following code in main.jsp file. This loads the bean and
sets/gets a simple String parameter −

<html>

<head>

<title>Using JavaBeans in JSP</title>

</head>

<body>
<center>

<h2>Using JavaBeans in JSP</h2>

<jsp:useBean id = "test" class = "action.TestBean" />

<jsp:setProperty name = "test" property = "message"

value = "Hello JSP..." />

<p>Got message....</p>

<jsp:getProperty name = "test" property = "message" />

</center>

</body>

</html>

Let us now try to access main.jsp, it would display the following result −

Using JavaBeans in JSP

Got message....
Hello JSP...

The <jsp:forward> Action


The forward action terminates the action of the current page and forwards
the request to another resource such as a static page, another JSP page, or
a Java Servlet.

Following is the syntax of the forward action −

<jsp:forward page = "Relative URL" />

Following table lists out the required attributes associated with the forward
action −

S.No. Attribute & Description

1 page
Should consist of a relative URL of another resource such as a static
page, another JSP page, or a Java Servlet.

Example
Let us reuse the following two files (a) date.jsp and (b) main.jsp as
follows −

Following is the content of the date.jsp file −

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

Following is the content of the main.jsp file −

<html>

<head>

<title>The include Action Example</title>

</head>

<body>

<center>

<h2>The include action Example</h2>

<jsp:forward page = "date.jsp" />

</center>

</body>

</html>

Let us now keep all these files in the root directory and try to
access main.jsp. This would display result something like as below.

Here it discarded the content from the main page and displayed the content
from forwarded page only.

Today's date: 12-Sep-2010 14:54:22

The <jsp:plugin> Action


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.

Following is the typical syntax of using the plugin action −

<jsp:plugin type = "applet" codebase = "dirname" code = "MyApplet.class"

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>

You can try this action using some applet if you are interested. A new
element, the <fallback> element, can be used to specify an error string to
be sent to the user in case the component fails.

The <jsp:element> Action

The <jsp:attribute> Action

The <jsp:body> Action


The <jsp:element>, <jsp:attribute> and <jsp:body> 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.

Following is a simple example to define XML elements dynamically −

<%@page language = "java" contentType = "text/html"%>

<html xmlns = "http://www.w3c.org/1999/xhtml"

xmlns:jsp = "http://java.sun.com/JSP/Page">

<head><title>Generate XML Element</title></head>

<body>

<jsp:element name = "xmlElement">

<jsp:attribute name = "xmlElementAttr">

Value for the attribute

</jsp:attribute>

<jsp:body>

Body for XML element

</jsp:body>

</jsp:element>

</body>

</html>

This would produce the following HTML code at run time −

<html xmlns = "http://www.w3c.org/1999/xhtml" xmlns:jsp =


"http://java.sun.com/JSP/Page">

<head><title>Generate XML Element</title></head>

<body>
<xmlElement xmlElementAttr = "Value for the attribute">

Body for XML element

</xmlElement>

</body>

</html>

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 thegt form, such as ${whatever gt 0} or an alternative is to
embed the value in a CDATA section.

<jsp:text><![CDATA[<br>]]></jsp:text>

If you need to include a DOCTYPE declaration, for instance for XHTML, you
must also use the <jsp:text> element as follows −

<jsp:text><![CDATA[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"DTD/xhtml1-strict.dtd">]]></jsp:text>

<head><title>jsp:text action</title></head>

<body>

<books><book><jsp:text>

Welcome to JSP Programming

</jsp:text></book></books>

</body>

</html>

Try the above example with and without <jsp:text> action.


JSP Directives:
In this chapter, we will discuss Directives in JSP. These directives provide
directions and instructions to the container, telling it how to handle certain
aspects of the JSP processing.

A JSP directive affects the overall structure of the servlet class. It usually
has the following form −

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

There are three types of directive tag −

S.No. Directive & Description

<%@ page ... %>


1
Defines page-dependent attributes, such as scripting language, error
page, and buffering requirements.

<%@ include ... %>


2
Includes a file during the translation phase.

<%@ taglib ... %>


3
Declares a tag library, containing custom actions, used in the page

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

Following is the basic syntax of the page directive −

<%@ page attribute = "value" %>


You can write the XML equivalent of the above syntax as follows −

<jsp:directive.page attribute = "value" />

Attributes
Following table lists out the attributes associated with the page directive −

S.No. Attribute & Purpose

buffer
1
Specifies a buffering model for the output stream.

autoFlush
2
Controls the behavior of the servlet output buffer.

contentType
3
Defines the character encoding scheme.

errorPage

4 Defines the URL of another JSP that reports on Java unchecked runtime
exceptions.

isErrorPage

5 Indicates if this JSP page is a URL specified by another JSP page's


errorPage attribute.

extends
6
Specifies a superclass that the generated servlet must extend.

import

7 Specifies a list of packages or classes for use in the JSP as the Java
import statement does for Java classes.

info
8
Defines a string that can be accessed with the
servlet'sgetServletInfo() method.

isThreadSafe
9
Defines the threading model for the generated servlet.

language
10
Defines the programming language used in the JSP page.

session
11
Specifies whether or not the JSP page participates in HTTP sessions

isELIgnored

12 Specifies whether or not the EL expression within the JSP page will be
ignored.

isScriptingEnabled
13
Determines if the scripting elements are allowed for use.

Check for more details related to all the above attributes at Page Directive.

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

The general usage form of this directive is as follows −

<%@ include file = "relative url" >

The filename in the include directive is actually a relative URL. If you just
specify a filename with no associated path, the JSP compiler assumes that
the file is in the same directory as your JSP.

You can write the XML equivalent of the above syntax as follows −

<jsp:directive.include file = "relative url" />

For more details related to include directive, check the Include Directive.
The 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.

The taglib directive declares that your JSP page uses a set of custom tags,
identifies the location of the library, and provides means for identifying the
custom tags in your JSP page.

The taglib directive follows the syntax given below −

<%@ taglib uri="uri" prefix = "prefixOfTag" >

Here, the uri attribute value resolves to a location the container


understands and the prefix attribute informs a container what bits of
markup are custom actions.

You can write the XML equivalent of the above syntax as follows −

<jsp:directive.taglib uri = "uri" prefix = "prefixOfTag" />

For more details related to the taglib directive, check the Taglib Directive

Custom tag :
In this chapter, we will discuss the Custom Tags in JSP. A custom tag is a
user-defined JSP language element. When a JSP page containing a custom
tag is translated into a servlet, the tag is converted to operations on an
object called a tag handler. The Web container then invokes those
operations when the JSP page's servlet is executed.

JSP tag extensions lets you create new tags that you can insert directly into
a JavaServer Page. The JSP 2.0 specification introduced the Simple Tag
Handlers for writing these custom tags.

To write a custom tag, you can simply extend SimpleTagSupport class


and override the doTag() method, where you can place your code to
generate content for the tag.

Custom Tag Libraries:


The JavaServer Pages Standard Tag Library (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.

Install JSTL Library


To begin working with JSP tages you need to first install the JSTL library. If
you are using the Apache Tomcat container, then follow these two steps −

Step 1 − Download the binary distribution from Apache Standard


Taglib and unpack the compressed file.

Step 2 − To use the Standard Taglib from its Jakarta Taglibs


distribution, simply copy the JAR files in the distribution's 'lib' directory to
your application'swebapps\ROOT\WEB-INF\lib directory.

To use any of the libraries, you must include a <taglib> directive at the top
of each JSP that uses the library.

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

Following table lists out the core JSTL Tags −

S.No. Tag & Description


<c:out>
1
Like <%= ... >, but for expressions.

<c:set >
2 Sets the result of an expression evaluation in a 'scope'

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

<c:catch>

4 Catches any Throwable that occurs in its body and optionally exposes
it.

<c:if>

5 Simple conditional tag which evalutes its body if the supplied condition
is true.

<c:choose>

6 Simple conditional tag that establishes a context for mutually exclusive


conditional operations, marked by <when> and<otherwise>.

<c:when>

7 Subtag of <choose> that includes its body if its condition evalutes


to 'true'.

<c:otherwise >

8 Subtag of <choose> that follows the <when> tags and runs only if all
of the prior conditions evaluated to 'false'.

<c:import>

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

10 The basic iteration tag, accepting many different collection types and
supporting subsetting and other functionality .

<c:forTokens>
11
Iterates over tokens, separated by the supplied delimeters.
<c:param>
12
Adds a parameter to a containing 'import' tag's URL.

<c:redirect >
13 Redirects to a new URL.

<c:url>
14
Creates a URL with optional query parameters

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

Following table lists out the Formatting JSTL Tags −

S.No. Tag & Description

<fmt:formatNumber>
1
To render numerical value with specific precision or format.

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

<fmt:formatDate>
3
Formats a date and/or time using the supplied styles and pattern.

<fmt:parseDate>
4 Parses the string representation of a date and/or time

<fmt:bundle>
5
Loads a resource bundle to be used by its tag body.

<fmt:setLocale>
6
Stores the given locale in the locale configuration variable.

<fmt:setBundle>
7
Loads a resource bundle and stores it in the named scoped variable or
the bundle configuration variable.

<fmt:timeZone>

8 Specifies the time zone for any time formatting or parsing actions
nested in its body.

<fmt:setTimeZone>
9 Stores the given time zone in the time zone configuration variable

<fmt:message>
10 Displays an internationalized message.

<fmt:requestEncoding>
11
Sets the request character encoding

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

Following table lists out the SQL JSTL Tags −

S.No. Tag & Description

<sql:setDataSource>
1
Creates a simple DataSource suitable only for prototyping

<sql:query>
2 Executes the SQL query defined in its body or through the sql attribute.

<sql:update>
3
Executes the SQL update defined in its body or through the sql attribute.

<sql:param>
4
Sets a parameter in an SQL statement to the specified value.

5 <sql:dateParam>
Sets a parameter in an SQL statement to the specified java.util.Date
value.

<sql:transaction >

6 Provides nested database action elements with a shared Connection, set


up to execute all statements as one transaction.

XML tags
The JSTL XML tags provide a JSP-centric way of creating and manipulating
the XML documents. Following is the syntax to include the JSTL XML library
in your JSP.

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

Before you proceed with the examples, you will need to copy the following
two XML and XPath related libraries into your <Tomcat Installation
Directory>\lib−

 XercesImpl.jar − Download it fromhttps://www.apache.org/dist/xerces/j/

 xalan.jar − Download it from https://xml.apache.org/xalan-j/index.html

Following is the list of XML JSTL Tags −

S.No. Tag & Description

<x:out>
1
Like <%= ... >, but for XPath expressions.

<x:parse>

2 Used to parse the XML data specified either via an attribute or in the tag
body.

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

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

<x:choose>

6 Simple conditional tag that establishes a context for mutually exclusive


conditional operations, marked by <when> and<otherwise> tags.

<x:when >

7 Subtag of <choose> that includes its body if its expression evalutes to


'true'.

<x:otherwise >

8 Subtag of <choose> that follows the <when> tags and runs only if all
of the prior conditions evaluates to 'false'.

<x:transform >
9
Applies an XSL transformation on a XML document

<x:param >

10 Used along with the transform tag to set a parameter in the XSLT
stylesheet

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

Following table lists out the various JSTL Functions −

S.No. Function & Description

1 fn:contains()
Tests if an input string contains the specified substring.

fn:containsIgnoreCase()

2 Tests if an input string contains the specified substring in a case


insensitive way.

fn:endsWith()
3 Tests if an input string ends with the specified suffix.

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

fn:indexOf()

5 Returns the index withing a string of the first occurrence of a specified


substring.

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

fn:length()

7 Returns the number of items in a collection, or the number of characters


in a string.

fn:replace()

8 Returns a string resulting from replacing in an input string all


occurrences with a given string.

fn:split()
9 Splits a string into an array of substrings.

fn:startsWith()
10
Tests if an input string starts with the specified prefix.

fn:substring()
11 Returns a subset of a string.

fn:substringAfter()
12
Returns a subset of a string following a specific substring.

13 fn:substringBefore()
Returns a subset of a string before a specific substring.

fn:toLowerCase()
14
Converts all of the characters of a string to lower case.

fn:toUpperCase()
15 Converts all of the characters of a string to upper case.

fn:trim()
16 Removes white spaces from both ends of a string.

JSP Custom Tag API:


The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom tag API.
The JspTag is the root interface in the Custom Tag hierarchy.

JspTag interface

The JspTag is the root interface for all the interfaces and classes used in custom tag. It is a
marker interface.

Tag interface

The Tag interface is the sub interface of JspTag interface. It provides methods to perform
action at the start and end of the tag.
Fields of Tag interface

There are four fields defined in the Tag interface. They are:

Field Name Description

public static int EVAL_BODY_INCLUDE it evaluates the body content.

public static int EVAL_PAGE it evaluates the JSP page content after the custom

public static int SKIP_BODY it skips the body content of the tag.

public static int SKIP_PAGE it skips the JSP page content after the custom tag.

Methods of Tag interface

The methods of the Tag interface are as follows:

Method Name Description

public void it sets the given PageContext object.


setPageContext(PageContext pc)

public void setParent(Tag t) it sets the parent of the tag handler.

public Tag getParent() it returns the parent tag handler object.

public int doStartTag()throws it is invoked by the JSP page implementation object. The JSP
JspException programmer should override this method and define the busi
to be performed at the start of the tag.

public int doEndTag()throws it is invoked by the JSP page implementation object. The JSP
JspException programmer should override this method and define the busi
to be performed at the end of the tag.

public void release() it is invoked by the JSP page implementation object to releas
state.

IterationTag interface
The IterationTag interface is the sub interface of the Tag interface. It provides an additional
method to reevaluate the body.

Field of IterationTag interface

There is only one field defined in the IterationTag interface.

o public static int EVAL_BODY_AGAIN it reevaluates the body content.

Method of Tag interface

There is only one method defined in the IterationTag interface.

o public int doAfterBody()throws JspException it is invoked by the JSP page


implementation object after the evaluation of the body. If this method returns
EVAL_BODY_INCLUDE, body content will be reevaluated, if it returns SKIP_BODY, no
more body cotent will be evaluated.

How to create custom tag:


To create a custom tag we need three things:
1) Tag handler class: In this class we specify what our custom tag will do when
it is used in a JSP page.
2) TLD file: Tag descriptor file where we will specify our tag name, tag handler
class and tag attributes.
3) JSP page: A JSP page where we will be using our custom tag.

Example:
In the below example we are creating a custom tag MyMsg which will display the
message “This is my own custom tag” when used in a JSP page.

Tag handler class:


A tag handler class should implement Tag/IterationTag/ BodyTag interface or it can
also extendTagSupport/BodyTagSupport/SimpleTagSupport class. All the classes that
support custom tags are present inside javax.servlet.jsp.tagext. In the below we are
extending the class SimpleTagSupport.
Details.java

package beginnersbook.com;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class Details extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
/*This is just to display a message, when
* we will use our custom tag. This message
* would be displayed
*/
JspWriter out = getJspContext().getOut();
out.println("This is my own custom tag");
}
}

TLD File
This file should present at the location: Project Name/WebContent/WEB-INF/ and it
should have a.tld extension.

Note:
<name> tag: custom tag name. In this example we have given it as MyMsg
<tag-class> tag: Fully qualified class name. Our tag handler class Details.java is in
packagebeginnersbook.com so we have given the value as beginnersbook.com.Details.

message.tld

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>My Custom Tag</short-name>
<tag>
<name>MyMsg</name>
<tag-class>beginnersbook.com.Details</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

Using custom tag in JSP:


Above we have created a custom tag named MyMsg. Here we will be using it.
Note: taglib directive should have the TLD file path in uri field. Above we have
created themessage.tld file so we have given the path of that file.
Choose any prefix and specify it in taglib directive’s prefix field. Here we have
specified it as myprefix.
Custom tag is called like this: <prefix:tagName/>. Our prefix is myprefix and tag name
is MyMsg so we have called it as <myprefix:MyMsg/> in the below JSP page.

<%@ taglib prefix="myprefix" uri="WEB-INF/message.tld"%>


<html>
<head>
<title>Custom Tags in JSP Example</title>
</head>
<body>
<myprefix:MyMsg/>
</body>
</html>

Output:

This is my own custom tag

You might also like