0% found this document useful (0 votes)
17 views67 pages

JavaServerPages Material

Uploaded by

Deep mathukiya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
17 views67 pages

JavaServerPages Material

Uploaded by

Deep mathukiya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 67

Java Server Pages

JSP technology is used to create web application just like Servlet technology. It can
be thought of as an extension to Servlet because it provides more functionality than
servlet such as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and development. It
provides some additional features such as Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet


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

1) Extension to Servlet

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

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the
presentation logic.

3) Fast Development: No need to recompile and redeploy

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

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.

Difference between Servlet and JSP


Servlet JSP

Servlet is a java code. JSP is a html-based code.

Writing code for servlet is harder JSP is easy to code as it is java in


than JSP as it is html in java. html.
Servlet plays a controller role in JSP is the view in MVC approach for
MVC approach. showing output.

JSP is slower than Servlet because


the first step in JSP lifecycle is the
translation of JSP to java code and
Servlet is faster than JSP. then compile.

Servlet can accept all protocol


requests. JSP only accept http requests.

In Servlet, we can override the In JSP, we cannot override its


service() method. service() method.

In Servlet by default session


management is not enabled, user In JSP session management is
have to enable it explicitly. automatically enabled.

In Servlet we have to implement


everything like business logic and In JSP business logic is separated
presentation logic in just one servlet from presentation logic by using
file. javaBeans.

Modification in Servlet is a time


consuming task because it includes
reloading, recompiling and restarting JSP modification is fast, just need to
the server. click the refresh button.

Life cycle of JSP


A Java Server Page life cycle is defined as the process started with its
creation which later translated to a servlet and afterward servlet lifecycle
comes into play. This is how the process goes on until its destruction.
Following steps are involved in JSP life cycle:
• Translation of JSP page to Servlet
• Compilation of JSP page(Compilation of JSP into test.java)
• Classloading (test.java to test.class)
• Instantiation(Object of the generated Servlet is created)
• Initialization(jspInit() method is invoked by the container)
• Request processing(_jspService()is invoked by the container)
• JSP Cleanup /Destroy (jspDestroy() method is invoked by the
container)
Translation of JSP page to Servlet :

This is the first step of JSP life cycle. This translation phase deals with
Syntactic correctness of JSP. Here test.jsp file is transllated to test.java.

Compilation of JSP page :

Here the generated java servlet file (test.java) is compiled to a class file
(test.class).

Classloading :

Servlet class which has been loaded from JSP source is now loaded into
container.

Instantiation :
Here instance of the class is generated. The container manages one or more
instance by providing response to requests.

Initialization :

jspInit() method is called only once during the life cycle immediately after the
generation of Servlet instance from JSP.

Request processing :

_jspService() method is used to serve the raised requests by JSP.It takes


request and response object as parameters.This method cannot be
overridden.

JSP Cleanup/Destroy :

In order to remove the JSP from use by the container or to destroy method
for servlets jspDestroy()method is used. This method is called once, if you
need to perform any cleanup task like closing open files, releasing database
connections jspDestroy() can be overridden.

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.

MVC in JSP
MVC stands for Model View and Controller. It is a design pattern that separates
the business logic, presentation logic and data.

Controller acts as an interface between View and Model. Controller intercepts all
the incoming requests.

Model represents the state of the application i.e. data. It can also have business
logic.

View represents the presentaion i.e. UI(User Interface).

Advantage of MVC (Model 2) Architecture


1. Navigation Control is centralized

2. Easy to maintain the large application


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.

3 <%@ taglib ... %>


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

1 buffer
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's getServletInfo() 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" />

JSP - Implicit Objects


hese Objects are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being
explicitly declared. JSP Implicit Objects are also called pre-defined variables.
Following table lists out the nine Implicit Objects that JSP supports −

S.No. Object & Description

1 request
This is the HttpServletRequest object associated with the request.

response
2
This is the HttpServletResponse object associated with the response to the
client.

out
3
This is the PrintWriter object used to send output to the client.

session
4
This is the HttpSession object associated with the request.
application
5
This is the ServletContext object associated with the application context.

config
6
This is the ServletConfig object associated with the page.

pageContext
7
This encapsulates use of server-specific features like higher
performance JspWriters.

page
8
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.

Exception
9
The Exception object allows the exception data to be accessed by designated
JSP.

The request Object


The request object is an instance of
a javax.servlet.http.HttpServletRequest object. Each time a client requests a page
the JSP engine creates a new object to represent that request.
The request object provides methods to get the HTTP header information including
form data, cookies, HTTP methods etc.
We can cover a complete set of methods associated with the request object in a
subsequent chapter − JSP - Client Request.

The response Object


