JavaServerPages Material
JavaServerPages Material
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.
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.
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.
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.
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.
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 :
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.
Attributes
Following table lists out the attributes associated with the page directive −
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.
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.
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.
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 −
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.
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>
<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 −
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.
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 −
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.
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;
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...
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>
<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.
<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.
<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>
<body>
<xmlElement xmlElementAttr = "Value for the attribute">
Body for XML element
</xmlElement>
</body>
</html>
<head><title>jsp:text action</title></head>
<body>
<books><book><jsp:text>
Welcome to JSP Programming
</jsp:text></book></books>
</body>
</html>
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
<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>
</body>
</html>
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.
<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>
</body>
</html>
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.
</body>
</html>
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>
• Maths Flag :: on
• 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>
</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 −
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.
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 −
[ ] ( ) = , " / ? @ : ;
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
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"));
<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>
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.
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;
</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 −
Example
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 −
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());
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
</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
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 0
Create Table
To create the Employees table in the EMP database, use the following steps −
Step 1
Step 3
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"/>
</body>
</html>
<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>
</body>
</html>
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"/>
</body>
</html>
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"/>
</body>
</html>
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 −
<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 −
<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 −
<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 −
<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 −
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.
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
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.*;
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>
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
<tag>
<name>Hello</name>
<tag-class>com.tutorialspoint.HelloTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>message</name>
</attribute>
</tag>
</taglib>
<html>
<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello message = "This is custom tag" />
</body>
</html>
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.
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>
.....
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>
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 −
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.
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 −
<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
The param object returns single string values, whereas the paramValues object
returns string arrays.
<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
Checked exceptions
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.
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.
<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>
</body>
</html>
Opps...
URI: /main.jsp
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)
<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
<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>
<html>
<head>
<title>JSTL x:parse Tags</title>
</head>
<body>
<h3>Books Info:</h3>
<c:import var = "bookInfo"
url="http://localhost:8080/books.xml"/>
Access the above JSP using http://localhost:8080/main.jsp, the following result will
be displayed −
Books Info:
<td>
<xsl:value-of select = "author"/>
</td>
<td>
<xsl:value-of select = "price"/>
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
<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>
Books Info: