JSP (Java server Pages): The
basic aim of JSP is to develop web applications.
A web application is a collection of
HTML programs, DHTML, Java script, VBScript, XML, image, servlets and JSP. We
know that every web application must resides in either web or application
server. Based on the place where the web application programs are running (but
the place where they are resides), the web application programs are divided
into two types they are
i.
Static web resource
programs
ii.
Dynamic web resource
programs
i)
Static web resource
programs: Static web resource programs are those
which are residing in the context of client(browser)
EX
HTML, XML, Java Script etc.,
Static
web resource programs are also known as client side static web resource
technologies. The role of static web resource programs in web application to
carry the client data and handover to server side programs.
ii)
Dynamic web resource
programs: Dynamic web resource programs are those
which are always resides in the server and also running in the context of
server
EX:
Servlet, JSP
Dynamic
web resource programs are also known as server side dynamic web technologies.
The role of dynamic web resource program is collect data from HTML program,
process the data and gives response back.
Conclusion:
In the web application static web
resource programs always provide fixed/static response where as dynamic web
resource programs always gives dynamic response.
Q) Define web application and web site?
A) If an application is in development
mode or in production mode then that application is known as web application.
If the application launched in the server by buying the space in the internet
server then that application is known as website or if the web application is
in running mode then it is known as website.
Limitations of servlets: When
we develop a web application by using servlets, we may get the following
limitations.
i.
Servlets of web application
requires strong knowledge of Java
ii.
Servlets are very
difficult for non Java programmers.
iii.
We know that servlet is
a mixture of both presentation (HTML) and business (Java) logic. At the time of
development of servlet by using it may becomes imbalance because a servlet
developer may be good in presentation logic or business logics but not in both.
iv.
Servlets never provides
separation between clarity between presentation and business logic. So that
servlets are not providing parallel development.
v.
If we do any
modification in a servlet then we need to perform redeployment process that is servlets
modifications require redeployments which is time consuming process.
vi.
If we develop web
application with servlets then it is mandatory for the web application
developer to develop web application configuration file(web.xml)
vii.
Servlets does not
provides any implicit objects(Implicit objects generally provided by containers
during the dynamic program execution)
viii.
Servlets does not
contain a facility called custom tags development.
ix.
Servlets are not
providing global/implicit exception facility.
x.
Servlets are not
containing page compilation concept.
When
servlets are already available in the industry, what is the need of developing
an another technology?
A) When
servlets are released in the industry already there was a server side
technology called ASP(Active server pages) which was developed by Microsoft.
Industry experts appreciated powerful features of servlets but they felt
servlets are hard in learning and hard in implementation. The technology called
ASP appreciated by industry programmers because it is available in the form of
tags. Learning tags based programming is easy and implementing the application
is also easy but industry opinion about the ASP is ASP containing fewer
facilities compared to servlets. Hence after taking the above industry opinion,
SUN Micros system has come up with a technology called JSP with approach of tags
based and inbuilt internal powerful features of servlets. Hence JSP tags based
programming + internal features of servlets. So that each and every JSP program
internally act as a servlet.
Writing a program in JSP is nothing but
with respective tags.
Q) What is the difference between
ASP and JSP?
A) ASP based applications runs only
Microsoft provided Servers(IIS) but they never runs on non Microsoft servers
like Tomcat, GlassFish, Weblogic etc., Hence technology ASP is treated as
Server dependent but server side
technology of JSP runs on each and every operating server irrespective their
vendors hence JSP and whose applications are treated as servers\ side
independent technologies and they full fill the slogan called WODA(Write once
and deploy any where)
Advantages of JSP: If
we develop any web application with a server side technology called JSP we get the
following benefits.
1. Learning
JSP is does not requires strong knowledge of Java because writing a program in
JSP is nothing but making use of tags.
2. JSP
programming is easy to learn and easy to implement for non Java programmers.
JSP programming environment provides the separation between business and
presentation logic.
3. JSP
programming environment provides Parallel development of web
application. JSP programming contains implicit objects.
4. JSP
programming eliminates repeated redeployment problems that is as and when we
modify the JSP, we need to save the JSP and makes a request and automatically
it is taken care by container(JSP execution environment).
5. JSP
provides optional mechanism in configuring web application file(web.xml).
6. JSP
environment provides implicit/global exception handling mechanism.
7. JSP
programming provides an additional concept called custom tags development.
8. JSP
programming environment provides page compilation automatically.
JSP technology specification: JSP
is one of the complementary technology for servlets with the aim of developing
strong web applications.
1. The
meaning of technology is that technology specification released by original
vendor and technology specification implementation done by third part software
vendors like Database vendors, server vendors etc.,
2. Since
JSP is the server side technology, it is also having a specification released
by SUN Micro system and it is implemented by third party server vendors like
Tomcat(Apache Jakarta foundation), Web logic(Oracle corporation)
Glassfish(oracle corporation) etc.,
3. In the programming point of view specification
is nothing but set of rules given in the form of abstract methods and present
in interfaces so for the JSP specification SUN Micro system has developed lot
of interfaces with the collection of abstract methods and these interfaces are
developed by server vendors in the form of classes and released in the form of
tags.
4. Hence all the classes which are developed by
various server vendors are common for al server softwares and they are available
to the programmers in the form of jar files. For example on Tomcat server JSP
related API is available in the form of jsp-api.jar and this jar file found in
C:/Tomcat/common/jsp/lib folder.
5. Similarly the JSP api is available in web logic
in the form of weblogic.jar. The JSP technology released by SUN Microsystem in
the month of September 1999 with JSP 1.0 version and later in the December 1999
JSP technology is enhanced to the industry on name JSP.
Phases in JSP: Whenever
we develop a web application with JSP the JSP programmers will undergoes three
types of phases they are
1. Translation
Phase
2. Compilation
Phase
3. Execution
Phase
1. Translation
Phase: The process of converting the .jsp
program into .java program(equivalent to servlet) is known as Translation
phase. In other words .jsp program is converted into .java program.
EX:
first.jsp converted into first-jsp.java.
first-jsp.java is an equivalent servlet of first.jsp which is prepared by the
container.
Translation
phase will be preformed by the container in the following occasions.
a) Making
a first request to .jsp program.
b) Making
a request to the modified JSP page.
Note: The
process of converting one technology program (.jsp) into another
technology(.java) is also known as automatic page compilation.
2. Compilation
Phase: The process of converting the .java
program into .class file is known as compilation phase for example
first-jsp.java is automatically compiled into first-jsp.class by the container.
Compilation phase will be performed by the container in the following occasions.
a) Making a first request to the JSP page
b) Making another request to the modified JSP
page.
3. Execution
Phase: Execution phase is nothing but
processing the client request and gives response back to the client. During
execution phase the container will perform following operations.
i.
Container loads
equivalent servlet of JSP in its memory.
ii.
Container instantiates
an object of equivalent servlet of JSP.
iii.
Container will perform initialization
process of equivalent servlet of JSP
iv.
Container will perform
request processing process/ service process and gives response back to client.
The above i, ii, iii, iv steps of execution phase will be performed by the
container in the case of first request to JSP or request to modified JSP from
second to further subsequent requests, the container will perform step-iv of
execution phase. The following diagram gives the diagrammatic representation of
JSP.
JSP
Phases
No
of
Results
|
Transition
Phase
|
Compilation
Phase
|
Executing
of servlet loading into server
|
Instantiation
of equivalent servlet
|
Initialization
equivalent servlet to JSP
|
Request
processing equivalent servlet of JSP
|
First Request
Request1
|
ü
|
ü
|
ü
|
ü
|
ü
|
ü
|
Request2
|
O
|
O
|
O
|
O
|
O
|
O
|
Modified
JSP
Request3
|
ü
|
ü
|
ü
|
ü
|
ü
|
ü
|
Request4
|
O
|
O
|
O
|
O
|
O
|
ü
|
Server
Restart
Request5
|
O
|
O
|
ü
|
ü
|
ü
|
ü
|
Request6
|
O
|
O
|
O
|
O
|
O
|
ü
|
In order to deal with JSP programming we
need to deal with the following packages.
i.
javax.servlet.jsp.*
ii.
javax.servlet.jsp.tagext. (extensions.custome tags)
iii.
javax.servlet.jspel.*
(el-expression language)
the above packages are coming along with
the server softwares but not form jdk.
Preparation of staging directory/
documentation software: SUN Microsystem has
prescribed te following steps for preparation of staging directory to execute
the web applications in the context of any srver.
i.
SRC
|
ii.
Create an another
directory/folder known as
(optional) in the staging directory.
SRC
|
iii.
WEB-INF
|
iv.
W
EB-INF
|
v.
W
EB-INF
|
classes
|
vi.
Create a fixed in in
vii.
Create an another fixed
lib which will contain *.jar files and place it into
hence staging directory name can be changable
but the other sub folder names can’t be change and whose locations are fixed.
Staging
directory name
|
SRC
|
.html
.js
..java
.jsp
WEB-INF
|
classes
|
lib
|
.class
*.jar
P) Write a JSP program which will
display Hello JSP world.
first
|
first.jsp
WEB-INF
|
web.xml
classes
|
first.class
first.jsp
<h2> hello
jsp world</h2>
<h2> I am
from Sathya institute</h2>
web.xml
<web-app>
<servlet-name> first
</servlet-name>
<jsp-file>first</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/sat.com</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
The
above application can be deployed in any server by using three approaches they
are
i.
Hard deployment
ii.
Console based
deployment
iii.
Tool based
deployment(IDE)
i.
Hard Deployment: In
the hard deployment we copy the web application name/staging directory name
from our local directory and paste it into webapps folder of Tomcat server
later makes a request to the web application. Open the browser pass the
following url http://loalhost:8080/first/first.jsp.
We can give the result of first.jsp. In
order to see the eqivalant result of the JSP we can found in the following
location.
C:/Tomcat
5.5/word/Catalina/localhost/first/org/apache/jsp
Here Catalina
represents servlet container. First represents name of the web
application/war file name (staging directory) org/apache/jsp represents name of
the package where which contains equivalent servlet of the JSP placed.
First.jsp equivalent name of the servlet is First.java
Console
based deployment: In the console based
deployment the web application developer must generate .war file for web
components like Servlets and JSP.
Syntax
for creating war file: jar cfv iss.war WEB-INF
*.jsp *html
Here jar s
developed by SUN Micro system and available in jdk1.5/bin folder. It is used
generating .war file, .jar file, .ear file
etc.,
cà
create fà file và
verboros
Here Verboros
represents ackground details about what files are placing in war file, their
original size, compression size and %of compression etc.,
EX:
jar cfb fs.war WEB-INF *.jsp
Fs.war contains
First.jsp
Web.xml
Etc.,
Packaging:
The mechanism of placing *.jsp, *.html,
all files and sub directories of WEB-INF folder in a single file is called
packaging.
Life
cycle methods of servlets: We know that JSP is one
of the server side technology and their applications are running in the context
of server. Any kind of applications running in the context of server, it
contains Life cycle methods(Loop back methods). JSP contains three life cycle
methods they are 1. public void jspInit()
2. public void
_jspService(HttpServletRequest,HttpServiceResponse) throws ServletExceptiopn,
IOException
3. public void
jspDestroy()
1.
public void jspInit(): It is one of the
predefined null body method. This method will be called by the container only
once when we make a first Request to the JSP program since this method is
calling only once by the container, it is highly recommended for the web
applicaton developer to write one time operations like opening files in read
mode or write mode obtaining the Database connection, initialization of
parameters etc., In general jspInit() contains block of statements which will
always gives resource gathering logic
2.
public void _jspService():
i.
After executing
jspInit() at the time of making first request, container will automatically
calls _jspService(-,-) from second request to further sub sequent request
container will call only _jspService(-,-)
ii.
Hence this method will
be called by the container each and every time whenever we make a request to
the jsp program. Since this method is calling each and every time it is
supposed to contain repeated operations like reading the records from the file,
reading the records from the Database etc.,
iii.
in general this method
always contains block of statements
which will perform Request Processing logic _jspService(-,-) is not posble to
override by programmer and this method is always override by JSP container.
Note:
As a JSP programmer what ever the
request processing logic will use writing in the form of tags that logic will
be automatically placed by the container with in the body of _jspService(-,-)
Public
void jspDestory():
1. It is one of the
predefined method defined with null body.
2. This
method will be called by the container automatically when the web application
developer removes the war file name or web application from the context of
server. Since this method is called when the web application was removed from
the context of server, It is highly recommended to close the resources like
files, Database connections etc., Hence JPS Destroy() always contains the block
of statements which will perform Resource relinquishing logic.
Note:
All the above life cycle methods of JSP
are internally calling by the container through the Life cycle methods of
Servlet. That is init(-) is automatically calling jspInit(), service(-,-) is
automatically calling _jspService(-), Destroy() automatically calling by
_jspDestroy(). So in the JSP life cycle methods it is always recommended to
override jspInit() and jspDestroy() but not recommended to override
_jspService(-,-).
Sun Micro system
has prescribed the following standard format for development of JSP programs.
If we write any
program in JSP then it must be saved on same file name with an extension .jsp
writing a program in JSP is nothing but making use of HTML tags for
presentation logic and JSP tags for request processing logic. Along with HTML
tags And JSP tags we may also use normal text and template text. Template text
is a collection of normal with HTML tags. If a client makes a request to the
JSP the client receives static response from HTML tags and whose related source
code can be viewed in the browser(right click on browser and select view
source) where as client receives dynamic response from JSP tags and whose
source code can’t be viewed in browser.
Q) What are the difference between HTML tags and JSP tags?
HTML
Tags
|
JSP Tags
|
1.
HTML tags are developed by w3c
organization.
2.
HTML tags are always used for the
development of static web resource programs.
3.
HTML tags always generated static
response.
4.
When static response is generated, the
client side programmer can view HTML tags in browser window.
5.
HTML tags are not case sensitive.
6.
In most of HTML tags, following the
order of attributes is optional.
7.
With HTML tags no more custom tags can
be developed.
|
1.
JSP tags are developed by SUN Micro
system and practically implemented by Server vendors.
2.
JSP tags are always used for the
development of dynamic web resource programs.
3.
JSP tags always generate dynamic
response.
4.
When dynamic response is generated a
client side programmer can’t view JSP tags in the browser window.
5.
JSP tags are case sensitive.
6.
All the JSP tags related attributes
and their order is mandatory to follow. Otherwise get translation problem.
7.
With JSP tags one can develop custom
tags.
|
Note: A HTML program
can contain a JSP program. That is a JSP program can be embedded within HTML
tags and it is opposite in the case of servlets.
Implicit objects in JSP:
i.
In JSP programming we
can have two types of Objects they are explicit objects and Implicit Objects.
ii.
Explicit
Objects are those which are created by Java
programmer with respect to some classes/interfaces either directly or
indirectly during the request processing logic.
EX: String
s=new String(“java”)
Runnable
r=new th1()
Here r and s are called explicit objects.
Implicit Objects: Implicit
objects are those which are created by server during JSP program is under
execution the following table gives nine implicit objects whose corresponding
class name/interface name.
Implicit
Object name
|
Instantiated
by
|
Request
response
out
config
application
session
exception
page
pagecontext
|
javax.servlet.http.HttpServletRequest
javax.servlet.http.HttpServletResponse
javax.servlet.jsp.JspWriter
javax.servlet.ServletConfig
javax.servlet.ServletContext
javax.servlet.http.HttpSession
javax.lang.Throwable
like java.lang.Object
javax.servlet.jsp.PageContext
|
All the above implicit variables are
available to every JPS program except Exception.
The object Exception will be visible if any Exception occurs in the JSP
program.
JSP Tags: JSP
tags are classified into four types for developing web applications they are
i.
Scripting elements
ii.
JSP commenting tags
iii.
JSP directives
iv.
JSP standard actions
Scripting Elements: The
basic aim of scripting elements is to develop preliminary programming in JSP.
Preliminary programming programming of JP requires how to declare variables,
how to define methods, how to form expressions and where to write business
logic code.
Scripting
elements are classified into three types
a)
Declaration tags
b)
Expression tafs
c)
Scriplets
a) Declaration tag: Declaration
tag is used for three purposes they are
1.
Defining the variables
2.
Defining the user
defined methods.
3.
Overriding the JSP life
cycle methods except _jspService(-,-)
Syntax1 (Standard
Syntax)
<%!
Variable declaration definition of user defined method overriding JSP life
cycle methods%>
JPS XML based:
<JSP:
declaration>
Variable
declaration definition of user defined methods overriding JSP life cycle
methods %>
In single JSP program one can write either
one or more number of declaration tags. Whatever the details we are written declaration
tag of JSP program they are becoming member properties in the equivalent
servlet of the JSP.
Declare
the variables a, b, c and places 10,20,30 respectively
<%!
int
a=10, b=20, c=30 %>
(or)
<!
int a=10
int
b=20
int
c=30%>
Al
the above three variables of declaration tags will become data members in the
equivalent servlets in JSP.
EX2: Define
the user defined methods
<% void sum()
{
int
a=10;
int
b=20;
---------
----------
}
%>
<%JSP:declaration
Void
sum()
{
C=a+b;
}
%>
The
above method SUM will become member method in the equivalent servlet of the
JSP.
Override jspInit() for
obtaining the database connection:
<%!
Public void jspInit()
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection
con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:orcl,”scott”,”tiger”);
Expression
Tag: Expression tag is always used fro
writing request processing logic which we are giving as a response back to
client.
Syn1:
(Standard syntax)
<%
=Java expressions)
Syn2: (XML based)
<JSP:expression>
Whatever
the Java expressions we are writing in the expression tag which will become as
a part of out.println and it will be placed with in _jspService(-,-).
The Java expression tag
should not be terminated by semicolon. If it will terminate by semicolon we
will get compile time error.
EX: <%!
Int a=10;
Int b=20; %>
sum=<%=a+b%> à (out.println(a+b))
sum=<%=a+b;%> à Invalid(Compile time error)
EX2:
<%!
int a=10;
int b=20;
%>
<%!
int sum()
{
return(a+b);
}
%>
As a part of <expression> one can call those method which are writing
sum values but one shouldn’t call those method which are writing void as a
return type.
P) Develop a web application which will print hit
ration of a website? Or write a JSP program which will print number of times a
web page is accessed?
/Hit.jsp
|
Hit.jsp
Hit1.jsp
WEB-INF
|
classes
|
Hit.jsp:
<%! int ctr=0;%>
<h1> number of hits<%=++ctr%></h1>Hit1.jsp:
Hit1.jsp
<%!int ctr=0;%>
<%!
int increment()
{
return(++ctr);
}
%>
<h1>number of hits=<%=increment()%></h1>
Web.xml:
<web-app>
</web-app>
P) Write a JSP program which will display current
data and time of the System.
Date1.jsp:
<h1>current data and time=<%=new
java.util.Date()%></h1>
Date2.jsp:
<%!String getSysDate()
{
java.util.Date d=new
java.util.Date();
String sd=d.toString();
return(sd);
}
%>
<h1>current Date and time is <%=getSysDate()%></h1>
}
Scriptlets: Scriptlets basic aim is to contain a pure Java code
which always provides request processing logic. Whatever the Java code we write
as a part of Scriptlet which is placed in _jspService(-,0) of equivalent
servlet one can write java expressions, one can call Java methods which are
returning a value and not returning a value and not returning value but one
should not write methods deifications as a part of scriptlets because nested
methods concept is not possible that is if we define any method as a part of
scriptlet then it becomes nested
method. As a part of
_jspService(-,-) which is not possible because the languages like C,C++, Java
never allows nested method concept.
Syntax: “4,5,6”
<% pure java code%>
Syntax2:
<JSP:Scriptlet> pure java code</JSP:scriptlet>
<%! Int a=10; %>
<%! Void print()
{
out.println(“value of a=”+a)
}
/>
Or
<%print()%>
<%print();%> (invalid)
P) Print
1 to 10 numbers in the browser window
EX:
<h1> The First Ten Numbers are</h1>
<%for(int i=0;i<=10;i++)
{%>
<%out.println("<h1>"+i+"</h1>");
}
%>
Q) In how many ways one can send
input the dynamic web resource program(either to servlet or JSP)
A) One can send and input to the servlet or JSP in three ways
i) Through form based requests.
ii) Through Query String based requests.
iii) Through hyperlink based requests.
P) Write a scriptlet which will calculate factorial
of a given number by passing value of n through Query String
<%
int num=Integer.parseInt(request.getParameter("num"));
%>
<%!
int factorial(int n)
{
if (n == 1) {
return n;
}
else {
return n * factorial(n
- 1);
}
}
%>
<%
out.println(" <h1>
The factorial of " +num+" is : " +
factorial(num)+"</h1>");
%>
OUTPUT
http://172.16.0.7:7001/Facts/Factorial.jsp?num=4 (for Weblogic) (or)
http://localhost:8080/Factorial/Factorial.jsp?num=54
(for Glass Fish)
The factorial of 4 is : 24
Equivalent Servlet of JSP available in NetBeans
project in following location
For source code of Date and Date1 please go NetBeans(JSP)\DateAndTime\build\web
D:\NetBeans(JSP)\PrintTennumbers\build\generated\src\org\apache\jsp
Establishing the communication between HTML and JSP:
We know that a
web application is a collection of static web resource programs and dynamic web
resource programs. Static web resource programs accepts client requests and
handover to serverside programs. Dynamic web resource programs are those which
will collect the data from the static web resource programs and gives the
response back to client. In web application development user input is accepted
in the form of GUI applications which are developed by making use of the
following approaches.
a) By using AWT/SWINGS/Applets
b) By using HTML controls
If we develop any GUI
application by using AWT/SWING/Applets then the programmer requires strong
knowledge of Java and it takes more application development time. To avoid this
complexity we require HTML controls. The usage of HTML controls are easy to
implement and takes less time hence in the most of websites the recommended
controls are HTML controls. It is highly desirable in the web projects. User
input is collected in HTML
Forms and user input
is evaluated in the form of either Servlet or JSP. In this context it is highly
desirable to establish the communication between HTML form and JSP.
Syntax to establishing the communication between
HTML and JSP:
Form controls:
<body>
<form action=”url pattern of jsp” method=”get/post”>
</form>
</body>
When we are writing <form> we must ensure that all the form
controls must be incorporated with in the <form> otherwise form data may
not be sending to the serverside program. The attribute action represents name
of the dynamic destination program either servlet name or JSP. In the case of
JSP we need to specify either url pattern of JSP or JSP file name. Method
represents either get() or post(). If method=”get” then form data subit into
the JSP as a part
of url. If we use
the method post then the form data/client data send to the serverside program
as a part of Request
body. Ensure that
the <form> must be written within the <body>
EX: <form action=”student.jsp” method=”post”>
----------
-----------
</form>
Here if we are not using method attribute then http takes get() as a
default method.
P) Write a web application which contains one HTML
program and one JSP. Html Program will accept student details and JSP program
will receive the values from HTML and display those
StudentDetails
|
Student.html
Show.jsp
WEB-INF
|
web.xml
classes
StudentDetails(WebLogic),
StudentDetails Projects
in NetBeans(JSP) Folder
JSP
Directive tags: The
purpose of directive tags is to supply or provides external or additional
information to the current JSP program. JSP directive tags related information
utilized by the JSP container during the JSP program execution, supplying the
additional information or external information to the JSP pages represents
importing the packages o fJSP including the static web resource programs
content and getting web.xml information at the time of development of custom
tag. JSP directive tags are classified into three types they are
i) Page directives
ii) Include directives
iii) Taglib directives
i)
Page directives: The purpose of Page directrive is to provide external or additional
information like importing the packages, specifying the content type, utilizing
the current JSP page only.
Syn:
<%@page
attribute name1=val1,attribute name2=val2
-------------
-------------
Attribute namen=valn%>
Page is one of the directive
tag Attribute1, Attribute2,----------,Attributen represents name of the page
directive attributes.
1. Val1, val2, -----,valn represents the values for attributes of page
directive by the convention of page directive it is highly recommended to write
as a first statements in the current JSP program. That is one JSP program may
contain many page directives an dall of htem must be written as first
statements in the cureent JSP program.
2. All the attribute names must be unique except import attribute that
means all the attribute names to be specified only one but import attribute can
be specified multiple times for importing multiple packages.
Page directive attributes divided into 12 types those are
1. import
2. ContentType
3. extends
4.errorPage
5. isErrorPage
6. autoFlush
7. buffer
8. sesson
9. isThreadSafe
10. isELIgnore
11. language
1. import: This attribute is used to for importing either
predefined packages of JSE or third party packages(Oracle corporation or IBM
etc) or user defined packages to the current JSP program.
Syn:
<%@page
import=”packname1=val1 packname2=val2----packnamen=valn%>
(or)
<%@page input=”packname1=val1”
Import =”packname2”=”val2”
--------------
--------------
Import=packnamen=valn”%>
In the above syntax the tag
values can be separated by coma or separated by space.
Date.jsp
Current date and time=<%=new Date()%>
In this Date.jsp program
java.util.* package is treated as external information.
2.
ContentType: The purpose
of this attribute is to specify the MIME Type. MIME Type always makes us to
understand the type of response like word document, except document, audio, pdf formats etc., The default value of MIME type
in JSP or content type in JSP is text/html programmatically the type of MIME
Syn:
<%@pageContentType=”MIME
Type”>
EX:
<%@page
contentType=”application/msword”
------------
------------ >
3.
extends: We know that
extends is inheriting the features of base class to derived class and base
interfaces to derived interfaces. In the case of JSP programming the keyword
extends is not available at programmer level because if the JSP programmer
specifies ame class name to extends attribute then the equivalent servlet of
the JSP related class is suppose to extends our class which is illegal the equivalent
servlet of this JSP related class is already extending http servlet. Hence the
extends attribute at server developer levels only
<%@page extends=fully Qualified name of the class%>
4.errorPage
5.
isErrorPage The basic aim of the above tags is to achieve
implicit or automatic Exception Handling fecility.
Syn:
<%@Page isErrorPage=”true||false” errorPage=”path
of error page%”>
The default value of
isErrorPage is true that is in the same JSP page we need to write try and catch
blocks for dealing with exceptions and it leads to a lengthy process for
utilizing try and catch blocks in the all JSP programs to avoid that it highly
recommended to write a separate JSP program for dealing with all the Exceptions
of the JSP programs. To do this pass the value false for isErrorPage
immediately specifies the name of the JSP program where exceptions are handled.
errorPage attribute always takes name of the program where exceptions are
handled. Hence if isError=false then use error page if isErrorPage value is
true we should not use error page.
x.jsp y.jsp
<%@page isErrorPage=”false” errorPage=”err.jsp”%>
err.jsp
Name of the exception=<%=exception%>
(or)
Name of msg=<%exception.getMessage()%>
6. autoFlush
7.
buffer
autoFlush is one
of the page directrive attribute which will take either true or false if
autoFlush is true then the container understands that there response object
will receive the data with 8 kb buffer or out.close is taken place that is the
data of the response object will be flushed or rendered or gives to the client
either 8KB buffer is full or out.close is taken place. In JSP programming
environment default buffer size is 8KB and it can be increased or specified
with the multiples of 2.
<%@page
autoFlush=”true” buffer=”name”> //invalid
<%@page
autoFlush=”true”%> //valid
IF autoFlush is false then container
understand the response data will be rendered or flushed to the client until
specified buffer size is filled or out.close is taken place when we use
autoFlush=”false” then it is mandatory to specify buffer size.
EX:
<%page autoFlush=”false”
buffer=16kb>
<%page
autoFlush=”false”> //invalid
Syntax:
<%@page
autoFlush=”true||false” buffer=”name”||8kb||6kb%”>
8.
sesson: We know that http protocol is one of the
stateless protocol it maintains identity of client for a limited period of
time. The real world servers like Tomcat, weblogic etc., will follow the http
protocol so that these servers are known as stateless servers. Stateless
servers remembers previous requests and response details this process leads the
identification problems regarding multiple requests of the same user in order
to avoid this problem all the server side technologies provides session
tracking API(Cookies, Http Sessions, Hidden Form Fields, url rewriting). In JSP
environment JSP containers are by default having Http Sessions as a default
session tracking mechanism. To use it we use session attribute of page
directive session attribute takes two valus they are true or false.
<%@page
session=”true||false”%>
Case(i):
If session=true and client makes first
request.
A) IF Container
will create session first time
Case(ii):
If session=”true” and client makes
second and further subsequent requests then
A) session will
be continued by checking whether it is created or not.
Case(iii):
If session=”false” and client makes
first request then
A) JSP container
never creates a session.
Caseiv):
If session=”fase” and client makes
second and further subsequent requests then
A) session will
be continued without checking whether it is created or not.
Conclusion:
By observing all the above cases it is
highly recommended to the JSP programmer to write the session attribute value
always true for continueing the session always. So that session data can be
carried from first request to second and further subsequent requests by making
use of session implicit variable.
Q) What is the
difference between sessionAttribute of a page and sessionImplicitVariable?
A)
sessionAttribute of page will create the session and continue the session
during client request and response model.
Session Implicit
variable will carry the session data(first request, second and further
subsequent requests to last request). In order to place the session and
retrieve the values from the session we use following methods which are present
in javax.servlet.http.HttpSession
i) public void
putValue(String, Object) (depreciated that means not in use right now)
ii) public void
setAttribute(String, Object)
iii) public
Object getValue(String) (depreciated)
iv) public
Object getAttribute(String)
The above I,ii methods are used for
placing the values in the form of (key, value) here key represents session
variable name(String parameter) and value represents session variable
values(Object).
Methods iii and
iv are used for retrieving the values from session by passing session variable
name.
9.
isThreadSafe
Syn:
<%@isThreadSafe=”true||false”>
isThreaedSafe is
one of the page directrive tag and it takes either true or false the default
value of the isThreadSafe=”true”. If isThreadSafe=”true” then we get
a) Inbuilt
synchronization concept
b) Container
provides concurrent access
If isThreadSafe=”false” then
a) container
won’t provide inbult synchronization mechanism
b) container
provides only sequential access.
Q)
Define static form and dynamic form?
A) A static form
is one which contains HTML form controls and it gives fixed content and it must
be saved on some file name with .html
extendsion. A dynamic form is one which is always containing html form form
controls and it gives dynamic context and it must be saved on some file name
either with and extension .java(servlet) or with extension .jsp(program)
Info:
Info is one of the page directive tag
which always meant for describing or expressing the purpose of a particular JSP
page which is nothing but writing a comment about the JSP.
Syn:
<%@page info=”comment” about jsp%>
EX:
x.jsp
<%@page
info=”this JSP communicates with Database”%>
In the equivalent servlet of
JSP(x_jsp.java) the info value is available as a part of body of getServletInfo
method.
10.
Language: The purpose of language attribute is to
make the container to understand about type of language used by the programmer
for writing scriptlets, expressions and declarations the default value of
language attribute is Java when we are writing client side validations by using
Java script then the value of the language attribute is Javascript. In the near
future or in the upcoming versions of the JSP the language attribute may
contain other languages like COBOL, .NET etc.,
EX:
x.jsp
<%page
language=”java”%>
-------
--------
Java loading
standards (default)
y.jsp:
<%page
language=javascript”%>
-----------
----------
-----------
%>
Note:
Java and Javascript is no way related
but javascript can be used for client
side validations. The vendor of Javascript is Netscape, vendor of Java is SUN Microsystem.
11.
isELIgnore:
P)
Write a JSP program which illustrate the concept of errorPage and isErrorPage
x.jsp
<%@page isErrorPage="false"
errorPage="ErrorPage.jsp"%>
<h1>Result =<%=30/0%></h1>
This program makes us to understand if any
exception occurs in this program, that exception will not be handled by current
JSP program but it will be transferring that exception to some other JSP
program where exception is handled.
ErrorPage
|
<%@page isErrorPage="true"%>
<h1> x.jsp
Exception
is<%=exception%></h1> ErorPage.jsp
WEB-INF
|
<h1>Generated .......
classes
|
P)
Write a JSP program which will illustrate the life cycle methods of JSP and
import statement.
For ODBC connection for Oracle Please refer ODBC for Oracle
document.
(int eh case of
type4 driver we have to keep lib folder(for only Tomcat). In this folder we
have to keep clases111.jar, ojdbc14.jar
If we have
multiple JSPs which are dealing with multiple databases then whose
corresponding jar files can be supplied in two ways they are by creating lib
folder individually in each JSP and placing corresponding jar fies in the lib
folder(not recommended this is classical approach). If which ever server we are
deploying our JSPs which are communicating with Database whose corresponding
files must be placed in lib folder of server softwares. For example in the case
of Tomcat we can place Oracle related jar files(classes111.jar). in either
Tomcat 5.shared\lib\ folder or Tomcat5.5\commond\lib folder
Int eh case of weblogic server we can
place in C:\bea\weblogic90\server\lib folder.
Note:
We shouldn’t declare any declarations
in scriptlet tag.
P)
Write a web application which illustrates the concept of session.
SessionExample
|
ses1.jsp
ses2.jsp
ses3.jsp
WEB-INF
|
classes
|
Enter
First No:
Enter
Second No:
Sum=15
Mul=50
Click
here to get Division
Division = 2
|
Ses1.jsp
Ses2.jsp
Ses3.jsp
Ses4.jsp
|
mul
|
1
|
5
|
sum
|
13
|
9
|
17
|
3
|
7
|
11
|
15
|
2
|
4
|
6
|
8
|
10
|
12
|
14
|
16
|
Include
Directives: This directive always include
static web resource programs during the transaction phase. In other words
whatever the static web resource name we specify which will directly placed in
the equivalent servlet of the JSP
Syn:
<%@include file=”name of the static
web resource program%>
Here include is one of the directive tag
and it supplies external information regarding static web resource program to
the current JSP.
Here file is an attribute of include
directive which will take the name of the static web resource program.
Conclusion:
include directive tag deals with only
static web resource programs but never deals with dynamic web resource programs
at any point of time one can use multiple includes in the current JSP page.
x.jsp:
<% Date d=new
Date();
Out.println(d);
%>
<@include
file=”footer.html”>
P)
Develop a web application which illustrates the concept of User authentication
that is check the user name and password.
Q)
How do you deal with Cookies in JSP related web applications?
A) In order to
deal with Cookies in the JSP application development, a JSP programmer we
follow the following tags.
i) Create the
number of Cookies depends on number of requested values by the client by making
use of Cookies class.
ii) Add the
Cookie class objects to response object because Cookies are created at server
side and residing at client (browser)
ii) Get the
Cookies from the current request object of current JSP.
Conclusion:
Compared to Cookies, sessions are having
many advantages so that it is highly recommended to follow sessions only.
Model 1 web application: All the
previous JSP applications contains collection of HTML Programs and JSP programs
this type of modeling of web application is known as model 1 web
application.
In
other words model 1 web application contains two types of programs they are
i) html programs
ii) JSP/servlet
programs
The limitation of model 1 application is
there is separation between presentation logic and business logic and it gives
only sequential development but not parallel development. In order to achieve
parallel development by separating presentation logic and business logic it is
highly recommended to use enhanced model 1. The following diagram gives
view about the data flow or request and response. A model in enhanced model 1
HTML Programs
Java
JSPs Beans
|
Database sw
|
2
|
3
|
5
|
9
|
4
|
11
|
13
|
1
|
6
|
8
|
10
|
12
|
Enhanced Model-1
7
|
According to the
industry standards Java beans must always contains business logic and
persistency logic. Where as JSPs must contain only presentation logic and no
Java code that is JSP must be developed without scriptlets.
In this approach one can develop JSP
related web applications parallel.
Java
Beans in JSP: A Java Bean is one of the reusable
component which is used either in JSP or in servlet
(or)
A Java Bean is one of the Java class which
contains both business logic and persistence logic. Since Java Bean class is
reusable so that it must be always placed in package.
Teps/Guidelines
for developing Java Bean: According to industry
standards to developing Java Bean class, we have the standard guidelines they
are
1.
Choose an appropriate
package name for placing Java Bean and it can be access anywhere else(either in
JSP or in servlet) and ensure package statement must be first executable
statement.
2.
Choose an appropriate
user defined class and this class will be called as Java Bean class and ensure whose
modifier must be public.
3.
Each and every class
which is selected step-2(Java Bean class) is highly recommended to implement
java.io.serializable.
4.
Choose the suitable
data members in Java Bean class.
5.
Each and every Java
Bean class must contain explicit public default constructor( because when we
use Java Bean class as a part of JSP or servlet) and whose object can be
created by the container by making use of explicit provided default
constructor.
6.
Define set of setXxx
methods for each and every data members
of Java Bean class(We know that setXxx methods) sets the values for Java Bean
class object which are received from the client side application.
7.
Define set of getXxx
methods for each and every data members of Java Bean class( we know that
getXxx) methods obtains the values from Java Bean class object and gives
response back to client through either JSP or Servlet. The file naming
convension in Java Beans is that what ever the Java Bean class we are placing
in the package, the class name must be given as a file name with an extension
.java
Define
a Java Bean class for Employee
//Employee.java
import
org.sathya
public class
Employee implements Serializable
{
//declare Bean Properties
//Declare member variables
private int eid;
private String fname,lname,email;
//write setXxx(-) and getXxx()
public void setEid(int eid)
{
this.eid=eid;
}
public int getEid()
{
return eid;
}
public void setFname(String fname)
{
this.fname=fname;
}
public String getFname()
{
return fname;
}
public void setLname(String lname)
{
this.lname=lname;
}
public String getLname()
{
return lname;
}
public void setEmail(String email)
{
this.email=email;
}
public String getEmail()
{
return email;
}
}
Compile the
above program
Javac –d .
Employee.java
Ensure org must
be created as a directory and sathya must be created as a subdirectory,
Employee.java program must be compiled, Employee.class file must be generated
and it must be automatically copied into org.sathya package.
Hence each and every object of Java bean
class is an Object of java.lang.Object because every Java Bean class is a sub
class of java.lang.Object.
Properties
of Java Bean Class: Java Beans contains
three properties they are
i. Simple
property
ii. Boolean
Property
iii. Indexed
property
i.
Simple property: Simple property of Java
Bean class always takes single value and returns single value.
EX:
Employee.java (see above page for
example).
ii.
Boolean property: Boolean property of
Java Bean class takes Boolean parameters and returns boolean values.
EX:
public class login
{
String uname;
String pwd;
------------- //set methods
------------- //get methods
public Boolean
isLogin()
{
if(uname.equals(“sathya”)&&pwd.equals(“test”))
retrun true;
else
return false
}
Indexed
properties: Indexed property of Java Bean
always takes arrays as parameters and returns arrays as return types.
EX:
public class Sathya
{
String courses
[];
public void
setCourses(String courses)
{
this.course=course
}
public String[]
getCourses()
{
return courses;
}
}
Note:
If any method of Java Bean operates on
indexes of the Arrays then such methods also satisfies indexed property.
JSP
Standard actions: JSP Standard actions
provide external information to the JSP at run time.
The external information of standard
actions represents the usage of Java Beans and servlets/JSPs as a part of JSP
program at run time.
Standard actions of JSP always participate
at execution time and whose response is mixed with current JSP response.
Standard actions
in JSP are
I.
<JSP:UseBean----/>
2.
<JSP:setProperty----/>
3.
<JSP:getProperty-----/>
4.
<JSP:forward------/>
5.
<JSP:include ------/>
I.
<JSP:UseBean----/>: The purpose of this tag
is to initiate Java Bean class object as a part of JSP program.
i. In the above
tag JSP represents prefix/short name.
ii. UseBean represents
a tag name
iii. UseBean tag
contains the following attributes those are id, class, Bean name, type and
scope
id:
This attribute represents object name of
the Java Bean class.
Class:
This attribute represents fully
qualified name of Java Bean class.
Bean
Name: It represents alias/alternative name
given to the Java Bean class.
Type:
This attribute represents base interface
name of Java Bean class and container will create an object of Java Bean class
indirectly (dynamic binfing).
Scope:
This attribute represents the
availability of Java Bean class object name. Scop attribute takes four values
or Java Bean class object will have four types of scopes they are
a)
page: If scope=page then the data of Java Bean
is available to the current JSP page only. Once the response of current JSP
page is completed, an object of Java Bean class will be destroyed by the
container.
b)
request: If scope=request then the data of Java
Bean class object is available to those JSPs which are participating in JSP
chaining once the JSP chaining gives the response back to the client then
container will automatically destroy the Java Bean class object. The number of
JSP programs participated in processing single request of the user is known as JSP
chaining.
c)
session: If scope=session then the data of Java
Bean class object can be available all those JSP programs which are
participating JSP session tracking. One the session is completed, automatically
container will destroy an object of Java Bean class
In request scope their exists single
request and response objects where as in session scope their exists
multiple requests and responses
d.
scope: scope=application
If
scope=application then the data of Java Bean class object can be access
throughout the entire web application in all the JSPs. We know that application
object exists one per web application. Application object will be created
when web application is deployed and it will be removed when the web
application is un deployed from the server so Java Bean class object data available
from deployment time to until we un deploy the web application. Out of all the
above scopes application scope > session scope > request scope>page
scope.
The default value of scope attribute is
page. Out of all the above five attributes
1 and 2 (id,
class) are mandatory and remaining attributes 3,4,5 (Bean name, type, scope)
are optional.
EX:
x.jsp
<JSP:UseBean
id=”eo” class=org.sathya.Employee”/>
When the above
statement is executed by the container in the equivalent servlet of the JSP the
container will automatically create an object of Java Bean class.
x.jsp.java
org.sathya.Employee
eo=new org.sathya.Employee();
<JSP:UseBean
id=”eo” class=”org.sathya.Employee”
Type=”org.sathya.GenericEmployee”
When the above statement is executed the
container will create an object of Java Bean class indirectly by using dynamic
binding.
x.jsp.java:
org.sathya.GenericEmployee=new
org.sathya.Employee()
2.
<JSP:setProperty----/>: The purpose of
this standard action is to place the values in the Java Bean class object which
is instantiated with respect to
EX:
<JSP:UseBean----/>
Whenever we use <JSP:setProperty
----/> it is mandatory for the JSP programmer to use
<JSP:UseBean-----/>
<JSP:SetProperty-----/>
contains three attributes they are
1.
name: This attribute always takes object name
of Java Bean class which is nothing but id attribute value of
<JSP:UseBean----/>
2.
property: property attribute takes other data
member name of Java Bean class individually or *. If we specify the data member
names of the class individually then container will call setXxx methods
individually. If we specify * then container will call all the setXxx methods
at once. It is highly recommended to specify * for property attribute for
reading the redundancy by achieving the flexibility.
3.
value: This attribute takes value of the Java
Bean class. A value of the Java Bean class can be specified in two ways they
are
a) statically
b) Dynamically:
a)
Statically: Specifying the values to the data
members of Java Bean class within the JSP program through the value attribute
is known as static value specification.
i) Application
gives hard coded approach but not flexible approach.
ii) Redundancy
of the code is increased and it reflects on performance of the web application
to avoid these problems we must use dynamic approach.
b)
Dynamically: Specifying the values dynamically
to the Data members of Java Bean class by gathering the values at run time is
known as dynamic specification. Even in dynamic specification we have two
approaches.
i)
Coolect the individual values from HTML
form at run time. In JSP program and specify those values to the value
attribute of each and every data member of Java Bean class.
I)
Emp.java:
<%String
empno=request.getParameter(“empno”);
String name=request.getParameter(“name”);
%>
<JSP:UseBean
id=”eo” class=”org.sat.Emp>
<JSP:setProperty
name=”eo” property=”empno” value=” “+empno+” “/>
<JSP:setProperty
name=”eo” property=”name” value=” “+name+” “/>
In the above approach we are gathering
flexibility but redundancy of the code is more that is if a Java Bean class is
containing n data members then it is mandatory to the JSP programmer to write
<JSP:setProperty----/>
‘n’ times. Which is one of the time consuming process. To eliminate this we use
the following
II)
* Approach: In this approach irrespective of
number of Data members in Java Bean class it is not necessary to write each and
every time <JSP:setProperty------/> but it is recommended to write only once
for accepting any number of dynamic values for the data members of Java Bean
class. In this approach we get the following advantages
a) Flexibility
achieved.
Redundancy is
eliminated which makes to get higher performance to the web application.
*While we are
using *approach for accepting the dynamic values the programmer must ensure
that HTML form parameters must be equal to data members of Java Bean class and
also satisfies the following.
i) Order must be
same.
ii) Meaning must
be same.
iii) Case must
be same.
0
Null
0.0
|
name
sal
0
Null
0.0
|
10 empno
Sathya
name
sal
3.5
Dynamically assigning the default values.
EX:2
<JSP:UseBean
id=”eo” class=”org.sathya.Emp”>
<JSP:setProperty
name=”eo” property=-“*”/>
10
Sathya
3.5
|
empno
name
sal
Initialized Java Bean class object dynamically.
Conclusion:
Hence <JSP:setProperty----/> name
and property are called mandatory attributes and value is optional mode.
3.
<JSP:getProperty-----/>: The purpose of
this tag is to obtain class in the values of JavaBean class in the JSP program.
Whenever we use this tag it is mandatory for the JSP programmer to specify
<JSP:USeBean-----/>
This tag
contains two attributes and they are mandatory
i.
name: This attribute takes object name of the
Java Bean class which is nothing but the value of id attribute of
<JSP:UseBean---/>
2.
property: This attribute takes data member of Java Bean class. This
attribute does not take *.
EX:
----------------
----------------
----------------
<b>EmpNo</b>
<JSP:getProperty name=”eo” property=”empno”/>
<br>
<b>EmpName</b>
<JSP:getProperty
name=”eo” property=”name”/>
P)
Develop a web application which illustrates the concept of Java Bean, JSP and
their communication.
P)
Develop a web application which illustrates the concept of communication
between HTML, JSP and Java Bean.
P)
Develop the following case in which we need to create a Database called Result
which contains htno, candidate name, father name, sub1 marks, sub2 marks and
total. Write HTML or JSP program which will accept htno from the client and
display candidate name, father name, sub1 marks, sub2 marks, total marks
including htno by writing JSPs and Java Beans.
P)
Develop a web application which will accept employee details and store them in
Database.
<JSP:forward ------/>: The
basic aim of this standard action is forwarding current client request to any
of the other dynamic web resource program that is either to servlet or to JSP.
This standard action can’t forward the current client request to any of the
static web resource programs that is to HTML programs because static web
resource programs does nto have validation capabilities.
This standard action must apper only one in the dynamic web resource
programs for forwarding its request to another dynamic web resource programs
that is even if we write <jsp:forward----/> standard actions container
will consider only first occurance of <jsp:forward----/> but not other
occurances.
Syn: <jsp:forward
page=”url pattern of dynamic web resource program”/>
Here dynamic web resource program represents either JSP or Servlet.
Conclusion: This
standard action is used for achieving the concept of JSP Chaining.
JSP Chaining: If
multiple JSPs are participating in processing of single client request from
those multiple JSPs are known as chainging. In this forward action tag source
JSP forward its request to the destination JSP/Servlet and finally client gets
the result of destination JSP/Servlet but client never gets the result of
source JSPs.
X.JSP:
<jsp:forward page=”y.jsp”/>
X.JSP:
<jsp: forward page=”url pattern of
Dynamic web resource program”/>
5. <jsp:include----/>: This
standard action is used for including both dynamic web resource
programs(JSPs/Servlets) and static web resource programs(HTMLs) in the source
JSP. In this action client receives the result of both destination web resource
programs(dynamic web resource programs and static web resource programs) by
including the result of source JSP.
SYN: <jsp:include page=”url
pattern of dynamic web resource programs”/>
<jsp include page=”name fo the static
web resource programs”>
EX:
X.JSP:
<jsp:include page=”Date.jsp”/>
<jsp:include page=”date url”/>
<jsp:include page=”footer.html”>
Q) What are the
differences between <%@include -------%> and <jsp include ------/>
<%include%>
|
<JSP:include-----/>
|
1.
It is one of the directive tag.
2.
Directive include always participates
in the compile time/translation time.
3.
Directive include is always used for
including static web resource programs only but not dynamic web resource
programs.
4.
Directive include includes the static
web resource program’s source code in the equivalent servlet of JSP during
translation phase.
5.
Directive tag include takes file as
an attribute.
|
1.
This is one of the standard action
tag.
2.
Action include participates at runtime
(execution phase).
3.
Action include can be used always for
including both static and dynamic web resource programs.
4.
Action include includes the result of
static web resource programs in the result of equivalent servlet of the JSP
during execution phase.
5.
Action include takes page an attribute
which illustrate the JSP and servlet.
|
P)
Develop a web application for communication between JSP and Servlet?
For complete program
please refer NetBeans(JSP)/ForwardJSP folder
Q) How do you pass the values from the JSP program to
servlet?
A) In order to pass the values from JSP
program to servlet we use <jsp:praram-----/>
Syn:
<jsp:param name=”param name”
value=value of the parameter”>
‘
‘
‘
The above tag must be always written as a part
of <jsp:forward>
EX:
X.JSP
<jsp:forward page=”empurl”>
<jsp:param name=eno” value=”100”/>
<jsp:param name=name”
value=”bhargav”/>
<jsp:param name=sal” value=”1000000”/>
All the above values are available
in Employee servlet in the form of Request object by organizing in (key, value).
Custom Tags:
In JSP custom tags are introduced in JSP
1.2 version and fully enhanced in JSP 2.0 version.
1. Custom
tags concept is one of the specification released by SUN Micros system and it
is implemented by server vendors.
2. In
Order to develop any custom tags we need to import a predefined package
javax.jsp.tagext.*
In JSP we have two catageories of tags
they are
i. Predefined tags
ii. Custom tags.
i. Predefined Tas: Predefined
tags are those which are developed by server vendors according to the
specification of SUN Micro system.
<jsp:forward----/>
<jsp:include----/>
What are all the predefined tags are available in JSP may not be
fulfilling the requirements of JSP to fulfill all the requirements of JSP
programmers so to fulfill the requirements of JSP programmers we need a
facility to develop our own tags called Custom tags.
Custom tags: Custom
tags are those which are developed by Java programmer according to the
specification of custom tag excepted by the JSP programmer.
Advantages of Custom tags: As
a part of our web project if we use concept of custom tags facility then we get
the following advantages.
1. Redundancy
of the code is reduced.
2. Custom
tags provides reusability.
3. Custom
tags provides simplicity or easiness to the JSP programmers.
Number of phases requirement for
development of custom tags: What are all the phases
followed by server vendors for development of defined tags in JSP. As a part of
our project we follow the same phases. These phases are classified into four
types.
1. Decide
the custom tag and use it JSP.
2. Develop
the web.xml file.
3. Develop
the TLD file (Tag library descriptor)
4. Develop
tag handler class(Java Bean class)
In above syntax prefiex name known as short name and it short name and
it should not be JSP, javax,SUN etc., because these prefixes are reserved by or
already used by server vendors.
Tagname: Represents
name of the custom tag and it should not be choosen from predefined tags
attribute name1, attribute name2 ----attribute name n represents name of the
attributes related to the custom tag and these may be optional may be managed
by HSP programmer val1,val2,-----,valn. Represents the values for the
attributes of custom tags.
EX:
<sathya:big name=”Sathya
Technologies”/>
Here Sathya à
prefix/short name
Big à
Tag name
Name à
attribute name (manadatory)
Sathya Technologies à
value for name attribute.
When we use any custom tag as a part of JSP it is mandatory for the JSP
programmer to specify the location of TLD file either directly or
indirectly through web.xml> location of TLD file is specified. To do this we
use a directive tag called
<%#taglib----%>
The <%taglib----%> directive tag will establish the bridge
between JSP program where custom tag is used and TLD file or web.xml file.
Syn:
<%@taglib url=”dummy name”
prefix=”short name of custom tag”%>
EX:
Sathya.jsp:
<%@taglib
uri=”demo” prefix=”sathya”>
stagà<sathya:big
name=”sathya technologies”/>
------
-------
(or)
etag à >/sathya:big>
ii) Development of web.xml file:
Development of web.xml file as a part of custom tag is
optional. If we specify a dummy name for uri attribute of taglib then it is
mandatory for the custom tag developer to develop web.xml file. In custome tags
development web.xml file always gives location of the TLD file which is present
in our web application directory structure
web.xml:
<web-app>
<taglib> demo</taglib-trl>
<taglib-location>/WEB-INF/Sathya.tld/</taglib-location>
<taglib>
</webapp>
In one web.xml
file one can have multiple taglibs(<taglib>------</taglib>) for
specification of locations of multiple tld files.
iii) Development of TLD Fle: TLD stands for tag library descriptor. TLD is
one of the XML document which always describes the custom tags that is
prefix name, tag name, tag handler class, attributes etc.,
The structure of the TLD file is given below filename.tld
<taglib>
<short name>
</short name>
<tag>
<name>-----</name>
<tagclass>------</tagclass>
<attribute>
<name>-----</name>
<required>--</required>
<rtextrvalue>
</attribute>
</tag>
</taglib>
1
|
<shortname>------</shortname>
2
|
<tag> ------</tag>
3
|
<name> -----</name>
Represents name
of the custom tag.
4
|
<tagclass> -------</tagclass> represents tag handler
Attribute represents the details about
attribute names or custom tag.
name: Represents
attribute name of the custom tag.
<required>-------</required>:
represents either true or false. If it
is true the attribute name is mandatory to use. If it is false then
the attribute name is operation to use.
<rtextr
value>-----</rtextrvalue>
Runtime or required text expression
value. It takes either true or false. If it is true then we must pass
value to the attribute of custom tag dynamically. If it is false then we
need to pass the value to the attribute of custom tag statically. If one custom
tag contains multiple attributes then write multiple times
<attribute>-----</attribute>
If one shortname contains multiple tags then write multiple tags
<tag>----</tag>
Conclusion: when
we are developing custom tags one can have multipl tld files, they must be
placed in WEB-INF folder on some filename with an extension .tld.
Sathya.tld:
<taglib>
<shortname> sathya
</shortname>
<tag>
<name>big</name>
<tagclass>sp.Sathya</tagclass>
<attribute>
<name>name</name>
<required>true</required>
<rtexprval>false<rtexprval>
</attribute>
Development of tag handler class: Tag handler class is one fo the Java Bean
class which always gives functionality for custom tag while we are developing
TagHandler class, the TagHandler class developer must ensure all the attributes
of custom tag must be taken as data members in the TagHandler class in the same
sequence, in the same meaning and in the same case in which they appear in JSP
program. In order to develop custom tags we need to use the kife cycle methods
known as custom tags life cycle methods. Which are present in
javax.servletr.jsp.tag.*.ext.TagSupport class.
Custom tag methods are classified into two types they are
i.
public int doStartTag()
ii. public int doEndTag() throws JSPException
i. public int doStartTag():
1. It
is one of the predefined null body method present in TagSupport class.
2. This
method will be called automatically by the container when starting tag of
custom tag is taken place.
3. Tn
this method we always write the block of statements which will provide
functionality to the custom tag in other words doStart tag must be overridden
in the TagHandler class by extending the from TagSupport class to provide functionality
to the custom tag in other words doStartTag must be overridden in the
TagHandler class by extending from TagSupport class to provide the
functionality to the Custom tag.
4. This
method returns the following possible values.
a)
public static final int EVAL_BODY_INCLUDE
b)
public static final int SKIP_BODY
Here Data member a is used for evaluating
body of the custom tag. Data member b is ued for skipping body of the custom
tag. The two data members makes the container to understand whether to execute
the body of custom tag a or skip the body of custom tag.
The default returned value of doStartTag
is EVAL_BODY_INCLUDE
EX:
Public
int doStartTag() throws JSPException, IOException
{
Try
{
pageContext.getOut().println(“<h1>+name+”</h1>”)
or
out.println(“<h1>+namne+”</h1>”);
}
Catch(Exception
e)
{
Throw(new
JSPException(e.getMessage());
}
Return
EVAL_BODY_INCLUDE;
ii. public int doEndTag() : It
is one of the predefined null body method present in TagSupport class. This
method will be called by the container automatically whenever ending tag of
custom tag is taken place. doEnd() is always used for providing the
functionality of custom tag that is we override doEndTag() in the TagHandler
class by extending fronm TagSupport class for providing the functionality of
custom tag. This method returns the following two possible values
c. public static final int EVAL_PAGE
d. public static final int SKIP_PAGE
Data member C is used for executing the rest of the statements which are
present in the JSP page after execution of ending tag of the custom tag.
Data member d is used to skipping the rest of the statements which are
return in JSP page after executing ending tag of custom tag. The default
returned value of the doEndTag() is EVAL_PAGE. Hence the functionality of
custom tag can be written either doStatrt() or doEndTag().
In the above the data members a,b,c,d are present in TagSupport class
and they are automatically getting inherited in TagHandler class.
Steps/Guidelines for developing
TagHandler class:
Import javax.servlet.jsp.tagext.*,
javax.servlet.jsp.* and other packages.
Choose an appropriate user defined class
and ensure whose modifier must be public.
This class is known as TagHandler class
and it is one kind of the JavaBean class.
Whatever class is selected in step-2
must extends a predefined class called TagSupport for inheriting life cycle
methods of custom tag.
doStart()
doEndTag()
4. Choose the date members in TagHandler
class the data members of TagHandler class must be similar to attribute names
of custom tag by matching with same case, order and meaning for each and every
data member of TagHandler class, we must define set if setXxx(-) and set of
getXxx(-)
Override either doStartTag() or
doEndTag() are both methods by writing the block of statements for providing
the functionality to custom tag.What ever the TagHandler class we are choosing
in step-2, it must be given as a file name with an extenstion .java
P) Develop a custom tag for
displaying the specified name <h1>
Note:
<body content>-----</body
content>
In the tld file the value of body content may be passed in two ways they
are
i. empty
i. jsp content.jsp
if<body content>-----</body content>
value is empty then container understands there is no body in custom tag and
the custom tag developers must ensure the return type of doStartTag() must be
SKIP_BODY. If <body content>-------</body content> is jsp then it
is an indication to the container or understands there is a body for the custom
tag and it will be executed by the JSP container like the body of the
predefined JSP tags and the custom tag developer must ensure the returned value
of doStartTag() must be EVAL_BODY_INCLUDE
P) Develop a custom tag which will select
all the records of specified Database
JSTL (JSP Standard template
library):
1. JSTL
one of the specification developed by SUN Micro system for the development of
frequently used tags by the JSP programmers.
2. JSTL
is one of the specification which contains set of rules released by SUN Micro
system and they are implemented by various server vendors.
3. At
the time of releasing JSTL specification there was a facility called custom
tags development custom tag development in JSP and developing custom tags for
the JSP programmer is the difficult process and time consuming process.
4. To
eliminate these problems of custom tags, we have JSTL specification and they
are implemented by server vendors in the initial days of JSTL development, the
JSTL tags becomes server development that is if we want to run any JSTL
based application on Tomcat server then the JSTL developer must learn JSTL tags
of Tomcat and weblogic server.
The developer has to learn web logic
related JSTL which is a complex process for the Java programmer that is
learning server dependent JSTL tags is difficult process to eliminate this
difficult SUN Micro system has collected all server dependent JSTL and prepared
common JSTL which will run on every server in order to deal with JSTL
based applications we need to take two jar files they are
i) JSTL.jar
ii) Standard.jar
JSTL tags are classified into five types
those are
1. Core Tags
2. SQL Tags
3. Internationalization Tags (il8n)
4. XML based tags
The following table gives the JSTL tagname, prefix uri and tld file.
Configuring web.xml file for JSTL
tags:
web.xml:
<taglib>
<taglib-location>/WEB-INF/c.tld</taglib-location>
<taglib>
-------------
--------------
Web application structure for deploying
JSTL based applications
Conclusion: The
jar files like JSTL.jar and standard.jar contains TagHandler class names used
in JSTL development.
Core Tags: The
basic aim of Core tags is to develop preliminary programming in web application
development by making use of JSTL tags that is JSTL core tags deals with the
following
a) Choosing the variables/ declaration
of variables
Initializing the variables and printing
the variable values dealing with the conditional statements dealing with
looping statements. Dealing with request parameter gathering logic etc., JSTL
core tags are classified into following
1. <c:set-----/>
2. <c:out-------/>
3. <c:if
------/>
4. <c:choose
-----/>
5. <c:forEach----/>
6. <c:forToken----/>
1. <c:set----/>: The aim of
this tag is choosing the variable name and passing the value inside the
variable.
Syn:
<c:set var=”varname” value=”val to
var” scope=”page” ||request|| session||application.
C à
represents prefix of core tags set represents tag name variable, value and
scope are attributes represents variable
name value attribute represents value to the variable name, var and value
attributes are mandatory.
scope: scope
attribute represents the availability of variable value and scope value can be
either page or request or session or application for more see
<JSP:setProperty>
EX:
<c:set var=”a” value=”100”/>
2. <c:out--------/>
EX: value
of a=<c:out value=”$#”{var name}/>
Aim: The
aim of this tag is to access/display/ print the variable which is set with
<c:set ----/>
Syn:
<c:out value=”$” {var name}/>
EX:
<c:set var=”stno” value=”100”/>
Studentno=<c:out value=’${stno}%>
3. <c:if--------/>
The aim of this tag is to evaluate
conditional statements( the behavious of this tag is somne thing like simple if
statement of C language
EX:
<c:if test=${testconfition}”>
Block of statements
</if>
<c:set var=”n1”, val=10”>
<c:set vatr=”n2” val=”20”>
>c: if test=’${n1}>${n2}”>
<c:out value=”${n1} is greater than
${n2}”/>
</c:if>
For all programs please
refer D:\NetBeans(JSP)\JSTL, D:\MyEclipse(JSP) folders