The response object is an instance of
a javax.servlet.http.HttpServletResponse object. Just as the server creates the
request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP
headers. Through this object the JSP programmer can add new cookies or date
stamps, HTTP status codes, etc.
We will cover a complete set of methods associated with the response object in a
subsequent chapter − JSP - Server Response.
The out Object
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is
used to send content in a response.
The initial JspWriter object is instantiated differently depending on whether the page
is buffered or not. Buffering can be easily turned off by using the buffered =
'false' attribute of the page directive.
The JspWriter object contains most of the same methods as
the java.io.PrintWriter class. However, JspWriter has some additional methods
designed to deal with buffering. Unlike the PrintWriter object, JspWriter
throws IOExceptions.
Following table lists out the important methods that we will use to write boolean char,
int, double, object, String, etc.

S.No. Method & Description

1 out.print(dataType dt)
Print a data type value

out.println(dataType dt)
2
Print a data type value then terminate the line with new line character.

out.flush()
3
Flush the stream.

The session Object


The session object is an instance of javax.servlet.http.HttpSession and behaves
exactly the same way that session objects behave under Java Servlets.
The session object is used to track client session between client requests. We will
cover the complete usage of session object in a subsequent chapter − JSP - Session
Tracking.

The application Object


The application object is direct wrapper around the ServletContext object for the
generated Servlet and in reality an instance of
a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object
is created when the JSP page is initialized and will be removed when the JSP page
is removed by the jspDestroy() method.
By adding an attribute to application, you can ensure that all JSP files that make up
your web application have access to it.
We will check the use of Application Object in JSP - Hits Counter chapter.

The config Object


The config object is an instantiation of javax.servlet.ServletConfig and is a direct
wrapper around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine
initialization parameters such as the paths or file locations etc.
The following config method is the only one you might ever use, and its usage is
trivial −
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-
name> element defined in the WEB-INF\web.xml file.

The pageContext Object


The pageContext object is an instance of a javax.servlet.jsp.PageContext object.
The pageContext object is used to represent the entire JSP page.
This object is intended as a means to access information about the page while
avoiding most of the implementation details.
This object stores references to the request and response objects for each request.
The application, config, session, and out objects are derived by accessing
attributes of this object.
The pageContext object also contains information about the directives issued to the
JSP page, including the buffering information, the errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE,
REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which
identify the four scopes. It also supports more than 40 methods, about half of which
are inherited from the javax.servlet.jsp.JspContext class.
One of the important methods is removeAttribute. This method accepts either one
or two arguments. For example, pageContext.removeAttribute
("attrName") removes the attribute from all scopes, while the following code only
removes it from the page scope −
pageContext.removeAttribute("attrName", PAGE_SCOPE);
The use of pageContext can be checked in JSP - File Uploading chapter.

The page Object


This object is an actual reference to the instance of the page. It can be thought of as
an object that represents the entire JSP page.
The page object is really a direct synonym for the this object.
The exception Object
The exception object is a wrapper containing the exception thrown from the previous
page. It is typically used to generate an appropriate response to the error condition.

JSP – Actions
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

1 jsp:include
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.

jsp:forward
5
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 id attribute 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


1 page
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 and jsp:getProperty actions to modify and retrieve the bean
properties.
Following table lists out the attributes associated with the useBean action −

S.No. Attribute & Description

1 class
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
a jsp: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
2 Indicates the property you want to set. A value of "*" means that all request
parameters whose names match bean property names will be passed to the
appropriate setter methods.

value
3
The value that is to be assigned to the given property. The the parameter's value
is null, or the parameter does not exist, the setProperty action is ignored.

param
4 The param attribute is the name of the request parameter whose value 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 getProperty action −

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.
property
2
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 CLASSPATH variable 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

page
1
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 the gt form, such as ${whatever gt 0} or
an alternative is to embed the value in a CDATA section.
<jsp:text><![CDATA[<br>]]></jsp:text>
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 - Form Processing


You must have come across many situations when you need to pass some
information from your browser to the web server and ultimately to your backend
program. The browser uses two methods to pass this information to the web server.
These methods are the GET Method and the POST Method.

The Methods in Form Processing


Let us now discuss the methods in Form Processing.

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. 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.
This information is passed using QUERY_STRING header and will be accessible
through QUERY_STRING environment variable which can be handled
using getQueryString() and getParameter() methods of request object.

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. This message comes to the backend program in the form of the standard
input which you can parse and use for your processing.
JSP handles this type of requests using getParameter() method to read simple
parameters and getInputStream() method to read binary data stream coming from
the client.
Reading Form Data using JSP
JSP handles form data parsing automatically using the following methods depending
on the situation −
• 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


The following URL will pass two values to HelloForm program using the GET method.
http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI
Below is the main.jsp JSP program to handle input given by web browser. We are
going to use the getParameter() method which makes it very easy to access the
passed information −
<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_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>

</body>
</html>

Now type http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI in


your browser's Location:box. This will generate the following result −
Using GET Method to Read Form Data
• First Name: ZARA
• Last Name: ALI

GET Method Example Using Form


