JSP Advance Java
JSP Advance Java
JSP Advance Java
Numerous CGI alternatives and enhancements, such as FastCGI, mod_ perl from
Apache, NSAPI from Netscape, ISAPI from Microsoft, and Java Servlets from Sun
Microsystems, have been created over the years. While these solutions offer
better performance and scalability, all of these technologies suffer from a
common problem: they generate web pages by embedding HTML directly in
programming language code. This pushes the creation of dynamic web pages
exclusively into the realm of programmers. JavaServer Pages, however, changes
all that.
JSP Advantages:
• Compilation
• Initialization
• Execution
• Cleanup
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle.
The four phases have been described below −
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it
needs to compile the page. If the page has never been compiled, or if the JSP
has been modified since it was last compiled, the JSP engine compiles the page.
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing
any requests. If you need to perform JSP-specific initialization, override
the jspInit() method −
Typically, initialization is performed only once and as with the servlet init
method, you generally initialize database connections, open files, and create
lookup tables in the jspInit method.
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the
JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the JSP.
JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being
removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for
servlets. Override jspDestroy when you need to perform any cleanup, such as
releasing database connections or closing open files.
The code written inside the jsp declaration tag is placed outside the service() method
of auto generated servlet.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
JSP expression tag
The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print the
values of variable or method.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Following table lists out the nine Implicit Objects that JSP supports −
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 client.
4 session
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 provides methods to get the HTTP header information
including form data, cookies, HTTP methods etc.
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..
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.
Following table lists out the important methods that we will use to
write boolean char, int, double, object, String, etc.
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.
The session object is used to track client session between client requests
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.
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.
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.
pageContext.removeAttribute("attrName", PAGE_SCOPE);
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 is a wrapper containing the exception thrown from the
previous page. It is typically used to generate an appropriate response to the
error condition.
Following are the unique characteristics that distinguish a JavaBean from other
Java classes −
1. getPropertyName ()
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
1. Create the Tag handler class and perform action at the start or at the end of the tag.
2. Create the Tag Library Descriptor (TLD) file and define tags.
3. Create the JSP file that uses the Custom tag defined in the TLD file.
The PageContext class provides getOut() method that returns the instance of JspWriter class.
TagSupport class provides instance of pageContext bydefault.
It uses taglib directive to use the tags defined in the tld file.
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.
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.
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 −
<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 −
<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.
<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.
<sql:dateParam>
5
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.
<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 −
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.
fn:escapeXml()
4
Escapes characters that can be interpreted as XML markup.
fn:indexOf()
5 Returns the index withing a string of the first occurrence of a specified
substring.
fn:join()
6
Joins all elements of an array into a string.
fn:length()
7 Returns the number of items in a collection, or the number of characters in a
string.
fn:replace()
8 Returns a string resulting from replacing in an input string all occurrences
with a given string.
fn:split()
9
Splits a string into an array of substrings.
fn:startsWith()
10
Tests if an input string starts with the specified prefix.
fn:substring()
11
Returns a subset of a string.
fn:substringAfter()
12
Returns a subset of a string following a specific substring.
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.
fn:trim()
16
Removes white spaces from both ends of a string.
JSTL Core Tags:
The JSTL core tag provides variable support, URL management, flow control etc. The
syntax used for including JSTL core library in your JSP is:
Tags Description
c:out It display the result of an expression, similar to the way <%=...%> tag work.
c:import It Retrives relative or an absolute URL and display the contents to either a String
in 'var',a Reader in 'varReader' or the page.
c:remove It is used for removing the specified scoped variable from a particular scope.
c:catch It is used for Catches any Throwable exceptions that occurs in the body.
c:if It is conditional tag used for testing the condition and display the body content
only if the expression evaluates is true.
c:choose, c:when, It is the simple conditional tag that includes its body content if the evaluated
c:otherwise condition is true.
c:forEach It is the basic iteration tag. It repeats the nested body content for fixed number
of times or over collection.
c:redirect It redirects the browser to a new URL and supports the context-relative URLs.