JSP
Introduction
Jsp
technology is used to web application like servlet.It can be thought as
extension of servlet as it provides more functionality more than that of
servlet like expression language,jstl etc.
Life Cycle of JSP:
1-Translation
2-Compilation
3-Classloading(class
file is loaded by classloader)
4-Instantiation(Object Of generated servlet is created )
5-Initialization( jspInit() method is invoked by container)
6-Request Processing( _jspService() method is invoked by container)
7-Destroy( jspDestroy() method is invoked by container)
Jsp scriptlet tag(Scriptlet Elements):-
1-scriptlet
tag:-
This one is
used to write the java source code.
For eg.
<% java source code
%>
<%@ page
language="java" contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Insert title
here</title>
</head>
<body>
<% out.print("welcome to jsp
scriptlet tag example code"); %>
</body>
</html>
2-expression
tag:-
This one replacement of output
stream in case of servlet.
<%= source code %>
For eg.
<body>
<%=("Hii")%>
</body>
3-Jsp
Declaration tag:-
The Jsp declaration tag is used
to declare variables and methods.
For eg
<%! statement %>
Jsp declaration tag only
declare the variable and methods and most thing is the it is placed out side
the _jspService() method so that it don’t memory get every time when service
method is called.
For eg.
<body>
<%! String name="Jeetendra"; %>
<%=("Hii
") +name %>
</body>
<body>
<%! int cube(int n){
return n*n*n ;
}%>
<%="Cube of
"+5+" is " +cube(5) %>
</body>
The JSP Standard Tag
Library represents a set of tags to
simplify the JSP development.JSTL mainly 5 types of tags:-
1-core tags:-
The JSTL core tag provides variable support,
URL management, Flow Control, etc.the url for the core tag is http://java.sun.com/jsp/jstl/core
The prefix of the core tag is c.
There are following jstl core
tags that are given below:-
Tag
|
Description
|
Like <%= ... >, but for expressions.
|
|
Sets the result of an expression
evaluation in a 'scope'
|
|
Removes a scoped variable (from a
particular scope, if specified).
|
|
Catches any Throwable that occurs in
its body and optionally exposes it.
|
|
Simple conditional tag which evalutes
its body if the supplied condition is true.
|
|
Simple conditional tag that establishes
a context for mutually exclusive conditional operations, marked by
<when> and <otherwise>
|
|
Subtag of <choose> that includes
its body if its condition evalutes to 'true'.
|
|
Subtag of <choose> that follows
<when> tags and runs only if all of the prior conditions evaluated to
'false'.
|
|
Retrieves an absolute or relative URL
and exposes its contents to either the page, a String in 'var', or a Reader
in 'varReader'.
|
|
The basic iteration tag, accepting many
different collection types and supporting subsetting and other functionality
.
|
|
Iterates over tokens, separated by the
supplied delimeters.
|
|
Adds a parameter to a containing
'import' tag's URL.
|
|
Redirects to a new URL.
|
|
Creates a URL with optional query
parameters
|
SnapShot of few tags:-
<%@ page
language="java" contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html
PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Insert title
here</title>
</head>
<body>
<c:import var="data"
url="http://www.javatpoint.com/jstl"></c:import>
<h2>Data Is</h2>
<c:out value="${data}"></c:out>
<c:catch
var="g" >
<% int i=29/0; %>
</c:catch>
<c:if test="${g!=null}">
<p>the exception. :${g.message}</p>
</c:if>
2-Sql tags:-
The prefix of this tag is sql.
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 is the list of SQL
JSTL Tags:
Tag
|
Description
|
Creates a simple DataSource suitable
only for prototyping
|
|
Executes the SQL query defined in its
body or through the sql attribute.
|
|
Executes the SQL update defined in its
body or through the sql attribute.
|
|
Sets a parameter in an SQL statement to
the specified value.
|
|
Sets a parameter in an SQL statement to
the specified java.util.Date value.
|
|
Provides nested database action
elements with a shared Connection, set up to execute all statements as one
transaction.
|
3-xml tags:-
Provides Flow control and
transformation etc.
Its url is http://java.sun.com/jsp/jstl/xml
The prefix is x.
The JSTL XML tags provide a
JSP-centric way of creating and manipulating XML documents. Following is the
syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has
custom tags for interacting with XML data. This includes parsing XML,
transforming XML data, and flow control based on XPath expressions.
<%@ taglib prefix="x"
uri="http://java.sun.com/jsp/jstl/xml" %>
Before you proceed with the
examples, you would need to copy following two XML and XPath related libraries
into your <Tomcat Installation Directory>\lib:
Following is the list of XML
JSTL Tags:
Tag
|
Description
|
Like <%= ... >, but for XPath
expressions.
|
|
Use to parse XML data specified either
via an attribute or in the tag body.
|
|
Sets a variable to the value of an
XPath expression.
|
|
Evaluates a test XPath expression and
if it is true, it processes its body. If the test condition is false, the
body is ignored.
|
|
To loop over nodes in an XML document.
|
|
Simple conditional tag that establishes
a context for mutually exclusive conditional operations, marked by
<when> and <otherwise>
|
|
Subtag of <choose> that includes
its body if its expression evalutes to 'true'
|
|
Subtag of <choose> that follows
<when> tags and runs only if all of the prior conditions evaluated to
'false'
|
|
Applies an XSL transformation on a XML
document
|
|
Use along with the transform tag to set
a parameter in the XSLT stylesheet
|
4-internationalization tags:-
Provides message
formatting,number and date formatting etc. the url for this is
and prefix is fmt.
The JSTL formatting tags are
used to format and display text, the date, the time, and numbers for
internationalized Web sites. Following is the syntax to include Formatting
library in your JSP:
<%@ taglib prefix="fmt"
uri="http://java.sun.com/jsp/jstl/fmt" %>
Following is the list of
Formatting JSTL Tags:
Tag
|
Description
|
To render numerical value with specific
precision or format.
|
|
Parses the string representation of a
number, currency, or percentage.
|
|
Formats a date and/or time using the
supplied styles and pattern
|
|
Parses the string representation of a
date and/or time
|
|
Loads a resource bundle to be used by
its tag body.
|
|
Stores the given locale in the locale
configuration variable.
|
|
Loads a resource bundle and stores it
in the named scoped variable or the bundle configuration variable.
|
|
Specifies the time zone for any time
formatting or parsing actions nested in its body.
|
|
Stores the given time zone in the time
zone configuration variable
|
|
To display an internationalized
message.
|
|
Sets the request character encoding
|
5-Functions tags:-
Provide for String manipulation
and lengthurl of this is http://java.sun.com/jsp/jstl/functions
Its prefix is fn.
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 is the list of JSTL
Functions:
Function
|
Description
|
Tests if an input string contains the
specified substring.
|
|
Tests if an input string contains the
specified substring in a case insensitive way.
|
|
Tests if an input string ends with the
specified suffix.
|
|
Escapes characters that could be
interpreted as XML markup.
|
|
Returns the index withing a string of
the first occurrence of a specified substring.
|
|
Joins all elements of an array into a
string.
|
|
Returns the number of items in a collection,
or the number of characters in a string.
|
|
Returns a string resulting from
replacing in an input string all occurrences with a given string.
|
|
Splits a string into an array of
substrings.
|
|
Tests if an input string starts with
the specified prefix.
|
|
Returns a subset of a string.
|
|
Returns a subset of a string following
a specific substring.
|
|
Returns a subset of a string before a
specific substring.
|
|
Converts all of the characters of a
string to lower case.
|
|
Converts all of the characters of a
string to upper case.
|
|
Removes white spaces from both ends of
a string.
|
There are 9 implicit objects
that are availabale for all jsp pages.
A list of the 9 implicit
objects are given below:
Object
|
Type
|
out
|
JspWriter
|
request
|
HttpServletRequest
|
response
|
HttpServletResponse
|
config
|
ServletConfig
|
application
|
ServletContext
|
session
|
HttpSession
|
pageContext
|
PageContext
|
Page
|
Object
|
exception
|
Throwable
|
These are the message which
tells to container how to translate a JSP page into the corresponding servlet.
There are three type of
directive:-
Page directive
Include
–--
Taglib
---
1-Page directive:-
Page directive defines the attribute that apply an entire JSP page.
<%@ page
attribute=”value”%>
Like <%@ page
import=”java.util.Date”%>
<%= Today is=new
Date();%>
Attributes of JSP pages are:-
·
import
·
contentType
·
extends
·
info
·
buffer
·
language
·
isELIgnored
·
isThreadSafe
·
autoFlush
·
session
·
pageEncoding
·
errorPage
·
isErrorPage
this is used to include the
contents of any resourcesit may be jsp file,html file or text file,since JSP
page is translated only once so better to use static resources.
<% include
file=”resourcesName”%>
<% include
file=”header.html”%>
Taglib:- The
JavaServer Pages API allows 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
a means for identifying the custom tags in your JSP page.
The taglib directive follows
the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
Where
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 XML equivalent
of the above syntax as follows:
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
Example:
For
example, suppose the custlib tag library contains a tag called hello. If you wanted to use
the hello tag with a prefix of mytag, your
tag would be <mytag:hello> and it will be used in your JSP file as follows:
<%@ taglib uri="http://www.example.com/custlib" prefix="mytag" %>
<html>
<body>
<mytag:hello/>
</body>
</html>
Advantage Of JSTL over JSP scriptlet tags:-
1- Automatic JavaBean Introspection Support
if you consider that
JSTL's expression language handles JavaBean introspection automatically—which
means you don't need to downcast objects you retrieve as scoped attributes—
<% if
((User)session.getAttribute("user")).getName().equals("jheaton")
{ %>
...
<% }
%>
Because
of JSP's automatic support of JavaBean introspection, this block of code
becomes much more simple in JSTL.
<c:if
test="${user.name == 'jheaton'}">
...
<% } %>
Standardized Support for Formatting and I18N
In
proper Web design, JSP pages should be responsible only for the presentation of
data. Two very common components to this presentation are the formatting of
numbers and strings, and internationalization (I18N) support. Prior to JSTL,
there was no official way to support these two features in JSP scriptlet code.
Many companies developed their own sets of objects that could be used to
support multiple languages. Data formatting was handled in a similar fashion
JSP EL(Expression Languange):-
SP 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:-
${expr}
Note :-
When the JSP compiler sees the ${} form in an attribute, it
generates code to evaluate the expression and substitues the value of
expresson.
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.
Advantages of Custom Tags:-
1-Elimenates the need
of scriptlate tags which is considered as bad programming approach.
2-Sepeartion of
business logic from the jsp so tat
it may be easy to maintain.
3-Reusability:-It
makes the possibility to make reusability of business logic.
Syntax of Custom Tag:-
There are two ways to use the custom tags:-
<prefix:tagname
attr1=value1……attr2=value2………attrn=valuen/>
<prefix:tagname
attr1=value1……attr2=value2………attrn=valuen>
Body content
</prefix:tagname>
Example Of Custom
Tag:
For creating the Custom Tag,We need to follow the following
steps:-
1:- Create The tag Handler Class and perform action at the
start or at end of tag.
2-Create The tag library descriptor file and define tags
3-Create the JSP file that uses the Custom Tag defined in
TLD file
UnderStanding The Flow Of Custom Tag in JSP:-
JSP File(Using Tags)è TLD File(Defining Tag name,Tag Handler
Class)è
Tag Handler Class(Business Logic to be Performed)
To create Tag Handler ,here we are
inheriting the TagSupport Class and overriding its method doStartTag().
To Write for JSP We need to use
JspWriter class.
SnapShot of Source
code:-
MyTagHandler.java
package com.jenesys.jsp_cutomTag;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class CustomTag_In_JSP extends
TagSupport{
public int doStartTag() throws
JspException {
JspWriter out=pageContext.getOut();
try{
out.print(Calendar.getInstance().getTime());
}catch(Exception e){System.out.println(e);}
return SKIP_BODY;
}
}
Tag Library Descriptor contains the
information of tag and tag handler classes.It must be contained in side the
WEB-INF:-
MyTags.tld:-
<?xml version="1.0"
encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun
Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<tag>
<name>today</name>
<tag-class>com.jenesys.jsp_cutomTag.CustomTag_In_JSP</tag-class>
</tag>
</taglib>
Now
create the JSP file it will use the the taglib directive defined in tld file.
index.jsp
<%@ taglib
uri="WEB-INF/mytags.tld" prefix="Jeetendra" %>
Current Date and
Time is: <Jeetendra:today/> //using
custom tag
WEB.xml
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Output:-
Current Date
and Time is: Mon Nov 11 15:04:29 IST 2013 //using custom tag




0 comments:
Post a Comment