Following is an example that passes two values using the HTML FORM and the
submit button. We are going to use the same JSP main.jsp to handle this input.
<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>

Keep this HTML in a file Hello.htm and put it in <Tomcat-installation-


directory>/webapps/ROOT directory. When you would
access http://localhost:8080/Hello.htm, you will receive the following output.

First Name:
Last Name:
< p>Try to enter the First Name and the Last Name and then click the submit button to see
the result on your local machine where tomcat is running. Based on the input provided, it will
generate similar result as mentioned in the above example.

POST Method Example Using Form


Let us do a little modification in the above JSP to handle both the GET and the POST
method. Below is the main.jsp JSP program to handle the input given by web
browser using the GET or the POST methods.
Infact there is no change in the above JSP because the only way of passing
parameters is changed and no binary data is being passed to the JSP program. File
handling related concepts will be explained in separate chapter where we need to
read the binary data stream.
<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_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>

</body>
</html>

Following is the content of the Hello.htm file −


<html>
<body>

<form action = "main.jsp" method = "POST">


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>

Let us now keep main.jsp and hello.htm in <Tomcat-


installationdirectory>/webapps/ROOT directory. When you
access http://localhost:8080/Hello.htm, you will receive the following output.

First Name:
Last Name:

Try to enter the First and the Last Name and then click the submit button to see the
result on your local machine where tomcat is running.
Based on the input provided, you will receive similar results as in the above examples.

Passing Checkbox Data to JSP Program


Checkboxes are used when more than one option is required to be selected.
Following is an example HTML code, CheckBox.htm, for a form with two
checkboxes.
<html>
<body>

<form action = "main.jsp" method = "POST" target =


"_blank">
<input type = "checkbox" name = "maths" checked =
"checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked =
"checked" /> Chemistry
<input type = "submit" value = "Select Subject" />
</form>

</body>
</html>

The above code will generate the following result −

Maths Physics Chemistry

Following is main.jsp JSP program to handle the input given by the web browser for
the checkbox button.
<html>
<head>
<title>Reading Checkbox Data</title>
</head>

<body>
<h1>Reading Checkbox Data</h1>

<ul>
<li><p><b>Maths Flag:</b>
<%= request.getParameter("maths")%>
</p></li>
<li><p><b>Physics Flag:</b>
<%= request.getParameter("physics")%>
</p></li>
<li><p><b>Chemistry Flag:</b>
<%= request.getParameter("chemistry")%>
</p></li>
</ul>

</body>
</html>

The above program will generate the following result −

Reading Checkbox Data

• Maths Flag :: on

• Physics Flag:: null

• Chemistry Flag:: on
Reading All Form Parameters
Following is a generic example which uses getParameterNames() method of
HttpServletRequest to read all the available form parameters. This method returns an
Enumeration that contains the parameter names in an unspecified order.
Once we have an Enumeration, we can loop down the Enumeration in the standard
manner, using the hasMoreElements() method to determine when to stop and using
the nextElement() method to get each parameter name.
<%@ page import = "java.io.*,java.util.*" %>

<html>
<head>
<title>HTTP Header Request Example</title>
</head>

<body>
<center>
<h2>HTTP Header Request Example</h2>
<table width = "100%" border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Param Name</th>
<th>Param Value(s)</th>
</tr>
<%
Enumeration paramNames =
request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName =
(String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue =
request.getHeader(paramName);
out.println("<td> " + paramValue +
"</td></tr>\n");
}
%>
</table>
</center>

</body>
</html>

Following is the content of the Hello.htm −


<html>
<body>

<form action = "main.jsp" method = "POST" target =


"_blank">
<input type = "checkbox" name = "maths" checked =
"checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked =
"checked" /> Chem
<input type = "submit" value = "Select Subject" />
</form>

</body>
</html>

Now try calling JSP using the above Hello.htm; this would generate a result
something like as below based on the provided input −

Reading All Form Parameters

Param Name Param Value(s)

maths on

chemistry on

You can try the above JSP to read any other form's data which is having other objects
like text box, radio button or dropdown, etc.

JSP - Cookies Handling


Setting Cookies with JSP
Setting cookies with JSP involves three steps −

Step 1: Creating a Cookie object

You call the Cookie constructor with a cookie name and a cookie value, both of which
are strings.
Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of
the following characters −
[ ] ( ) = , " / ? @ : ;

Step 2: Setting the maximum age

You use setMaxAge to specify how long (in seconds) the cookie should be valid. The
following code will set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
Step 3: Sending the Cookie into the HTTP response headers

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


follows
response.addCookie(cookie);

Example

Let us modify our Form Example to set the cookies for the first and the last name.
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));

// Set expiry date after 24 Hrs for both the cookies.


firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

// Add both the cookies in the response header.


response.addCookie( firstName );
response.addCookie( lastName );
%>

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

Let us put the above code in main.jsp file and use it in the following HTML page −
<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>

