Professional Documents
Culture Documents
Advanced Java: JSP Technology Is Used To Create Web Application Just Like Servlet Technology. It Can Be
Advanced Java: JSP Technology Is Used To Create Web Application Just Like Servlet Technology. It Can Be
JSP
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.
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.
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.
1
ADVANCED JAVA
o Instantiation (Object of the Generated Servlet is created).
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator. The JSP translator is a part of the web server which is responsible for translating
the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets
converted into the class file. Moreover, all the processes that happen in Servlet are performed
on JSP later like initialization, committing response to the browser and destroy.
To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.
2
ADVANCED JAVA
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in
the JSP page. We will learn scriptlet tag later.
1. <html>
2. <body>
4. </body>
5. </html>
No, there is no need of directory structure if you don't have class files or TLD files. For
example, put JSP files in a folder directly and deploy that folder. It will be running fine.
However, if you are using Bean class, Servlet or TLD file, the directory structure is required.
The directory structure of JSP page is same as Servlet. We contain the JSP page outside the
WEB-INF folder or in any directory.
3
ADVANCED JAVA
1. javax.servlet.jsp
2. javax.servlet.jsp.tagext
javax.servlet.jsp package
Package javax.servlet.jsp
Classes and interfaces for the Core JSP 2.3 API.
Interface Summary
Interface Description
HttpJspPage The HttpJspPage interface describes the interaction that a JSP Page
Implementation Class must satisfy when using the HTTP protocol.
JspApplicationContext Stores application-scoped information relevant to JSP containers.
JspPage The JspPage interface describes the generic interaction that a JSP Page
Implementation class must satisfy; pages that use the HTTP protocol
are described by the HttpJspPage interface.
4
ADVANCED JAVA
Class Summary
Class Description
JspContext JspContext serves as the base class for the PageContext class and abstracts all
information that is not specific to servlets.
JspEngineInfo The JspEngineInfo is an abstract class that provides information on the current
JSP engine.
JspFactory The JspFactory is an abstract class that defines a number of factory methods
available to a JSP page at runtime for the purposes of creating instances of various
interfaces and classes used to support the JSP implementation.
JspWriter The actions and template data in a JSP page is written using the JspWriter object
that is referenced by the implicit variable out which is initialized automatically
using methods in the PageContext object.
PageContext PageContext extends JspContext to provide useful context information for when
JSP technology is used in a Servlet environment.
Exception Summary
Exception Description
JspException A generic exception known to the JSP engine; uncaught JspExceptions
will result in an invocation of the errorpage machinery.
JspTagException Exception to be used by a Tag Handler to indicate some unrecoverable
error.
SkipPageException Exception to indicate the calling page must cease evaluation.
The javax.servlet.jsp package contains a number of classes and interfaces that describe and define
the contracts between a JSP page implementation class and the runtime environment provided
for an instance of such a class by a conforming JSP container.
According to the JSP specification, all the generated servlet classes must implement the
JspPage interface. It extends the Servlet interface. It provides two life cycle methods.
5
ADVANCED JAVA
1. public void jspInit(): It is invoked only once during the life cycle of the JSP when
JSP page is requested firstly. It is used to perform initialization. It is same as the init()
method of Servlet interface.
2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP
before the JSP page is destroyed. It can be used to perform some clean up operation.
The HttpJspPage interface provides the one life cycle method of JSP. It extends the JspPage
interface.
1. public void _jspService(): It is invoked each time when request for the JSP page
comes to the container. It is used to process the request. The underscore _ signifies
that you cannot override this method.
6
ADVANCED JAVA
Package javax.servlet.jsp.tagext
Classes and interfaces for the definition of JavaServer Pages Tag Libraries.
See:
Description
Interface Summary
The BodyTag interface extends IterationTag by defining
BodyTag additional methods that let a tag handler manipulate the
content of evaluating its body.
For a tag to declare that it accepts dynamic attributes, it must
DynamicAttributes
implement this interface.
The IterationTag interface extends Tag by defining one
IterationTag
additional method that controls the reevaluation of its body.
This interface indicates to the container that a tag handler
JspIdConsumer
wishes to be provided with a compiler generated ID.
JspTag Serves as a base class for Tag and SimpleTag.
SimpleTag Interface for defining Simple Tag Handlers.
The interface of a classic tag handler that does not want to
Tag
manipulate its body.
The auxiliary interface of a Tag, IterationTag or BodyTag tag
TryCatchFinally
handler that wants additional hooks for managing resources.
Class Summary
An encapsulation of the evaluation of the body of an action
BodyContent
so it is available to a tag handler.
A base class for defining tag handlers implementing
BodyTagSupport
BodyTag.
FunctionInfo Information for a function in a Tag Library.
Encapsulates a portion of JSP code in an object that can be
JspFragment
invoked as many times as needed.
PageData Translation-time information on a JSP page.
A base class for defining tag handlers implementing
SimpleTagSupport
SimpleTag.
TagAdapter Wraps any SimpleTag and exposes it using a Tag interface.
TagAttributeInfo Information on the attributes of a Tag, available at
7
ADVANCED JAVA
translation time.
The (translation-time only) attribute/value information for
TagData
a tag instance.
Optional class provided by the tag library author to
TagExtraInfo describe additional translation-time information not
described in the TLD.
Tag information for a tag file in a Tag Library; This class
TagFileInfo is instantiated from the Tag Library Descriptor file (TLD)
and is available only at translation time.
Tag information for a tag in a Tag Library; This class is
TagInfo instantiated from the Tag Library Descriptor file (TLD)
and is available only at translation time.
Translation-time information associated with a taglib
TagLibraryInfo
directive, and its underlying TLD file.
TagLibraryValidator Translation-time validator class for a JSP page.
A base class for defining new tag handlers implementing
TagSupport
Tag.
Variable information for a tag in a Tag Library; This class
TagVariableInfo is instantiated from the Tag Library Descriptor file (TLD)
and is available only at translation time.
A validation message from either TagLibraryValidator or
ValidationMessage
TagExtraInfo.
Information on the scripting variables that are
VariableInfo
created/modified by a tag (at run-time).
Custom actions can be used by JSP authors and authoring tools to simplify writing
JSP pages. A custom action can be either an empty or a non-empty action.
An empty tag has no body. There are two equivalent syntaxes, one with separate
start and end tags, and one where the start and end tags are combined. The two
following examples are identical:
<x:foo att="myObject"></foo>
<x:foo att="myObject"/>
8
ADVANCED JAVA
A non-empty tag has a start tag, a body, and an end tag. A prototypical example is
of the form:
<x:foo att="myObject" >
BODY
</x:foo/>
Java provides various scripting elements that allow you to insert Java code from your
JSP code into the servlet. Scripting elements have different components that are
allowed by JSP. Understanding each of these components is essential to writing code
in JSP. Let us discuss each of the components in detail.
Scripting elements in JSP must be written within the <% %> tags. The JSP engine will
process any code you write within the pair of the <% and %> tags, and any other
texts within the JSP page will be treated as HTML code or plain text while translating
the JSP page.
Example:
<!DOCTYPE html>
<html>
<head>
<title>w3schools JSP Tutorial</title>
</head>
<% int cnt = 6; %>
<body>
Calculated page count is <% out.println(cnt); %>
</body>
9
ADVANCED JAVA
</html>
Here are five different scripting elements:
Comment
Comments are marked as text or statements that are ignored by the JSP container.
They are useful when you want to write some useful information or logic to
remember in the future.
Example:
Directives
These tags are used to provide specific instructions to the web container when the
page is translated. It has three subcategories:
Declaration
10
ADVANCED JAVA
As the name suggests, it is used to declare methods and variables you will use in
your Java code within a JSP file. According to the rules of JSP, any variable must be
declared before it can be used.
Syntax:
<!DOCTYPE html>
<html>
<body>
<%! int variable_value=62; %>
<%= " Your integer data is :"+ variable_value %>
</body>
</html>
The scriptlet tag allows writing Java code statements within the JSP page. This tag is
responsible for implementing the functionality of _jspService() by scripting the java
code.
Syntax:
<!DOCTYPE html>
<html>
<head>
<title>Scriptlet Tag</title>
</head>
<% int count = 2; %>
<body>
Calculated page count <% out.println(cnt); %>
</body>
</html>
Another code snippet that shows how to write and mix scriptlet tags with HTML:
Example:
<table border="1">
<% for ( int g = 1; g <= cnt; g++ ) { %>
<tr>
<td>Number</td>
<td><% = g+1 %></td>
</tr>
11
ADVANCED JAVA
<% } %>
</table>
Expressions
Example:
<!DOCTYPE html>
<html>
<body>
<%= "A JSP based string" %>
</body>
</html>
request
1 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
12
ADVANCED JAVA
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.
13
ADVANCED JAVA
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.
out.print(dataType dt)
1
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.
14
ADVANCED JAVA
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.
15
ADVANCED JAVA
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.
Directives
Directives supply directions and messages to a JSP container. The directives provide global
information about the entire page of JSP. Hence, they are an essential part of the JSP code.
These special instructions are used for translating JSP to servlet code. In this chapter, you
will learn about the different components of directives in detail.
In JSP's life cycle phase, the code must be converted to a servlet that deals with the
translation phase. They provide commands or directions to the container on how to deal with
and manage certain JSP processing portions. Directives can contain several attributes that are
separated by a comma and act as key-value pairs. In JSP, directives are described with a pair
of <%@ .... %> tags.
1. Page directive
2. Include directive
3. Taglib directive
Let us now discuss each of them in detail.
Page Directive
16
ADVANCED JAVA
The page directive is used for defining attributes that can be applied to a complete JSP page.
You may place your code for Page Directives anywhere within your JSP page. However, in
general, page directives are implied at the top of your JSP page.
1. buffer: Buffer attribute sets the buffer size in KB to control the JSP page's output.
2. contentType: The ContentType attribute defines the document's MIME (Multipurpose
Internet Mail Extension) in the HTTP response header.
3. autoFlush: The autofill attribute controls the behavior of the servlet output buffer. It
monitors the buffer output and specifies whether the filled buffer output should be
flushed automatically or an exception should be raised to indicate buffer overflow.
4. errorPage: Defining the "ErrorPage" attribute is the correct way to handle JSP errors.
If an exception occurs on the current page, it will be redirected to the error page.
5. extends: extends attribute used for specifying a superclass that tells whether the
generated servlet has to extend or not.
6. import: The import attribute is used to specify a list of packages or classes used in JSP
code, just as Java's import statement does in a Java code.
7. isErrorPage: This "isErrorPage" attribute of the Page directive is used to specify that
the current page can be displayed as an error page.
8. info: This "info" attribute sets the JSP page information, which is later obtained using
the getServletInfo() method of the servlet interface.
9. isThreadSafe: Both the servlet and JSP are multithreaded. If you want to control JSP
page behavior and define the threading model, you can use the "isThreadSafe"
attribute of the page directive.
10. Language: The language attribute specifies the programming language used in the JSP
page. The default value of the language attribute is "Java".
11. Session: In JSP, the page directive session attribute specifies whether the current JSP
page participates in the current HTTP session.
12. isELIgnored: This isELIgnored attribute is used to specify whether the expression
language (EL) implied by the JSP page will be ignored.
13. isScriptingEnabled: This "isScriptingEnabled" attribute determines if the scripting
elements are allowed for use or not.
Include Directive
The JSP "include directive" is used to include one file in another JSP file. This includes
HTML, JSP, text, and other files. This directive is also used to create templates according to
the developer's requirement and breaks the pages in the header, footer, and sidebar.
17
ADVANCED JAVA
<jsp:directive.include file = "relative url" />
Example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Include Directive Example</title>
</head>
<body>
<p>This file includes a header file named directive_header_code.jsp</p>
</body>
</html>
In the above example of JSP code, a JSP header file is being added to the current JSP file
using "include directive".
Taglib Directive
The JSP taglib directive is implemented to define a tag library with "taglib" as its prefix.
Custom tag sections of JSP use taglib. JSP's taglibdirective is used as standard tag libraries.
Exceptions
Exceptions can be defined as an object that is thrown during a program run. Exception
handling is the practice of handling errors at runtime. Exceptions can occur at any time in a
web application. Therefore, the web developer must handle exceptions to be on the safe side
and make the user work flawlessly on the web.
Checked Exception
Runtime Exception
Errors Exception
Let us now discuss each of them in detail.
Checked Exceptions
"Checked exceptions" are a type of exception that is usually a user fault or a problem that
cannot be foreseen by the programmer. This type of exception is checked at compile-time.
Here is a list of some common "Checked exceptions" that occur in the programming domain:
Runtime Exceptions
"Runtime exceptions" can be defined as exceptions evaded by the programmer. They are left
unnoticed at compilation time. Here is the list of some of the common examples that occurred
in the programming domain:
Errors
"Error exception" arises solely because of the user or programmer. Here you might encounter
error due to stack overflows. Here is the list of some of the common examples that occurred
in the programming domain:
19
ADVANCED JAVA
Error: This is a subclass of throwable that indicates serious problems the applications
cannot catch.
Internal Error: This error occurs when a fault occurs in the Java Virtual Machine
(JVM).
Instantiation error: This error occurs when you try to instantiate an object, ultimately
failing to do that.
ArithmeticException Example
Example (HTML file):
<!DOCTYPE html>
<html>
<head>
<title>Enter two Integers for Division</title>
</head>
<body>
<form action="submit.jsp">
Insert first Integer: <input type="text" name="numone" /><br />
Insert second Integer: <input type="text" name="numtwo" /><br />
<input type="submit" value="Get Results" />
</form>
</body>
</html>
Example (submit.jsp):
<%
String num1 = request.getParameter("numone");
String num2 = request.getParameter("numtwo");
int var1= Integer.parseInt(num1);
int var2= Integer.parseInt(num2);
int r= var1 / var2;
out.print("Output is: "+ r);
%>
Example (exception.jsp):
<%
out.print("Error Message : ");
out.print(exception.getMessage());
%>
20
ADVANCED JAVA
Actions Tags
The JSP specification provides a standard tag called Action tag used within JSP code
and is used to remove or eliminate Scriptlet code from your JSP code as JSP
Scriptlets are obsolete and are not considered nowadays. There are many JSP action
tags or elements, and each of them has its own uses and characteristics. Each JSP
action tag is implemented to perform some precise tasks.
The action tag is also implemented to streamline flow between pages and to employ
a Java Bean. As it coincides with the XML standard, the syntax for the action element
is:
Syntax:
Two basic attributes are commonly used for all action tags. These are:
1. id: The id attribute defines unique action elements and allows actions to be
referenced within the JSP page. When the action creates an object's instance,
the id attribute is used to refer to it.
2. Scope: The scope attribute is used for identifying an action's life cycle. It
correlates with the id attribute because the scope attribute is used to establish
that particular object's lifespan associated with the ID.
Here the syntax and implementation of some actions are described below:
21
ADVANCED JAVA
jsp:include Action
This "include action" allows you to include another resource in the page being
generated.
Syntax:
<!DOCTYPE html>
<html>
<head>
<title>JSP include Action</title>
</head>
<body>
<h2>JSP page: with include</h2>
<jsp:include page="header.jsp" flush="false" />
</body>
</html>
jsp:forward Action
This "forward action" terminates the current page and allows you to forward the
request to other resources.
Syntax:
<!DOCTYPE html>
<html>
<head>
<title>Example for Forward Action</title>
</head>
<body>
<h2>JSP page: Demo forward</h2>
<jsp:forward page="forward_eg.jsp" />
</body>
</html>
It is to be noted that this JSP file and forward_eg.jsp file should have to reside in the
same directory to make it work.
jsp:param Action
This "param action" is used for setting the parameter for (forward or include) value.
22
ADVANCED JAVA
Syntax:
<!DOCTYPE html>
<html>
<head>
<title>Example of param Action</title>
</head>
<body>
<h2>JSP page: Param with forward</h2>
<jsp:forward page="forward_eg.jsp">
<jsp:param name="date" value="06-09-2019" />
<jsp:param name="time" value="10:30PM" />
<jsp:param name="data" value="GKR" />
</jsp:forward>
</body>
</html>
jsp:useBean Action
Syntax:
<!DOCTYPE html>
<html>
<head>
<title>JSP Page for showing use of useBean action</title>
</head>
<body>
<h2>UseBean Action</h2>
<jsp:useBean id="teacher" class="packageName.Teacher" />
<jsp:setProperty name="teacher" property="*" />
<h2>
name:<jsp:getProperty name="teacher" property="t_name" /> <br />
empno:<jsp:getProperty name="teacher" property="dept" /> <br />
</h2>
</body>
</html>
Example: Java Class:
package samplePackageName;
23
ADVANCED JAVA
public Teacher() {}
Syntax:
out.print((6*4));
It is to be noted that you will never terminate an expression using semicolon within
Expression Tag. Like this:
24
ADVANCED JAVA
Example:
<!DOCTYPE html>
<html>
<head>
<title>Expression Tag in JSP</title>
</head>
<% int rollNo = 02; %>
<body>
The next roll number is: <%= ++rollNo %>
</body>
</html>
Different Expression Tags with Different Expression Types:
Expression of Values
In this chase, you have to pass the expression of values within the expression tag.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example1</title>
</head>
<body>
<%= 2+4*5 %>
</body>
</html>
Expression of Variables
In this case, you have to initialize a few variables, which can then be passed as the expression
of variables within the expression tag in order to evaluate the result.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>
<% int g = 60; int k = 40; int r = 20; %>
<%= g+k+r %>
</body>
</html>
25
ADVANCED JAVA
Here, you have to set an attribute using an application implicit object and then display it with
a simple string on another JSP page via an expression tag.
Example(start.jsp):
<!DOCTYPE html>
<html>
<head>
<title>Example of JSP expression tag</title>
</head>
<body>
<% application.setAttribute("EmpName", "Alex"); %>
<a href="show.jsp"> Click to See </a>
</body>
</html>
Example(show.jsp):
<!DOCTYPE html>
<html>
<head>
<title>Show Employee Name Page</title>
</head>
<body>
<%="A String value:" %> <br />
<%= application.getAttribute("EmpName") %>
</body>
</html>
1. In Scriptlet tag, it evaluates your Java expression but does not print or show your
result in conjunction with the HTML created. The declared variables have a local
scope only and hence can't take access from another place in the .jsp. In contrast, the
Expression Tag has the capability to evaluate the Java expression. It is used for
inserting the result in the form of a string in conjunction with the HTML in the JSP.
2. You don't have to write the out.println in the expression tag to print the expression
based output because these are changed into out.print() statement (as shown above the
process of transformation of expression), which gets inserted by the container in
the _jspService(-, -) of the servlet class.
26
ADVANCED JAVA
MVC Architecture in JSP with Example
Prashant Srivastava MVC in jsp
MVC stands for Model View Controller. It is a design pattern which is used to separate the
business logic, presentation logic and data. It can be used to design a web application in a
standard manner ie: It will provide a pattern to design web application. It is able to define
which element is used for which purpose. As per MVC, our application will be divided
into three layers.
1.Model Layer:
Model Layer is the data layer.
It consists of all the data of our web application.
It represents a state of an application.
The Model Layer is responsible to connect with the database as well as stores the data
into a database.
It consists of all the classes in our application which have the connection to the
database.
2. View Layer:
It represents the presentation layer
It normally represents the User Interface (UI) of the application.
We can use HTML,CSS,JS etc to create presentation layer.
3. Controller Layer:
It is an interface between the view layer and the model layer.
It receives the request from View Layer.
It read the data which is coming from the presentation layer.
To read data from the presentation layer, we can use Servlet, JSP, Filter, etc.
The MVC Architecture is given below:
MVC Architecture
27
ADVANCED JAVA
index.jsp
ControllerServlet.java
28
ADVANCED JAVA
LoginMvcBean.java
29
ADVANCED JAVA
loginSuccess.jsp
30
ADVANCED JAVA
loginError.jsp
web.xml
31
ADVANCED JAVA
32
ADVANCED JAVA
33
ADVANCED JAVA
JSTL Tags
i) c:out:
it is used to display the result of an expression. It is just like an expression tag.
ii) c:set:
34
ADVANCED JAVA
It is used to set the value of a variable in a specified scope.
iii) c:remove:
This JSTL core tag is used to remove an attribute from a specified scope or from all scope.
iv) c:catch:
It is used for exception handling in JSP.
35
ADVANCED JAVA
v) c:forEach:
It is used for iteration. It is just like for loop in java.
vi) c:param:
It is used to add a parameter and their values to the output of these tags.
vii) c:redirect:
It is used for redirecting the current page to another URL.
36
ADVANCED JAVA
viii) c:url:
To rewrite URL returned from a JSP page, we can use url tag.
ix) c:if:
It is used to testing the condition. It is just like to if statement in java.
x) c:import:
It is used for importing the content from another file/page to the current JSP page.
37
ADVANCED JAVA
i) fmt:timeZone:
It specifies the time zone for any time formatting or parsing action nested in its body.
ii) fmt:setTimeZone:
Stores the given time zone in the time zone configuration variable.
iii) fmt:formatDate:
Formats a date and/or time using the supplied styles and pattern.
iv) fmt:message:
used to display an internationalized message.
v) fmt:formatNumber:
It is used to render numerical value with a specific precision or format.
vi) fmt:parseNumber:
Parses the string representation of number, currency, or percentage.
vii) fmt:parseDate:
38
ADVANCED JAVA
Parses the String representation of the date and/or time.
viii) fmt:bundle:
Load a resource bundle to be used by its tag body.
ix) fmt:setBundle:
Loads a resource bundle and stores it in the named scoped variable or the bundle
configuration variable.
ii) fn:containsIgnoreCase():
It tets if an input string contains the specified substring in a case-insensitive way.
iii) fn:endsWith():
It tets if an input string ends with the specified suffix.
iv) fn:indexOf():
Return the index writing a string of the first occurrence of the specified string.
v) fn:join():
It joins all the elements of an array into a String.
vi) fn:length():
It returns the number of character in a String or number of collection in a String.
vii) fn:replace():
It is used to replacing an input string all occurrences with the given String.
viii) fn:split():
Split a string into an array of a substring.
ix) fn:startsWith():
It tests if an input string starts with the specified prefix.
39
ADVANCED JAVA
x) fn:substring():
It returns a subset of a string
xi) fn:substringAfter():
It returns a subset of a String after a specific substring.
xii) fn:substringBefore():
It returns a subset of a String before a specific substring.
xiii) fn:toLowerCase():
It converts all of the characters of a string to lower case.
xiv) fn:toUpperCase():
It converts all of the characters of a string to upper case.
ii) x:parse:
It is used to parse the XML data specified either via an attribute or in the tag body.
iii) x:set:
It sets the value of a variable of an XPath expression.
iv) x:choose:
Subtag of that will include its body if the condition evaluated to be 'true'.
v) x:when:
Subtag of <choose> that includes its body if its expression evaluates to 'true'.
vi) x:otherwise:
subtag of <choose> that follows the <when> tags and run only if all of the prior condition
evaluated to 'false'.
vii) x:if:
40
ADVANCED JAVA
It evaluates a test XPath expression and if it is true, it processes its body. If the condition is
false, then the body is ignored.
viii) x:param:
It is used along with the transform tag to set a parameter in the XSLT stylesheet.
ix) x: transform:
It applies an XSL transformation on a XML document.
ii) sql:query:
It is used to executes the SQL queries defined in its body or through the SQL attribute.
iii) sql:update:
It executed the SQL update defined in its body or through the SQL attribute.
iv) sql:param:
It sets a parameter in an SQL statement to the specified value.
v) sql:dateParam:
It sets a parameter in an SQL statement to the specified java.util.Date value.
vi) sql:transaction:
It provides nested database action elements with a shared connection, set up to execute all
statement as one transaction
41
ADVANCED JAVA
Custom Tags in JSP with Example
Custom tags are user-defined tags. By using Custom tags we can get the following
advantages:
1. We can reduce the java code into a JSP page.
2. We can provide security in JSP.
3. We can get the logic reusability.
4. By using the custom tag we can separate the business logic from the JSP page.
To creating any Custom Tag we need three things:
1. The Tag Handler Class.
2. The Tag Library Descriptor.
3. A JSP page.
These two classes are available inside the javax.servlet.jsp.tagext. package. if we want to
define the logic for a custom tag start and custom tag end then we override the following two
methods of the Tag Support class.
i) doStartTag()
ii) doEndTag()
42
ADVANCED JAVA
2. The Tag Library Descriptor:
A TLD file is like an XML file in which custom tags are configured. The main purpose of the
TLD file is to connect the Tag handler class with a tag name that will appear in the JSP
document. It also gives more information to the JSP container about the tags it describes. It
describes the tag attributes that can be used with the tag and tells whether they're required or
are optional.
3. A JSP page:
A JSP page is a page where we will be using our custom tag. In the JSP page to define some
prefix for our custom tags, we use taglib directive in JSP. Using taglib directive we also
define a unique identification name for the tag started with the same prefix. To add a prefix
and a unique identification name we use two attributes URI and prefix.
43
ADVANCED JAVA
Pagination in JSP
To divide a large number of records into multiple parts, we use pagination. It allows users to
display a part of records only. Loading all records on a single page may take time, so it is
always recommended to created pagination. In java, we can develop pagination examples
easily. In this pagination example, we are using the MySQL database to fetch records.
We can create pagination example in JSP easily. It is required if you have to display many
records. Displaying many records in a single page may take time, so it is better to break the
page into parts. To do so, we create pagination application.
In this pagination example, we are using MySQL database to fetch records.
We have created “emp” table in “test” database. The emp table has three fields: id, name and
salary. Either create table and insert records manually or import our sql file.
44