jsp
Java
Server Pages
JSP is another web technology from Sun Microsystems besides SERVLETS.
JSP is a simple but powerful technology used to generate dynamic web pages on
the server side. Jsps are direct extension of java servlets and provide a way
to separate content generation from content presentation. Important point about jsps is that they are
just servlets that are created from a combination of HTML and java code. It means that they have the complete
functionality of a normal servlet.
Disadvantages of
servlets
Servlets are poor in presenting the response to the client. Dynamic
content generation code is mixed with presentation code. As a result
development, maintenance and administrative problems arise. RAD(Rapid
Application Development) is not promoted as web designing tools cannot be used
for web content.
LIFE CYCLE
OF A JSP PAGE
When a JSP is accessed for the first time, the server is slower in
responding. This is because, every JSP
page must be converted into an instance of a Servlet class before it can be
used to service client requests. For
each request, the JSP engine checks the time stamps of the source JSP page and
the corresponding Servlet class file to determine if the JSP Page and the
corresponding Servlet class file to determine if the JSP page is new or if it
has already been converted into class file.
Therefore, if we modify a JSP page, the whole process of converting the
JSP page into servlet is performed again.
This process consists of the following phases known as life cycle
phases.
·
Page translation
·
Page compilation
·
Generated Servlet class loading
·
Servlet instantiation phase
·
Calling jspInit() known as
initialization phase
·
Calling _jspService() known as
servicing phase.
·
Calling jspDestroy() known as
destruction phase
Translation
phase: - During this phase, the JSP engine reads the JSP
page, parses it, and validates the syntax of the tags. Once the validations are completed, the
engine creates the java source code that contains public Servlet class.
Compilation
phase: - In this phase, the java compilation unit generated
in the previous phase is compiled. The
result of this compilation is the class file of the container generated
Servlet.
Instantiation
Phase: - The Servlet class is loaded dynamically and the
Servlet engine creates the Servlet instance.
Life cycle
methods of ajsp: - Container generated Servlet implements
javax.servlet.HttpJspPage which is a sub interface of jspPage interface. JspPage
interface extends javx.servlet.servlet interface. JspPage interface declares 2
methods.
·
JspInit()
·
JspDestroy()
HttpJspPage interface declares one method that serves the Http client
requests.
·
_jspService()
These methods are known as life cycle methods of a jsp.
Initialization
Phase: - The container calls this method to initialize the
Servlet instance.
Servicing
phase:- In this phase –jspService () method is called by
the container every time request comes to the jsp
Destruction
phase: - When the container is instructed to take the
Servlet instance out of service, before the instance is sent for garbage
collection, container calls the life cycle method jspDestroy().
The
components of a JSP page
A jsp contains HTML content, jsp tags and java code. By using jsp tags either we can embed java
code directly into the jsp page or we can invoke the functionality of java code
running behind the scenes. Java code is required for a jsp to provide dynamism
to the web page.
Jsp tags can be classified into the following 3 categories.
1.
Scripting Elements
2.
Directives
3.
Actions
Scripting
elements: - The basic functionality of scripting elements is
to allow jsp authors to embed java code directly into the jsp. We can classify scripting elements as
follows.
1.
Declaration
2.
Expression
3.
Scriptlet
Declaration: A JSP declaration lets us define methods or variables in a jsp. These methods and variables become direct
members of the container generated Servlet class. We can define both instance and static
members in a declaration. A declaration
has the following form.
<%!
//Java variable
declarations and method definitions
%>
For example,
<%!
private int
count=1;//instance variable definition
static int
total;//static variable declaration
int getCount() //instance method
definition
{
return count;
}
static int getTotal()
{
return total;
}
%>
·
In a declaration we can define
(rarely) a static block and a class also
·
In a jsp we can have any number of
declarations in any order.
·
Variables declared in a declaration
are initialized to java default values.
·
Variables in a declaration retain
their values across multiple requests because
they are created and initialized only once.
Expression: - An expression-scripting element is an embedded java expression that
is evaluated and converted to a text string.
The resulting text string is placed in a JSP output, in the location at
which the element appears. Expressions
act as placeholders for java language expressions. An expression is evaluated each time the page
is accessed, and its value is then embedded in the output HTML. An expression
has the following form.
<%= any valid java
expression %>
Examples:
<%= a+b %>
<% = new java.util.Date()%>
·
Expressions are inserted into the
service method of the container- generated servlet.
·
We can have any number of
expressions per page.
·
Embedded java expression should not
be terminated with a semicolon.
·
We can print the value of any
object or any primitive data type to the output stream using an expression.
·
We can also use an expression in a
jsp action attribute. In this case the
value of the expression does not go to the output stream. It is evaluated at request time, and its
value is assigned to the attribute. An
expression used in this way is known as request-time attribute expression.
Scriptlet: - A scriptlet is used to include complete fragments of java code in
the body of the JSP page. This scripting
element differs from the other two in 2 ways.
·
It is not limited to the
declaration of methods and variables.
·
It does not generate a string
output directly, as expressions do.
A scriptlet has the following form. <% Any valid free from of java
code%>
For example,
<% int sum =0;
for(int
I=1;I<10;I++)
sum + =1;
%>
·
Scriptlet can be placed anywhere
within the jsp body.
·
We can place any number of
scriptlets in a jsp.
·
Each scriptlet is inserted into the
service method of the container-generated servlet in the given order.
·
The scriptlet is executed each time
the page is requested.
·
As scriptlets contain any java
code, they are typically used for embedding computing logic within a JSP page.
Comments in
a JSP page
In a jsp we can have 3 kinds of comments.
·
Java comments
·
HTML comments
·
JSP comments
In a declaration or a scriptlet we can have single line or multi line
java comments.
HTML comment is of the form <!-- Any commenting text -->
A JSP comment is of the form <%--Any commenting text --%>
Note: - A JSP comment is also known as a hidden comment as it is not
displayed in the client.
Example jsp
that makes use of all scripting elements
//one.jsp
<HTML>
<BODY BGCOLOR= “wheat”>
<CENTER>
<H2> FIRST JSP
EXAMPLE</H2>
</CENTER>
<%!
String names
[]={“Rama”, “Rahim”, “David”};// Array definition
private String
getName(int index)
{
return
names[index];
}
%>
THE THIRD ERSON IS : <%
=getName(2) %> <BR>
<%
for(int I=1
;I<=5;I++){
%>
WELCOME TO JSP
WORLD<BR>
<%
}
%>
</BODY>
</HTML>
XML syntax for
JSP elements
The JSP specification defines two sets of syntax for authoring JSP pages:
standard JSP syntax format and XML syntax format. JSP files that use the
standard syntax are called JSP pages. JSP files that use the XML syntax are
called JSP documents.
JSP
declaration
<jsp:declaration>
int count=0;
</jsp:declaration>
Jsp
expression
<jsp:expression>
count
</jsp:expression>
Jsp
sriptlet
<jsp:scriptlet>
if(count<6)
count++;
</jsp:scriptlet>
Jsp text
<jsp:text>
Welcome to JSP
documents
</jsp:text>
JSP DIRECTIVES
While expressions, scriptlets and declarations are used to define the
logic to be executed at run-time (request processing time), directives are used
to provide pages with information at translation time-when the JSP page is
converted to a Servlet.
Directives are used to specify the classes that are imported, to
specify the error page used for catching exceptions, to import tag libraries
and making them available to use on the page etc.
JSP directives provide general information about the JSP page to the
JSP engine.
JSP directives do not generate code.
They are not part of the logic within the JSP code. JSP directives provide directions and
instructions to the container, telling it how to handle certain aspects of JSP
processing.
There are 3 types of directives according to JSP specification.
·
Include directive
·
Taglib directive
·
Page directive
A JSP directive is of the form
<%@ directive
attribute=value %>
include
Directive:- An include directive tells the JSP engine
to include the contents of another file inline (exactly at the location of
directive usage) in the current jsp.
Included file can be another jsp or a HTML file. Include directive is of the following
form. <%@ include file= “filename”
%>
The following example includes the source code of the header.jsp in the
current jsp.
<%@ include file= “header.jsp”%>
When the current jsp (the jsp in which this directive is used) receives
the client request, the jsp engine reads the entire jsp before translation. Once include directive is encountered, the
jsp engine copies the contents of the header.jsp into the current jsp
inline. Then it translates the current
jsp into a Servlet. As this happens
during the translation phase of the jsp, we say that directives are translation
time instructions that are given to the jsp container (engine).
taglib
Directive: - This directive is used to tell the
container which tag library a specific JSP requires. It is also used to assign a prefix that is
used within the JSP page to identify tags from a specific tag library. Now jsp engine can locate the code for these
tag libraries and get them ready for use by the JSP page. Taglib directive is
of the form <%@ taglib prefix= “name” uri= “value”%> (More on this in
Custom tags).
page
Directive:- This directive informs the engine about
the overall properties of a JSP page.
This directive applies to the entire translation unit and not just to
the page in which it is declared. This
directive is of the following form.
<%@ page attribute= “value” attribute = “value”…….%>
Even though there are many attributes for the page directive, the most
frequently used ones are discussed here.
import: - This attribute is similar to
the import statement in a normal java source code. Once this attribute is used, the jsp
container inserts an import statement into the generated Servlet for each of
the packages declared using this attribute.
We can import multiple packages in a single tag by using a comma-separated
list of package names. We can also use
multiple tags for readability.
Example:-
<%@ page import=
“java.io.*,java.util.*”%>
OR
<%@ page import=
“java.io.*,” %>
<%@ page import=
“java.util.*”%>
The key point is that it is the only attribute of the page directive
that can occur multiple times in a translation unit.
session:- This attribute indicates to the jsp engine whether the current jsp
takes part in a Http session. The
default value is true. If we don’t want
the jsp to participate in a session, then we have to explicitly say
<%@ page session = “false”%>
errorPage: - We can handle the exceptions in a jsp by writing try and catch
blocks. However, the JSP specification
provides cleaner approach. This approach
separates the error handling code from the main page and thus promotes
reusability of exception handling mechanism.
In this approach, a jsp uses the error page attribute of the page
directive to delegate the exception to another JSP page that has the error
handling code.
<%@ page erorPage= “handler.jsp”%>
Once the above instruction is encountered, jsp engine delegates the
exception handling to handler.jsp if at all an exception is generated in the
current jsp.
isErrorpage: - This attribute conveys whether the current jsp can act as an error
handler for any other jsp. By default
this value is false. In the above
example, when we write handler.jsp, in that file we must use the following
statement.
<%@ page isErrorPage= “true”%>
contentType: - This attribute specifies the MIME type of the output. The default value is text/html.
If we want to change the MIME type we can say as follows.
<%@ page contentType=”image/gif” %>
JSP IMPLICIT OBJECTS
During the translation phase, the JSP engine declares and initializes
nine commonly used variables in the service method of the generated
Servlet. They are implicitly made
available to a jsp without need of declaring them. These are known as implicit variables or
implicit objects. They are as follows.
·
request
·
response
·
session
·
config
·
application
·
page
·
exception
·
out
·
pageContext
request: - This object is of type javax.Servlet.http.HttpServletRequest. It
refers to the current request to the jsp.
By using this object we can capture the client data.
For example, in a scriptlet we can write as follows.
<%
String
name=request.getParameter (“html textbox name”);
%>
with the above scriptlet we can get the form data directly into the
jsp.
response: - This object is of type javax.servlet.http.HttpServletResponse. It is used for sending customized response to
the client.
session: - This object is of type javax.servlet.http.HttpSession. This object
is not available in a jsp if we say <%@ page session= “false” %>. In a Servlet when we implement session
tracking we call the method getSession() on the request object. In a jsp it is implicitly available. If we want to implement session tracking in a
jsp, we make use of this object.
config: - This object is of type javax.servlet.ServletConfig. When
initialization parameters are supplied to the jsp explicitly from the web.xml,
we can retrieve them by using this object.
<% String paramvalue= config.getInitParameter (“paramname”); %>
application: - This is an object of type javax.servlet.ServletContext. It refers to the environment to which the jsp
belongs. Using this object we can
retrieve application level state. All
the web components (jsps & servlets) running in the same application can
share common information. For example if
a Servlet or another jsp has stored some info in the ServletContext object, in
our current jsp we can retrieve it as follows.
<% String value= (String) application.getAttribute(“name”); %>
page: - This is an object of type java.lang.object. It refers to the instance of the generated
Servlet. This is very rarely used in a
jsp.
exception:- This object is of type java.lang.Throwable. This object is not available to all the
jsps. Those pages, which are designated
as error pages, can access this object.
Note: - Recollect how to declare a page as error handler.
<%@ page isErrorPage= “true” %>
out:- This object is of type javax.servlet.jsp.JspWriter. It refers to the output stream for the
page. We use this object to send html
content from the jsp. Its usage is seen
more in custom actions.
pageContext:- This object is of type javax.servlet.jsp.PageContext. This is the most important implicit
object. It refers to the page
environment. This object does 3 things.
·
It stores references to implicit
objects. By supplying this single object
to any java helper class, we can supply all the implicit objects. That helper class can retrieve all the
implicit by calling getxxx() methods on the pageContext object.
ServletContext context=
pageContext.getServletContext();
ServletConfig
config=pageContext.getConfig();
HttpSessionsession=
pageContext.getSession();
HttpServletRequest request =pageContext.getServletRequest(); etc.
·
Provides methods to get and set
attributes in different scopes
·
Provides methods for dispatching
requests to other resources in the web application, which is equivalent to
RequestDispatcher in SERVLET API.
pageContext.include(String relativeurl);
pageContext.forward(String relativeurl);
JSP PAGE SCOPES
A scope defines the existence and accessibility of objects from within
the jsps and servlets in a web application.
All the objects in a jsp page exist in any one of the following four
scopes.
·
Page
·
Request
·
Session
·
Application
Page scope: - Objects in the page scope are accessible only in the translation
unit in which they are defined. They do
not exist outside the processing of a single request within a single translation
unit. That is, objects in page scope are
non shareable across multiple web components.
Such objects are stored as attribute-value pairs by the pageContext
object. PageContext class provides
methods to store objects in page scope and retrieve them.
1.
public void setAttribute(String
name, Object value):- This method is used to store an application level object
into the pageContext object with a specified name in page scope.
2.
Object getAttribute(String name):-
Returns the object associated with the name in the page scope or null if not
found.
Request
scope: - Objects in the request scope are shared across all
the web components that process the same request and are accessible only while
that request is being serviced. These
objects are maintained as name value pairs in the HttpServletRequest
object. If we want to store objects in
one jsp in request scope, we call the following method on the pageContext
object.
setAttribute(String name, Object value, PageContext.REQUEST_SCOPE);
In another jsp, if we want to retrieve the object we call the method on
the pageContext object.
Object getAttribute (String name, PageContext. REQUEST_SCOPE);
We have 2 more methods in the PageContext to deal with objects at
different scopes
1.
void removeAttribute(String name,
int scope):- Removes the object associated with the specified name in the given
scope,
2.
Enumeration
getAttributeNameinScope(int scope)
Application
scope: - Application scoped objects are shared across all
the web components of the web application.
They are accessible for the life of the application. These objects are maintained as name value
pairs by the instance of ServletContext.
If we want to store an object in application scope, we have to call the
following method on the pageContext object.
setAttribute(String name, Object value, pageContext.APPLICATION_SCOPE);
Once the above method call is executed, the specified object reference
is stored in the ServletContext object. As ServletContext object is unique for
every web application, from any other jsp or servlet in the same web
application, the object can be retrieved.
Session
scope: - Objects in the session scope are shared across all
the requests that belong to a single user session and are accessible only while
the session id is valid. These objects
are maintained as name value pairs by the instance of HttpSession. If we want to store an object in application
scope, we have to call the following method on the pageContext object.
setAttribute(String name, Object value, pageContext.SESSION-SCOPE);
List of scope specifying constants in the pagecontext class
·
static final int APPLICATION_SCOPE
·
static final int REQUEST_SCOPE
·
static final int SESSION_SCOPE
·
static final int REQUEST_SCOPE
Methods inherited by the PageContext class from JspContext class
·
void setAttribute(string name,
Object value, int scope)
·
Object getAttribute(String name,
int scope)
·
Object removeAttribute(String name,
int scope)
·
Enumeration getAttributeNames
InScope(int scope)
Scope
search methods of PageContext inherited from JspContext
·
Object findAttribute (String
name):- This method searches for the named attribute in page, request, session
and application in this order and returns the associated value.
·
int getAttributeScope (String
name):- This method returns the scope in which a given attribute is defined.
JSP ACTIONS (TAGS)
An Action is a request time instruction given to the JSP engine. Actions are high-level JSP elements that
create, modify, or use other objects.
Actions are coded strictly according to the XML syntax. JSP specification defines two kinds of
actions.
·
Standard actions
·
Custom actions
Standard Actions:- standard actions are those actions that are
associated with standard tags. Which are delivered with the JSP container. The container knows the meaning of these
tags. Whenever standard action’s tag is
encountered in a jsp, the container invokes built in functionally and the
required action takes place. Every
standard action is of the form
<jsp:action attributed1= “value” attribute2 = “value” />. According to JSP specification the following
are the important standard actions.
·
include
·
forward
·
param
·
useBean
·
setProperty
·
getProperty
include
standard action:-
The net effect of this standard action is equivalent to the
RequestDispatcher’s include() method of the SERVLET API. Include standard action is of the form
<jsp:include page= “resourcepathtoinclude” />. This standard action includes the output of
the target jsp into the response of the main jsp at the time of main jsp is requested. This action works as follows.
When the client makes a request for the main jsp, the JSP container
reads the entire page first. When it
encounters the include standard action, it inserts a method call inline in the
generated Servlet. That method call at
runtime combines the response from the target jsp. The container generates servlets for both JSP
files.
param
standard action:-
In the include mechanism or forward mechanism; the included page (target
jsp) uses the same request object as the originally requested page (main
jsp). As a result, the included page
normally sees the same request parameters as that of main jsp. If at all, we want to add or replace those
parameters, we make use of param standard action. This action is of the following form.
<jsp;param name= “paramname” value= “paramvalue” />
forward
standard action:- the net effect of this standard action
is equivalent to the RequestDispatcher’s forward() method of the SERVLET API,
forward standard action is of the form <jsp:forward page=
“resourcepathtoinclude” />. This
standard action switches the control completely from the source jsp to the
target jsp. And the target jsp is
responsible to deliver the output to the client.
USING JAVA BEANS IN A jsp
In order to handle a java bean in a jsp we make use of 3 standard
actions.
·
useBean
·
setProperty
·
getProperty
Before we observe the functionality of these standard actions, first of
all let us see the details about Java Beans.
A java bean is a specialized java class that is defined according to
Java Beans specification. According this
specification a bean class should be defined according to the following rules.
·
Class is public
·
It has public default constructor
·
Properties of the class are private
·
Each property has one set method
and one get method that is public
·
The class implements java.io.Serializable
interface
Whenever a Java bean is used in a web application, besides the above
rules, we have to place it in a user-defined package.
/*
EmployeeBean example
Source code:-
EmployeeBean.java
*/
package emppack;
public class EmployeeBean implements java.io.Serializable
{
private int empno;
private float salary;
public void setEmpno(int
empno)
{
this.empno=empno;
}
public void setSalary(float
salary)
{
this.salary=salary;
}
public int getEmpno()
{
return empno;
}
public float getSalary()
{
return salary;
}
}// EmployeeBean
In order to make use of this bean in a web application, we have to
compile it with special command. >
javac –d . EmployeeBean.java.
As a result of compilation we get the directory emppack in which
EmployeeBean.class file placed. Then
copy this emppack in the classes directory of WEB-INF. Now a JSP page in that web application can
make use of this bean class.
useBean
standard action:-
This standard action either gives the existing bean instance reference
or creates one. This standard action is
of the following form.
<jsp:useBean id= “refname” class = “package.ClassName” scope=
“scopename”/>
id
attribute:- The id attribute uniquely identifies a
particular instance of a bean. This
attribute is mandatory because its value is required by other two standard
actions. In the generated java Servlet
class, the value of id is treated as a java programming Language reference
variable. Therefore, this variable name
can be used in expressions and scriptlets.
class
attribute:- It specifies the java class for the
bean instance. If the useBean action tag
cannot find an existing bean in the specified scope, it creates a new instance
of the bean’s class as specified by the value of the class attribute.
scope
attribute:- This attribute specifies the scope in
which the bean resides. The existence
and accessibility of a java bean from JSP
pages are determined by the 4 scopes that we have already
discussed. This attribute is
optional. If we don’t specify this
attribute, by default it takes page scope.
setProperty: - This standard action is used
to provide data to the bean instance.
This is of the following form
<jsp:setProperty name = “beanref” property= “propertyname” value=
“value”/>
name
attribute:- This is the bean reference specified in
the id attribute of useBean standard action.
To which bean instance we are providing data is specified by this
attribute.
property
attribute: - This attribute specifies to the
container that to which bean field data has to be assigned.
value
attribute: - This attribute specifies the value to
be given to the bean field.
getProperty
standard action:- This standard action is used to
retrieve values from the bean instance and to send the values to the
client. This is of the following form
<jsp:getProperty name= “beanref” peoperty = “propertyname” />
name
attribute:-
This is the bean reference specified in the id attribute of useBean
standard action. Which bean instance’s
property we are trying to access is specified by this attribute.
property
attribute:- This attribute specifies the bean field
name whose value we are trying to access.
CUSTOM ACTIONS (CUSTOM TAGS)
Our own created tags are known as custom tags. By using standard tags we are able to make
jsps script less. But the functionally
offered by standard actions (tags) is limited.
Industry strength web applications demand complex application
logic. To meet that requirement and make
jsps scriptless we develop custom tags.
JSP API provides library support for custom tag development through the
package javax.servlet.jsp.tagext.
Whenever we want to develop a custom tag and its associated action,
there are 2 important things we need to do.
·
Writing the tag handler and copy it
into the classes directory
·
Write the tag library descriptor
and copy it into the WEB-INF
Tag Library descriptor: - It is
an xml file with tld extension. In this
file we define our own tags, specify their properties and perform mappings
between the tags and associated tag handlers.
Tag Handler: - Defining a tag is not sufficient to perform an
action. Every tag we define should have
a java class associated with it to provide custom functionality. The java class that provides the
functionality for the custom tag is known as the tag handler. Every java class cannot act as a tag
handler. It should be defined in
compliance with the JSP specification.
According to the JSP specification, any java class can become a tag handler
if it implements javax.servlet.jsp.tagext.Tag interface directly or
indirectly. This interface provides life
cycle methods for the tag handler.
Container manages the life cycle of the tag handler and calls the life
cycle methods on the tag handler instance.
Tag interface provides the following important life cycle methods.
·
setPageContext (pageContext
pageContext)
·
doStartTag()
·
doEndTag()
·
release()
setPageContext():- JSP container after instantiating the tag handler,
calls this method by supplying the PageContext object as argument. By supplying this object, the container makes
the tag handler aware of the environment in which, its associated tag
runs. PageContexxt gives us all the
implicit objects required in the tag handler.
doStartTag():- Container calls
this life cycle method on the tag handler instance when the start tag is
encountered in the jsp. We write custom
action code in this method. This method
can return any of the following 2 constants to the container.
·
Tag.SKIP_BODY
·
Tag.EVAL_BODY_INCLUDE
The first constant instructs the container to ignore the body of the
tag. The second constant indicates to
the container that the body of the tag has to be evaluated. doEndTag():- Container calls this method when
it encounters end tag in the jsp. This
method is called irrespective of whether the custom tag has been written using
the full or short hand format. This
method can return any of the following 2 constants to the container.
·
Tag.SKIP_PAGE
·
Tag.EVAL_PAGE
The first constant indicates that the rest of the page after this tag
should not be evaluated. The second
constant indicates that the rest of the page should be evaluated.
release():- This method is called by the container just before the tag
handler instance is garbage collected.
This method is used by the programmer to release any resources (data
base connections) allocated to the tag handler.
Note:- Our tag handler does not implement
Tag interface directly. It extends
TagSupport class that implements Tag interface.
This provides some default functionality to the tag handler.
APPLICATION
FLOW FOR THE CUSTOM TAG
·
When JSP engine encounters a custom
tag in a JSP page, it checks for a matching prefix in the JSP page’s list of
taglib directives.
·
When it finds the match, it gets
the uri value from the taglib directive.
·
Container looks for the uri match
in the web.xml
·
When match is found in the web.xml,
container looks for the taglib-location
·
Container uses the TLD file to map
the appropriate tag handler with the custom tag.
·
Tag handler is executed.
Custom tag
with attributes
Whenever a custom tag has attributes the implementation is a 2-step
process.
·
For every attribute of the tag, one
private instance variable plus corresponding public setter method is to be
defined in the tag handler class.
·
In the .tld file, within the
<tag> element we have to make use of <attribute> elements.
<attribute> element has 3 child elements.
a)
name:- It is used to specify the
name of the attribute
b)
required:- It specifies whether
this attribute is mandatory or optional.
c)
Rtexprvalue:- It specifies whether
the value can be supplied at runtime or not.
Jsp examples
Q) Web
application in which, the end user enters his/her name into the web form. A jsp
should receive the name and greet the use with name.
Directory
structure
greetingapp
greet.html
greet.jsp
WEB-INF
web.xml
After deployment, type the following URL in the browser.
http://localhost:8080/greetingapp/greet.html
When end user enters name and clicks on the button, the following
response comes.
Source code
of greet.html
<HTML>
<BODY
BGCOLOR="wheat">
<FORM
ACTION="greet.jsp">
<CENTER>
NAME <INPUT TYPE="text"
NAME="t1">
<INPUT TYPE=submit
VALUE="send">
</CENTER>
</FORM>
</BODY>
</HTML>
Source code
of greet.jsp
<HTML>
<BODY
BGCOLOR="yellow">
<H1> HELLO, <%=
request.getParameter("t1") %>
WELCOME TO OUR
WEBSITE</H1>
</BODY>
</HTML>
Source code
of web.xml
<web-app>
</web-app>
Observation
to be made
1.
We need not register jsps with the
web application.
2.
In the expression, implicit object
request is used to capture form data.
3.
In the <FORM> tag of HTML,
ACTION=”greet.jsp” indicates the jsp as the server side entity.
Q) Web
application in which, the end user enters 2 numbers into the web form. When clicked on the add button or subtract
button, appropriate result should be sent to the client.
Directory
structure
computeapp
numbers.html
compute.jsp
WEB-INF
web.xml
After deployment, type the following URL in the browser.
http://localhost:8080/computeapp/numbers.html
Source code
of numbers.html
<HTML>
<BODY >
<CENTER>
<H1>Numbers entry screen</H1>
<FORM ACTION="compute.jsp">
NUMBER ONE<INPUT TYPE="text"
NAME="t1"><BR>
NUMBER TWO<INPUT TYPE="text"
NAME="t2"><BR><BR>
<INPUT
TYPE="submit" NAME="click" VALUE="add">
<INPUT
TYPE="submit" NAME="click" VALUE="sub">
</FORM>
</CENTER>
</BODY>
</HTML>
compute.jsp
source code
<%
String
caption=request.getParameter("click");
int n1=Integer.parseInt(request.getParameter("t1"));
int
n2=Integer.parseInt(request.getParameter("t2"));
int result=0;
if(caption.equals("add"))
result=n1+n2;
else
result=n1-n2;
%>
<HTML>
<BODY BGCOLOR="yellow">
<H1> THE RESULT
IS:<%= result %></H1>
</BODY>
</HTML>
Source code
of web.xml
<web-app>
</web-app>
Observation
to be made
1.
In the HTML document, we need to
give same request parameter name for both add and sub buttons. Give different
captions.
2.
In the scriptlet, retrieve the 2
numbers and also the end user clicked
button.
Q) Web
application in which, a jsp performs database operations.
Directory
structure
databaseapp
emp.html
employee.jsp
WEB-INF
web.xml
After deployment, type the following URL in the browser.
http://localhost:8080/databaseapp/emp.html
Source code
of emp.html
<HTML>
<BODY BGCOLOR="cyan">
<CENTER>
<H1>Employee Details Query
Screen</H1>
<FORM
ACTION="employee.jsp">
EMPLOYEE NO<INPUT TYPE="text"
NAME="t1"><BR>
<INPUT
TYPE="submit"
VALUE="send"><BR>
</FORM>
</CENTER>
</BODY>
</HTML>
When the end user clicks on the button any one of the following screens
come.
Source code
of web.xml
<web-app>
</web-app>
Source code
of the employee.jsp
<%@ page import="java.sql.*" %>
<%!
Connection con;
public void jspInit()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:lnrao","scott","tiger");
}
catch(Exception
e)
{
e.printStackTrace();
}
}//jspInit()
public void jspDestroy()
{
try
{
con.close();
}
catch(Exception
e){}
}
%>
<%
int
eno=Integer.parseInt(request.getParameter("t1"));
String name=null;
float sal=0;
Statement
st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT * FROM EMPLOYEE WHERE
EMPNO="+eno);
if(rs.next())
{
name=rs.getString(2);
sal=rs.getFloat(3);
%>
<H1> EMPLOYEE
NAME:<%= name %></H1>
<H1>SALARY :Rs.
<%= sal %></H1>
<%
}
else
{
%>
<H1> EMPLOYEE NOT
FOUND</H1>
<%
}
%>
Q) Web
application in which a jsp makes use of a Java bean.
JspBeanApp
bookform.html
bookbean.jsp
WEB-INF
web.xml
classes
bookpack
Book.class
After the deployment of the
application, type the following URL.
When the end
user clicks on the button, the following output is shown
Source code
of the bean class
package bookpack;
public class Book
{
private int isbn;
private String title;
public void setIsbn(int
isbn)
{
this.isbn=isbn;
}
public int getIsbn()
{
return isbn;
}
public void
setTitle(String title)
{
this.title=title;
}
public String getTitle()
{
return title;
}
} //Bean class
jsp source
code
<HTML>
<BODY
BGCOLOR="WHEAT">
<CENTER>
<H3>ACCESSING BEAN
FROM THE JSP</H3>
<%@ page
import="bookpack.Book" %>
<jsp:useBean
id="book" class="bookpack.Book" scope="request" />
<jsp:setProperty
name="book" property="*" />
BOOK ISBN
:<jsp:getProperty name="book" property="isbn"
/><BR>
BOOK
TITLE:<jsp:getProperty name="book" property="title"
/>
</CENTER>
</BODY >
</HTML>
web.xml
source code
<web-app>
</web-app>
Q) Web
application in which a java bean is shared in request scope.
RequestScopeApp
emp.html
source.jsp
target.jsp
WEB-INF
web.xml
classes
rscopepack
Employee.class
After the web application is deployed, if the above URL is typed in the
browser, the following web form is displayed in the web client (browser).
Source code
of the emp.html
<HTML>
<BODY
BGCOLOR="pink">
<CENTER>
<H3>EMPLOYEE
DETAILS FORM</H3>
<FORM ACTION="source.jsp">
EMPNO<INPUT TYPE="TEXT"
NAME="empno" ><BR>
NAME<INPUT TYPE="TEXT"
NAME="name" ><BR>
<INPUT TYPE="submit"
VALUE="CLICK HERE">
</FORM>
</CENTER>
</BODY>
</HTML>
When the end user enters the empno, salary and clicks on the button, it
is received by the source.jsp. It instantiates the java bean and populates it.
It also keeps the bean in request scope. Now control is switched to the
target.jsp using forward standard action. target.jsp retrieves the employee
bean state and sends to the client.
source.jsp
<%@ page import="rscopepack.Employee" %>
<jsp:useBean id="emp"
class="rscopepack.Employee"
scope="request"/>
<jsp:setProperty name="emp" property="*" />
<jsp:forward page="target.jsp" />
target.jsp
<HTML>
<BODY
BGCOLOR="WHEAT">
<CENTER>
<%@ page
import="rscopepack.Employee" %>
<jsp:useBean
id="emp" class="rscopepack.Employee"
scope="request"/>
<H3>EMPLOYEE
DETAILS</H3>
EMPNO:<jsp:getProperty name="emp" property="empno"
/><BR>
NAME:<jsp:getProperty name="emp" property="name"
/>
</CENTER>
</BODY >
</HTML>
Q) Web
application in which a java bean is shared in session scope.
SessionScopeApp
userdetails.html
sessioncontroller.jsp
sessionvalues.jsp
WEB-INF
web.xml
classes
sessionpack
EmailBean.class
After the web application is deployed, if the above URL is typed in the
browser, the following web form is displayed in the web client (browser).
userdetails.html
<HTML>
<BODY
BGCOLOR="pink">
<CENTER>
<FORM
ACTION="sessioncontroller.jsp">
NAME<INPUT TYPE="TEXT"
NAME="username" ><BR>
MAILID<INPUT TYPE="TEXT"
NAME="email" ><BR>
<INPUT TYPE="submit"
VALUE="CLICK HERE">
</FORM>
</CENTER>
</BODY>
</HTML>
When the end-user clicks on the hyperlink, the following output
comes.
sessioncontroller.jsp
<HTML>
<BODY BGCOLOR="cyan">
<H2>BEAN SHARING AT SESSION LEVEL</H2>
<%@ page import="sessionpack.EmailBean" %>
<jsp:useBean id="mail"
class="sessionpack.EmailBean" scope="session" />
<jsp:setProperty name="mail" property="*" />
<A HREF="sessionvalues.jsp">CLICK HERE TO GET USER
DETAILS</A>
</BODY>
</HTML>
sessionvalues.jsp
<HTML>
<BODY BGCOLOR="cyan">
<H2>USER DETAILS</H2>
<%@ page import="sessionpack.EmailBean" %>
<jsp:useBean id="mail"
class="sessionpack.EmailBean" scope="session" />
USERNAME:<jsp:getProperty name="mail"
property="username" /><BR><BR>
EMAIL ID :<jsp:getProperty name="mail"
property="email" />
</BODY>
</HTML>
web.xml
<web-app>
</web-app>
Q) Web
application that is built using MVC architecture
mvcapp
emp.html
view.jsp
WEB-INF
web.xml
classes
beanpack
Employee.class
nit
servlets
ControllerServlet.class
http://localhost:8080/mvcapp/emp.html
source code
of emp.html
<HTML>
<BODY
BGCOLOR="cyan">
<FORM
ACTION="./mvc">
EMPLOYEE NUMBER<INPUT
TYPE="text"
NAME="eno"><BR><BR>
<INPUT
TYPE=SUBMIT VALUE="SENDEMPNO">
</FORM>
</BODY>
</HTML>
Source code
of web.xml
<web-app>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>nit.servlets.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/mvc</url-pattern>
</servlet-mapping>
</web-app>
source code
of the Java bean
package beanpack;
import java.sql.*;
public class Employee implements
java.io.Serializable
{
Connection con;
private int empno;
private String name;
private float salary;
public Employee()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.
getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
}
catch(Exception
e) {}
}
public void setEmpno(int
empno)
{
this.empno=empno;
results();
}
public int getEmpno()
{
return
this.empno;
}
public void
setName(String name)
{
this.name=name;
}
public String getName()
{
return
this.name;
}
public void setSalary(float
salary)
{
this.salary=salary;
}
public float getSalary()
{
return
this.salary;
}
public void results()
{
try
{
Statement s=con.createStatement();
ResultSet rs=s.executeQuery("select *
from employee where
empno="+empno);
rs.next();
name=rs.getString("name");
salary=rs.getFloat("salary");
}
catch(Exception
e){}
}
}//class
//source
code of the controller
package nit.servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import beanpack.Employee;
import java.io.*;
public class ControllerServlet
extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse
response)throws
ServletException,IOException
{
int empno=Integer.parseInt(request.getParameter("eno"));
Employee
ebean=new Employee();
ebean.setEmpno(empno);
getServletContext().setAttribute("ebean",ebean);
getServletContext().getRequestDispatcher("/view.jsp").forward(request,respo
nse);
}
}
// source
code of the view (view.jsp)
<HTML>
<BODY>
EMPLOYE
DETAILS<BR><BR>
<%@ page import="beanpack.Employee" %>
<jsp:useBean id="ebean"
class="beanpack.Employee" scope="application" />
EMPNO:<jsp:getProperty
name="ebean" property="empno"/><BR>
NAME:<jsp:getProperty
name="ebean" property="name"/><BR>
SALARY:<jsp:getProperty name="ebean"
property="salary"/>
</BODY>
</HTML>
Q) Web
application to implement a custom tag
customtagapp
hello.jsp
WEB-INF
web.xml
tld
ourtaglib.tld
classes
hellopack
HelloHandler.class
Source code
of hello.jsp
<HTML>
<BODY
BGCOLOR=WHEAT>
<%@ taglib
prefix="nit"
uri="http://www.nit.com/customtags" %>
<H3>
<nit:hello />WELCOME TO CUSTOM TAGS</H3>
</BODY>
</HTML>
source code
of web.xml
<web-app>
<taglib>
<taglib-uri>
http://www.nit.com/customtags
</taglib-uri>
<taglib-location>
/WEB-INF/tld/ourtaglib.tld
</taglib-location>
</taglib>
</web-app>
source code
of ourtaglib.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>nit</short-name>
<tag>
<name>hello</name>
<tag-class>hellopack.HelloHandler</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Tag handler
source code
package hellopack;import javax.servlet.jsp.*;import
javax.servlet.jsp.tagext.*;
import java.io.*;
public class HelloHandler extends TagSupport
{
public int doStartTag()
throws JspException{
try
{
JspWriter
out=pageContext.getOut();
out.println("hello");
}
catch(IOException
e){System.out.println(e);}
return
SKIP_BODY;
} }
Q) Web
application to implement a custom tag with attributes
Tag handler
source code
package greetpack;
import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;
import java.io.*;
public class GreetingHandler extends TagSupport
{
private String name; private int age;
public void
setName(String name)
{
this.name=name;
}
public void setAge(int
age)
{
this.age=age;
}
public int doStartTag()
throws JspException
{
try
{
spWriter
out=pageContext.getOut();
out.println("Hello
"+name+" you are "+age+" years old");
}
catch(IOException
e){System.out.println(e);}
return
SKIP_BODY;
}
}
jsp source
code
<HTML>
<BODY BGCOLOR=WHEAT>
<%@ taglib prefix="nit"
uri="http://www.nit.com/customtags" %>
<H2><nit:greet
name="Ram"
age="35" /></H2>
</BODY></HTML>
tld source code
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>nit</short-name>
<tag>
<name>greet</name>
<tag-class>greetpack.GreetingHandler</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>age</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
web.xml
source code
<web-app>
<taglib>
<taglib-uri>
http://www.nit.com/customtags
</taglib-uri>
<taglib-location>
/WEB-INF/tld/ourtaglib.tld
</taglib-location>
</taglib>
</web-app>
Q) Web
application on IterationTag implementation
iterateapp
loop.jsp
WEB-INF
web.xml
tld
mytaglib.tld
classes
iterationpack
IterationTagHandler.class
After deploying the web application, we have to type the following URL
in the browser.
Tag handler
source code
package iterationpack;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class IterationTagHandler extends TagSupport
{
private int count;
public void setCount(int
count)
{
this.count=count;
}
public int doStartTag()
throws JspException
{
if(count>0)
return
EVAL_BODY_INCLUDE;
else
return SKIP_BODY;
}
public int doAfterBody()
throws JspException
{
if(--count>0)
return
EVAL_BODY_AGAIN;
else
return
SKIP_BODY;
}
}
jsp source
code
<HTML>
<BODY BGCOLOR="pink">
<%@ taglib prefix="nit" uri="customtags" %>
<nit:iterate count="5">THIS IS EVALUATED
REPETITIVELY</nit:iterate>
</BODY>
</HTML>
tld source
code
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>nit</short-name>
<tag>
<name>iterate</name>
<tag-class>iterationpack.IterationTagHandler</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>count</name>
<required>true</required>
</attribute>
</tag>
</taglib>
web.xml
source code
<web-app>
<taglib>
<taglib-uri>
customtags
</taglib-uri>
<taglib-location>/WEB-INF/tld/mytaglib.tld</taglib-location>
</taglib>
</web-app>
When the request comes to the jsp, the body of the tag is evaluated 5
times and the body will be displayed to the client.
TagSupport class implements IterationTag interface. IterationTag
interface has one constant and one life cycle method.
IterationTag.EVAL_BODY_AGAIN
int doAfterBody()
After the body of the custom tag is evaluated once, container calls
doAfterBody() method. This method can return any one of the following two constants.
1.
Tag.SKIP_BODY
2.
IterationTag.EVAL_BODY_AGAIN
As long as the doAfterBody() method returns the EVAL_BODY_AGAIN
constant to the container, it evaluates
the body of the custom tag and then calls the doAfterBody method. Therefore
iteration occurs. Once our requirement of iteration is fulfilled, we return
SKIP_BODY constant to the container. Now doAfterBody method is not called.
Instead, doEndTag method is called.