Keep the above HTML content in a file hello.jsp and


put hello.jsp and main.jsp in <Tomcat-installation-
directory>/webapps/ROOT directory. When you will
access http://localhost:8080/hello.jsp, here is the actual output of the above form.

First Name:
Last Name:

Try to enter the First Name and the Last Name and then click the submit button. This
will display the first name and the last name on your screen and will also set two
cookies firstName and lastName. These cookies will be passed back to the server
when the next time you click the Submit button.
In the next section, we will explain how you can access these cookies back in your
web application.

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

Let us now read cookies that were set in the previous example −
<html>
<head>
<title>Reading Cookies</title>
</head>

<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;

// Get an array of Cookies associated with the this


domain
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];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+"
<br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>

</html>

Let us now put the above code in main.jsp file and try to access it. If you set
the first_name cookie as "John" and the last_name cookie as "Player" then
running http://localhost:8080/main.jsp will display the following result −

Found Cookies Name and Value

Name : first_name, Value: John

Name : last_name, Value: Player

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.

Example

Following example will show you how to delete an existing cookie


named "first_name" and when you run main.jsp JSP next time, it will return null
value for first_name.
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;

// Get an array of Cookies associated with the this


domain
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];

if((cookie.getName( )).compareTo("first_name") ==
0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " +
cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+"
<br/>");
}
} else {
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>

</html>

Let us now put the above code in the main.jsp file and try to access it. It will display
the following result −

Cookies Name and Value

Deleted cookie : first_name

Name : first_name, Value: John

Name : last_name, Value: Player


Now run http://localhost:8080/main.jsp once again and it should display only one
cookie as follows −

Found Cookies Name and Value


Name : last_name, Value: Player
You can delete your cookies in the Internet Explorer manually. Start at the Tools
menu and select the Internet Options. To delete all cookies, click the Delete Cookies
button.

JSP - Session Tracking


The session Object
Apart from the above mentioned options, JSP makes use of the servlet provided
HttpSession Interface. This interface provides a way to identify a user across.

• a one page request or


• visit to a website or
• store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is
instantiated for each new client automatically. Disabling session tracking requires
explicitly turning it off by setting the page directive session attribute to false as follows

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

Session Tracking Example

This example describes how to use the HttpSession object to find out the creation
time and the last-accessed time for a session. We would associate a new session
with the request if one does not already exist.
<%@ page import = "java.io.*,java.util.*" %>
<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());

// Get last access time of this Webpage.


Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your Webpage.


if (session.isNew() ){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>

<html>
<head>
<title>Session Tracking</title>
</head>

<body>
<center>
<h1>Session Tracking</h1>
</center>

<table border = "1" align = "center">


<tr bgcolor = "#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>

</body>
</html>
Now put the above code in main.jsp and try to
access http://localhost:8080/main.jsp. Once you run the URL, you will receive the
following result −

Welcome to my website

Session Information

Session info value

id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 0

JSP - Database Access


We assume you have good understanding on how JDBC application works. Before
starting with database access through a JSP, make sure you have proper JDBC
environment setup along with a database.
For more detail on how to access database using JDBC and its environment setup
you can go through our JDBC Tutorial.
To start with basic concept, let us create a table and create a few records in that table
as follows −

Create Table
To create the Employees table in the EMP database, use the following steps −

Step 1

Open a Command Prompt and change to the installation directory as follows −


C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2

Login to the database as follows −


C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>

Step 3

Create the Employee table in the TEST database as follows − −


mysql> use TEST;
mysql> create table Employees
(
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>

Create Data Records


Let us now create a few records in the Employee table as follows − −
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');


Query OK, 1 row affected (0.00 sec)

mysql>

SELECT Operation
Following example shows how we can execute the SQL SELECT statement using
JTSL in JSP programming −
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ 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>SELECT Operation</title>
</head>

<body>
<sql:setDataSource var = "snapshot" driver =
"com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>

<sql:query dataSource = "${snapshot}" var = "result">


SELECT * from Employees;
</sql:query>

<table border = "1" width = "100%">


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

Access the above JSP, the following result will be displayed −

Emp ID First Name Last Name Age

100 Zara Ali 18

101 Mahnaz Fatma 25

102 Zaid Khan 30

103 Sumit Mittal 28


INSERT Operation
Following example shows how we can execute the SQL INSERT statement using
JTSL in JSP programming −
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ 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>JINSERT Operation</title>
</head>

<body>
<sql:setDataSource var = "snapshot" driver =
"com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>
<sql:update dataSource = "${snapshot}" var = "result">
INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');
</sql:update>

<sql:query dataSource = "${snapshot}" var = "result">


SELECT * from Employees;
</sql:query>

<table border = "1" width = "100%">


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

Access the above JSP, the following result will be displayed −


Emp ID First Name Last Name Age

100 Zara Ali 18

101 Mahnaz Fatma 25

102 Zaid Khan 30

103 Sumit Mittal 28

104 Nuha Ali 2

DELETE Operation
Following example shows how we can execute the SQL DELETE statement using
JTSL in JSP programming −
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ 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>DELETE Operation</title>
</head>

<body>
<sql:setDataSource var = "snapshot" driver =
"com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>

<c:set var = "empId" value = "103"/>

<sql:update dataSource = "${snapshot}" var = "count">


DELETE FROM Employees WHERE Id = ?
<sql:param value = "${empId}" />
</sql:update>

<sql:query dataSource = "${snapshot}" var = "result">


SELECT * from Employees;
</sql:query>
<table border = "1" width = "100%">
<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>

Access the above JSP, the following result will be displayed −

Emp ID First Name Last Name Age

100 Zara Ali 18

101 Mahnaz Fatma 25

102 Zaid Khan 30

UPDATE Operation
Following example shows how we can execute the SQL UPDATE statement using
JTSL in JSP programming −
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ 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>DELETE Operation</title>
</head>
<body>
<sql:setDataSource var = "snapshot" driver =
"com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>

<c:set var = "empId" value = "102"/>

<sql:update dataSource = "${snapshot}" var = "count">


UPDATE Employees SET WHERE last = 'Ali'
<sql:param value = "${empId}" />
</sql:update>

<sql:query dataSource = "${snapshot}" var = "result">


SELECT * from Employees;
</sql:query>

<table border = "1" width = "100%">


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

Access the above JSP, the following result will be displayed −

Emp ID First Name Last Name Age

100 Zara Ali 18

101 Mahnaz Fatma 25

102 Zaid Ali 30


JSP - Standard Tag Library (JSTL)
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's webapps\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 from https://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

fn:contains()
1
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.

4 fn:escapeXml()
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.

fn:substringBefore()
13
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.

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

JSP - Custom Tags


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.

Create "Hello" Tag


Consider you want to define a custom tag named <ex:Hello> and you want to use it
in the following fashion without a body −
<ex:Hello />
To create a custom JSP tag, you must first create a Java class that acts as a tag
handler. Let us now create the HelloTag class as follows −
package com.tutorialspoint;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;

public class HelloTag extends SimpleTagSupport {


public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println("Hello Custom Tag!");
}
}

The above code has simple coding where the doTag() method takes the current
JspContext object using the getJspContext() method and uses it to send "Hello
Custom Tag!" to the current JspWriter object
Let us compile the above class and copy it in a directory available in the environment
variable CLASSPATH. Finally, create the following tag library file: <Tomcat-
Installation-Directory>webapps\ROOT\WEB-INF\custom.tld.
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD</short-name>

<tag>
<name>Hello</name>
<tag-class>com.tutorialspoint.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

Let us now use the above defined custom tag Hello in our JSP program as follows −
<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>

<html>
<head>
<title>A sample custom tag</title>
</head>

<body>
<ex:Hello/>
</body>
</html>

Call the above JSP and this should produce the following result −
Hello Custom Tag!
Accessing the Tag Body
You can include a message in the body of the tag as you have seen with standard
tags. Consider you want to define a custom tag named <ex:Hello> and you want to
use it in the following fashion with a body −
<ex:Hello>
This is message body
</ex:Hello>

Let us make the following changes in the above tag code to process the body of the
tag −
package com.tutorialspoint;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;

public class HelloTag extends SimpleTagSupport {


StringWriter sw = new StringWriter();
public void doTag()

throws JspException, IOException {


getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
}

Here, the output resulting from the invocation is first captured into
a StringWriter before being written to the JspWriter associated with the tag. We need
to change TLD file as follows −
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD with Body</short-name>

<tag>
<name>Hello</name>
<tag-class>com.tutorialspoint.HelloTag</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>

Let us now call the above tag with proper body as follows −
<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>

<html>
<head>
<title>A sample custom tag</title>
</head>

<body>
<ex:Hello>
This is message body
</ex:Hello>
</body>
</html>

You will receive the following result −


This is message body
Custom Tag Attributes
You can use various attributes along with your custom tags. To accept an attribute
value, a custom tag class needs to implement the setter methods, identical to the
JavaBean setter methods as shown below −
package com.tutorialspoint;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;

public class HelloTag extends SimpleTagSupport {


private String message;

public void setMessage(String msg) {


this.message = msg;
}
StringWriter sw = new StringWriter();
public void doTag()

throws JspException, IOException {


if (message != null) {
/* Use message from attribute */
JspWriter out = getJspContext().getOut();
out.println( message );
} else {
/* use message from the body */
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
}
}

The attribute's name is "message", so the setter method is setMessage(). Let us


now add this attribute in the TLD file using the <attribute> element as follows −
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD with Body</short-name>

<tag>
<name>Hello</name>
<tag-class>com.tutorialspoint.HelloTag</tag-class>
<body-content>scriptless</body-content>

<attribute>
<name>message</name>
</attribute>

</tag>
</taglib>

Let us follow JSP with message attribute as follows −


<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>

<html>
<head>
<title>A sample custom tag</title>
</head>

<body>
<ex:Hello message = "This is custom tag" />
</body>
</html>

This will produce following result −


This is custom tag
Consider including the following properties for an attribute −

S.No. Property & Purpose


name
1
The name element defines the name of an attribute. Each attribute name must be
unique for a particular tag.

required
2
This specifies if this attribute is required or is an optional one. It would be false for
optional.

rtexprvalue
3
Declares if a runtime expression value for a tag attribute is valid

type
4
Defines the Java class-type of this attribute. By default it is assumed as String

description
5
Informational description can be provided.

fragment
6
Declares if this attribute value should be treated as a JspFragment.

Following is the example to specify properties related to an attribute −


.....
<attribute>
<name>attribute_name</name>
<required>false</required>
<type>java.util.Date</type>
<fragment>false</fragment>
</attribute>
.....

If you are using two attributes, then you can modify your TLD as follows −
.....
<attribute>
<name>attribute_name1</name>
<required>false</required>
<type>java.util.Boolean</type>
<fragment>false</fragment>
</attribute>

<attribute>
<name>attribute_name2</name>
<required>true</required>
<type>java.util.Date</type>
</attribute>
.....

JSP - Expression Language (EL)


JSP Expression Language (EL) makes it possible to easily access application data
stored in JavaBeans components. JSP EL allows you to create expressions
both (a) arithmetic and (b) logical. Within a JSP EL expression, you can
use integers, floating point numbers, strings, the built-in constants true and
false for boolean values, and null.

Simple Syntax
Typically, when you specify an attribute value in a JSP tag, you simply use a string.
For example −
<jsp:setProperty name = "box" property = "perimeter" value =
"100"/>
JSP EL allows you to specify an expression for any of these attribute values. A simple
syntax for JSP EL is as follows −
${expr}
Here expr specifies the expression itself. The most common operators in JSP EL
are . and []. These two operators allow you to access various attributes of Java Beans
and built-in JSP objects.
For example, the above syntax <jsp:setProperty> tag can be written with an
expression like −
<jsp:setProperty name = "box" property = "perimeter"
value = "${2*box.width+2*box.height}"/>
When the JSP compiler sees the ${} form in an attribute, it generates code to
evaluate the expression and substitues the value of expresson.
You can also use the JSP EL expressions within template text for a tag. For example,
the <jsp:text> tag simply inserts its content within the body of a JSP. The
following <jsp:text> declaration inserts <h1>Hello JSP!</h1> into the JSP output −
<jsp:text>
<h1>Hello JSP!</h1>
</jsp:text>

You can now include a JSP EL expression in the body of a <jsp:text> tag (or any
other tag) with the same ${} syntax you use for attributes. For example −
<jsp:text>
Box Perimeter is: ${2*box.width + 2*box.height}
</jsp:text>

EL expressions can use parentheses to group subexpressions. For example, ${(1 +


2) * 3} equals 9, but ${1 + (2 * 3)} equals 7.
To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute
of the page directive as below −
<%@ page isELIgnored = "true|false" %>
The valid values of this attribute are true and false. If it is true, EL expressions are
ignored when they appear in static text or tag attributes. If it is false, EL expressions
are evaluated by the container.

Basic Operators in EL
JSP Expression Language (EL) supports most of the arithmetic and logical operators
supported by Java. Following table lists out the most frequently used operators −

S.No. Operator & Description

1 .
Access a bean property or Map entry

[]
2
Access an array or List element

()
3
Group a subexpression to change the evaluation order

+
4
Addition

-
5
Subtraction or negation of a value

*
6
Multiplication

/ or div
7
Division

% or mod
8
Modulo (remainder)
== or eq
9
Test for equality

!= or ne
10
Test for inequality

< or lt
11
Test for less than

> or gt
12
Test for greater than

<= or le
13
Test for less than or equal

>= or ge
14
Test for greater than or equal

&& or and
15
Test for logical AND

|| or or
16
Test for logical OR

! or not
17
Unary Boolean complement

empty
18
Test for empty variable values

Functions in JSP EL
JSP EL allows you to use functions in expressions as well. These functions must be
defined in the custom tag libraries. A function usage has the following syntax −
${ns:func(param1, param2, ...)}
Where ns is the namespace of the function, func is the name of the function
and param1 is the first parameter value. For example, the function fn:length, which
is part of the JSTL library. This function can be used as follows to get the length of a
string.
${fn:length("Get my length")}
To use a function from any tag library (standard or custom), you must install that
library on your server and must include the library in your JSP using
the <taglib> directive as explained in the JSTL chapter.

JSP EL Implicit Objects


The JSP expression language supports the following implicit objects −

S.No Implicit object & Description

1 pageScope
Scoped variables from page scope

requestScope
2
Scoped variables from request scope

sessionScope
3
Scoped variables from session scope

applicationScope
4
Scoped variables from application scope

param
5
Request parameters as strings

paramValues
6
Request parameters as collections of strings

header
7
HTTP request headers as strings

8 headerValues
HTTP request headers as collections of strings

initParam
9
Context-initialization parameters

cookie
10
Cookie values

pageContext
11
The JSP PageContext object for the current page

You can use these objects in an expression as if they were variables. The examples
that follow will help you understand the concepts −

The pageContext Object


The pageContext object gives you access to the pageContext JSP object. Through
the pageContext object, you can access the request object. For example, to access
the incoming query string for a request, you can use the following expression −
${pageContext.request.queryString}
The Scope Objects
The pageScope, requestScope, sessionScope, and applicationScope variables
provide access to variables stored at each scope level.
For example, if you need to explicitly access the box variable in the application scope,
you can access it through the applicationScope variable as applicationScope.box.

The param and paramValues Objects


The param and paramValues objects give you access to the parameter values
normally available through
the request.getParameter and request.getParameterValues methods.
For example, to access a parameter named order, use the
expression ${param.order} or ${param["order"]}.
Following is the example to access a request parameter named username −
<%@ page import = "java.io.*,java.util.*" %>
<%String title = "Accessing Request Param";%>

<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>

<div align = "center">


<p>${param["username"]}</p>
</div>
</body>
</html>

The param object returns single string values, whereas the paramValues object
returns string arrays.

header and headerValues Objects


The header and headerValues objects give you access to the header values normally
available through the request.getHeader and the request.getHeaders methods.
For example, to access a header named user-agent, use the
expression ${header.user-agent} or ${header["user-agent"]}.
Following is the example to access a header parameter named user-agent −
<%@ page import = "java.io.*,java.util.*" %>
<%String title = "User Agent Example";%>

<html>
<head>
<title><% out.print(title); %></title>
</head>

<body>
<center>
<h1><% out.print(title); %></h1>
</center>

<div align = "center">


<p>${header["user-agent"]}</p>
</div>
</body>
</html>

The output will somewhat be like the following −

User Agent Example

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64;


Trident/4.0;
SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR
3.0.30729;
Media Center PC 6.0; HPNTDF; .NET4.0C; InfoPath.2)
The header object returns single string values, whereas the headerValues object
returns string arrays.

JSP - Exception Handling


When you are writing a JSP code, you might make coding errors which can occur at
any part of the code. There may occur the following type of errors in your JSP code

Checked exceptions

A checked exception is an exception that is typically a user error or a problem that


cannot be foreseen by the programmer. For example, if a file is to be opened, but the
file cannot be found, an exception occurs. These exceptions cannot simply be ignored
at the time of compilation.

Runtime exceptions

A runtime exception is an exception that probably could have been avoided by the
programmer. As opposed to the checked exceptions, runtime exceptions are ignored
at the time of compliation.

Errors

These are not exceptions at all, but problems that arise beyond the control of the user
or the programmer. Errors are typically ignored in your code because you can rarely
do anything about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
We will further discuss ways to handle run time exception/error occuring in your JSP
code.

Using Exception Object


The exception object is an instance of a subclass of Throwable (e.g., java.lang.
NullPointerException) and is only available in error pages. Following table lists out
the important methods available in the Throwable class.

S.No. Methods & Description

public String getMessage()


1
Returns a detailed message about the exception that has occurred. This message
is initialized in the Throwable constructor.

2 public Throwable getCause()


Returns the cause of the exception as represented by a Throwable object.

public String toString()


3
Returns the name of the class concatenated with the result of getMessage().

public void printStackTrace()


4
Prints the result of toString() along with the stack trace to System.err, the error
output stream.

public StackTraceElement [] getStackTrace()


5 Returns an array containing each element on the stack trace. The element at index
0 represents the top of the call stack, and the last element in the array represents
the method at the bottom of the call stack.

public Throwable fillInStackTrace()


6
Fills the stack trace of this Throwable object with the current stack trace, adding to
any previous information in the stack trace.

JSP gives you an option to specify Error Page for each JSP. Whenever the page
throws an exception, the JSP container automatically invokes the error page.
Following is an example to specifiy an error page for a main.jsp. To set up an error
page, use the <%@ page errorPage = "xxx" %> directive.
<%@ page errorPage = "ShowError.jsp" %>

<html>
<head>
<title>Error Handling Example</title>
</head>

<body>
<%
// Throw an exception to invoke the error page
int x = 1;

if (x == 1) {
throw new RuntimeException("Error condition!!!");
}
%>
</body>
</html>

We will now write one Error Handling JSP ShowError.jsp, which is given below. Notice
that the error-handling page includes the directive <%@ page isErrorPage = "true"
%>. This directive causes the JSP compiler to generate the exception instance
variable.
<%@ page isErrorPage = "true" %>

<html>
<head>
<title>Show Error Page</title>
</head>

<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre><% exception.printStackTrace(response.getWriter());
%></pre>
</body>
</html>

Access the main.jsp, you will receive an output somewhat like the following −
java.lang.RuntimeException: Error condition!!!
......

Opps...
Sorry, an error occurred.

Here is the exception stack trace:


Using JSTL Tags for Error Page
You can make use of JSTL tags to write an error page ShowError.jsp. This page
has almost same logic as in the above example, with better structure and more
information −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"
%>
<%@page isErrorPage = "true" %>

<html>
<head>
<title>Show Error Page</title>
</head>

<body>
<h1>Opps...</h1>
<table width = "100%" border = "1">
<tr valign = "top">
<td width = "40%"><b>Error:</b></td>
<td>${pageContext.exception}</td>
</tr>

<tr valign = "top">


<td><b>URI:</b></td>
<td>${pageContext.errorData.requestURI}</td>
</tr>

<tr valign = "top">


<td><b>Status code:</b></td>
<td>${pageContext.errorData.statusCode}</td>
</tr>

<tr valign = "top">


<td><b>Stack trace:</b></td>
<td>
<c:forEach var = "trace"
items = "${pageContext.exception.stackTrace}">
<p>${trace}</p>
</c:forEach>
</td>
</tr>
</table>

</body>
</html>

Access the main.jsp, the following will be generated −

Opps...

Error: java.lang.RuntimeException: Error condition!!!

URI: /main.jsp

Status code: 500

org.apache.jsp.main_jsp._jspService(main_jsp.java:65)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:
Stack trace: javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Using Try...Catch Block


If you want to handle errors within the same page and want to take some action
instead of firing an error page, you can make use of the try....catch block.
Following is a simple example which shows how to use the try...catch block. Let us
put the following code in main.jsp −
<html>
<head>
<title>Try...Catch Example</title>
</head>

<body>
<%
try {
int i = 1;
i = i / 0;
out.println("The answer is " + i);
}
catch (Exception e) {
out.println("An exception occurred: " +
e.getMessage());
}
%>
</body>
</html>

Access the main.jsp, it should generate an output somewhat like the following −
An exception occurred: / by zero

JSP - XML Data


When you send the XML data via HTTP, it makes sense to use JSP to handle
incoming and outgoing XML documents; for example, RSS documents. As an XML
document is merely a bunch of text, creating one through a JSP is much easier than
creating an HTML document.

Sending XML from a JSP


You can send the XML content using JSPs the same way you send HTML. The only
difference is that you must set the content type of your page to text/xml. To set the
content type, use the <%@page%> tag, like this −
<%@ page contentType = "text/xml" %>
Following example will show how to send XML content to the browser −
<%@ page contentType = "text/xml" %>

<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
</books>

Access the above XML using different browsers to see the document tree
presentation of the above XML.
Processing XML in JSP
Before you proceed with XML processing using JSP, you will need to copy the
following two XML and XPath related libraries into your <Tomcat Installation
Directory>\lib −
• XercesImpl.jar − Download it from https://www.apache.org/dist/xerces/j/
• xalan.jar − Download it from https://xml.apache.org/xalan-j/index.html
Let us put the following content in books.xml file −
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>

<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>

Try the following main.jsp, keeping in the same directory −


<%@ 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:parse Tags</title>
</head>

<body>
<h3>Books Info:</h3>
<c:import var = "bookInfo"
url="http://localhost:8080/books.xml"/>

<x:parse xml = "${bookInfo}" 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>

Access the above JSP using http://localhost:8080/main.jsp, the following result will
be displayed −
Books Info:

The title of the first book is:Padam History

The price of the second book: 2000


Formatting XML with JSP
Consider the following XSLT stylesheet style.xsl −
<?xml version = "1.0"?>
<xsl:stylesheet xmlns:xsl =
"http://www.w3.org/1999/XSL/Transform"
version = "1.0">

<xsl:output method = "html" indent = "yes"/>


<xsl:template match = "/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>

<xsl:template match = "books">


<table border = "1" width = "100%">
<xsl:for-each select = "book">
<tr>
<td>
<i><xsl:value-of select = "name"/></i>
</td>

<td>
<xsl:value-of select = "author"/>
</td>

<td>
<xsl:value-of select = "price"/>
</td>
</tr>
</xsl:for-each>
</table>

</xsl:template>
</xsl:stylesheet>

Now consider the following JSP file −


<%@ 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:transform Tags</title>
</head>

<body>
<h3>Books Info:</h3>
<c:set var = "xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>

<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>

<c:import url = "http://localhost:8080/style.xsl" var =


"xslt"/>
<x:transform xml = "${xmltext}" xslt = "${xslt}"/>
</body>
</html>

The following result will be displayed −

Books Info:

Padam History ZARA 100

Great Mistry NUHA 2000

You might also like