Sie sind auf Seite 1von 250

Session Tracking

Mechanism of Http Protocol


The communication between web browser and web server by
http protocol will be done like the following
1) When a client request is made then http protocol opens a
socket connection with a server internally
2) Http protocol transfer values from browser side to server side
3) After processing is done at server side, the values are
transferred from server to browser
4) Http protocol closes the socket connection
) The above 4-steps are repeated fro each request made from a
browser

Stateless behavior
When a client request is made to a server then server reads
client data and process the request, after that the response will
be send back to the client
Once response is given back to the client, a server doesnt
remember any data of the client. So when same client is
sending another request to server then server doesnt recognize
that client
This behavior is called as stateless behavior
In a stateless behavior, a server feels that each request made
by a new client

Stateful behavior
When a client request is made to a server then a server store
data of the client and whenever the same client is visiting
again to the server then server recognize a client
This behavior is called as stateful behavior

Session Tracking
Http protocol by default behaves like a stateless protocol. But
in some applications, we need statteful behavior. To convert
the http protocol behavior from stateless to stateful we apply a
mechanism called session tracking.
Session tracking is a combination of session management
and state management
Session management is nothing but identifies a client whether
is a old or a new and state management is nothing but
remember the values of client at server side

How Session Management works?


When a client request is made to a server then server first
checks whether a client is an old client or a new client by
identifying a token
If there is no token in the client request then server identifies
the client as new and generates a new token and after that the
token will be sent to the client along with a response
When the same client is next time visiting server then along
with the request the token will also be sent to the server.
So a server identifies the client as an existing client

Session Management
request-1

token

response+token
Request(2)+token
response
Client-1
Server

How State Management Works


State management refers to remembering a client data in a server
In order to remember a client data in a server, at server an object will
be created for each new client
If a server remember a client data then a response for a request of a
client, can be constructed by depending on not only the current
values but also depending on previous values of the client
In order to remember a client data in a server, for each new client
one object will be created and the data will be stored in that object
until the client logout from the server
Whenever a client request is made to server for first time then at
server side a token and an object both are generated for a client.
Here token for session management and object for state management
The number of clients connected with a server is equal to the number
of tokens generated by the server and it is equal to number of objects
created for storing the data

State Management

client-1

session object
to store client-1
data

session object
to store client-2
data

client-2

Session Tracking Techniques


The following four techniques are used to fulfill session tracking
mechanism
1) HttpSession Interface
2) Hidden Form Fields
3) Cookies
4) URL Rewriting

HttpSession Interface

HttpSession Interface
In servlet api, HttpSession interface contains a method called
getSession() and this method contains the logic of creating
session-id and session-object
We have getSession() method in two flavours
1) getSession()
2) getSession(boolean)
) When we call getSession() it returns an associated sessionobject of a client
) getSession() contains logic of verifying whether a client who
send the request is containing a session-id or not and also
contains logic for creating new session-id and session-object
) When we call getSession() then it internally calls
getSession(true)

HttpSession Interface
The logic of getSession(true) is, it checks whether the given
request is associated with a session-id or not.
If yes then identifies the client as an existing client and returns
the associated session-object
1) HttpSession session=request.getSession();
2) HttpSession session=request.getSession(true);
) getSession(false) verifies whether a client who send this
request is associated with a session-id or not, if contains then,
it returns the associated session-object, if not contains then
returns null.
) It means, getSession(false) method doesnt generate any new
session-id and session-object
1) HttpSession session=request.getSession(false);

HttpSession Interface
In HttpSession interface technique, a session-id is transfer
between a client and server in the form of cookie
When a response is send to a client then along with response a
cookie will be added for the response, which contains sessionid and this cookie will be transfer from a server to a client
When a client is sending next request to a server then along
with request the cookie which contains session-id will also be
transfer to the server with the help of this cookie a server will
identify a client

Storing and sending data in Session object


If you want store or read the data in session-object then it will
in the form of attributes, it means a session object stores data
in key-value pair
In order to store or read data of a session-object then we need
to use the following four methods
1) setAttribute(key, value)
2) getAttribute(key);
3) removeAttribute();
4) getAttributeNames();
) The above methods are some times called as state management
methods of HttpSession

Methods of HttpSession interface


getId()
This method returns a session-id associated with a session-object
String str=session.getId();
isNew()
This method is to know the state of a session object that is, whether a
session is new or old
If the session is new then a client is a new client and if the session is
old then the client is old client
if(session.isNew())
{
//logic-1
}
else
{
logic-2
}

Methods of HttpSession interface


getMaxInactiveInterval()
This method return maximum waiting time allowed between a
request and next request
If the time gap exceeds the maximum inactive interval then the
server will automatically discord/remove/destroy a client
session
The inactive interval time varies from one server to another
server.
This method returns inactive interval time in seconds
long seconds=session.getMaxInactiveInterval();

Methods of HttpSession interface


setMaxInactiveInterval()
This method is used to set a session expire time explicitly
By default, each session generated by the container will have
some expire time
As a programmer, we can set/change the expire time for a
session in following 2-ways
1) Programmatically
2) Declaratively
) If we want to set programmatically then we need to call
setMaxInactiveInterval() method by passing input value in
seconds
session.setMaxInactiveInterval(10);

We can also set a session expire time declaratively through


web.xml file like,
<session-config>
<session-timeout>15</session-timeout>
</session-config>
If we set expire time for a session in both programmatic and
declarative approaches then programmatic value will be
considered

Difference between Programmatic and Declarative approaches

In programmatic approach we can set minimum expire time


for a session as one second. In declarative approach we can set
a minimum expire time for a session as one minute
In programmatic approach we can set a session expire time in
each servlet differently. But in declarative approach, the expire
time will be commonly applied for all servlets

In programmatic or declarative approach, if we set a session


expire time as ve value then that session doesnt expire until
it is explicitly invalidated
In order to expire a session explicitly then we need to call
invalidate() method
When we sign-out/logout from website then internally
invalidate() method is called to expire a session of a client

HttpSession interface methods


getCreationTime()
This method is used to get a session creation time.
This method returns milliseconds
These milliseconds are calculated from 1970,Jan-1,00:00
hours
We can convert these milliseconds into system date and time
format by using java.util.Data class
long ms=session.getCreationTime();
java.util.Date d=new java.util.Date(ms);
out.println(d.toString());

HttpSession interface methods


getLastAccessedTime()
This method is used to read last request/accessed time by a
client with a session. It returns milliseconds
These milliseconds are calculated from 1970,Jan-1,00:00
hours
For first request and second request both creation time and last
accessed time both are one and same
From third request by a client, creation time and last accessed
time will be different
long ms=session.getLastaccessedTime();
java.util.Date d=new java.util.Date(ms);
out.println(d.toString());

Cookie Class

Cookie Class
Cookie class is given in javax.servlet.http package
Generally, a cookie is defined as an object which
contains/stores text information in the form of key-value pair,
created on server and stored on browser
In servlet api, we create cookie class objects for client data and
these cookies are transferred from server to browser and
browser to along with that client
Cookies are only for state management and but not for session
management. So cookies are for particial session tracking in
web applications
With the help of cookies, it is possible to transfer previous data
of client also along with current data from a browser to a
server. So that server can access both current data and also
previous data of client

Cookie Class
While working with cookies the programmer is responsible to
create the cookies and the programmer is responsible to send
cookies to browser and also to read cookies from browser
The cookies which are created by the programmer are called
data cookies. In order to create data cookie, we need Cookie
class of servlet api
While working with HttpSession technique, internally sessionid will be transferred between a server and a client in the form
of a cookie. But this cookie is a container generated cookie
and the container is responsible to transfer this cookie on to
the browser
While creating cookie, we are responsible to pass name and
value into a cookie object

Cookie class
Syntax:
Cookie c1=new Cookie(String name, String value);
If any cookies are created explicitly then the servlet
programmer is responsible to transfer the cookies from a
server to browser explicitly.
To transfer a cookie from a server to browser it must added to
the response object by calling addCookie() method
Response.addCookie(c1);
When a request is given from a browser, then a browser
automatically transfers cookies also to the server. In a servelet,
to read these cookies, we need to call getCookies() method of
HttpServeltRequest interface
Cookie coo[]=request.getCookies();

Types of Cookies
1) In-Memory Cookie
2) Persistance Cookie
In-memory Cookie
) By default whenever a new cookie is created then it is an inmemory cookie
) An in-memory cookie will be alive on browser until that
browser is closed
) The in-memory cookie contains its expire time as -1

Types of Cookies
Persistance Cookie
For a cookie, if we set some expire time then that cookie
becomes as a persistance cookie
A persistance cookie will be alive on browser until its expire
time is reached
A persistance cookie will not removed from a browser even
though the browser is closed

Methods of Cookie class


setValue()
This method is used to modifies the values stored in cookie
object
Once a cookie object is created, then its name cant be
modified(key) but its value can be modified
Cookie c1=new Cookie(user,talent);
Key is user and Value is talent
c1.setValue(Java);
Now Key is user and Value is Java

Methods of Cookie class


getName() and getValue()
These methods are used to read key and value stored in a
cookie object
Cookie c1=new Cookie(ram, java);
String s1=c1.getName();
System.out.println(s1); //ram
String s2=c1.getValue();
System.out.println(s2);

Methods of Cookie Class


setMaxAge() and getMaxAge()
These methods are used to set expire time and used to read
expire time respectively
If we want to change a cookie in-memory to persiatance then
we need call setMaxAge() method
By reading expire time of a cookie, we can identifies whether
it is in-memory or a persistance cookie
Cookie c1=new Cookie(ram,java);
c1.setMaxage(120); //seconds
long k=c1.getMaxAge();
if(k==-1) in-memory cookie
else
persistance cookie

Methods of Cookie class


setComment() and getComment()
These methods are used to set a comment for a cookie and also
to read a comment of a cookie respectively
Cookie c1=new Cookie(ram,java);
C1.setComment(This is Ram Cookie);
String s1=c1.getComment();
System.out.println(s1); //This is Ram Cookie

JSP

Limitations of Servlets
Servlet need huge amount of java code to implement business
logic
In a servlet both business logic and presentation logic
combined. So a java developer must be know html also
A servlet is a java class file, so if any modifications are done
on it then we must recompile, reload the application and
sometimes we need to restart the server
In servlets, we dont have implicit objects support

What is JSP?
A JSP is a web page, resides on a server and provides dynamic
presentation on browser
A JSP is page, looks like on HTML page, the difference is
HTML can produce only static content, but a JSP can produce
dynamic content
JSPs are called pages rather than programs because a JSP
contains every thing in the form of a tag
JSPs are pages, written by authors

Difference between a Servlet and JSP


Servlets

Jsp

Servlet need huge amount of java code to A Jsp need less amount of java code to
implement business logic
implement business logic
In a servlet both business logic and In Jsp, we can separate presentation logic
presentation logic combined. So a java from business logic. So, a programmer
developer must be know html also
may not be html designer
A servlet is a java class file, so if any
modifications are done on it then we must
recompile, reload the application and
sometimes we need to restart the server

In Jsp, it is a page so if any modification


are done then no need to recompile or
reload or restart the server. Instead, we
need to refresh to page on broser

In servlets, we dont have implicit objects In a Jsp, we have implicit objects


support
A servlet doesnt manage a session by A Jsp by default maintains sessions. If we
default. Explicitly we need to enable dont require them then we can disable
sessions
them
In a servlet, we have to write all import In Jsp, we can insert import statements at
statements on top of the servlet
any where in the page

Contents of JSP Page


1) Ordinary text (template text)
2) Html tags
3) Jsp tags
) Ordinary text and Html tags will produce static content and
Jsp tags will generate dynamic content
) A Jsp is a server side resource. It means a jsp executes at
server side and its response will be constructed in the form of
web page and that web page is delivered to web client
>
) Html tags are enclosed with in <
%>
) Jsp tags are enclosed with in <%

Jsp Execution
At server side, 2-phases are executed for a Jsp
1) Translation Phase
2) Request Processing Phase
) Translation phase means, translating a jsp into equivalent
servlet and then generating a .class file
) Request processing phase means, executing service() method
for a given request and generating response to the client
) Translation doesnt occur for each request. But request
processing occurs for each request
) Translation occurs in the following 2-cases
1) When a first request is arrived to a jsp
2) When request arrived after modification of a jsp

First Request
First Request Received by Jsp
http://localhost:8080/app1/one.jsp

request

compiler

translator

one.jsp

one_jsp.java

response

one_jsp.class
object
_jspService(
-,-)
{
---------

Next Request on wards

http://localhost:8080/app1/one.jsp

request
one.jsp

response
object
_jspService(
-,-)
{
---------

Jsp pages are not compiled by the developers explicitly. But t


server side, a web container will do jsp compilation. It means
a jsp also need compilation, because a jsp is internally
converted to a servlet
A web container uses a page compiler(translator), to convert
a .jsp file into .java file
For example, catelina is a web container of tomact, uses a page
compiler called jasper, to translate a .jsp into a .java file
After converted to .java file, container uses javac and
generate .class file
To identify whether a jsp is like a previous executed jsp or any
modifications done on it, a web container uses file comparison
tools. In tomact catalina uses araxis tool for identification

A jsp is executed in a server, if we shutdown a server then the


object created for a jsp will be removed from the server. But
the .java and .class files are not removed
If we restart the server and if you again give a request to a jsp
then the container creates an object for existing class and
invokes its life cycle and then provides the response back to
the client
If you shutdown and restart the server then again translation
phase for a jsp will not be executed
If we remove .class file and if you give request to a jsp then
partial translation occurs and again a new .class file created
and the request processing will be executed
We can modify the source code of an internal servlet created
by the container for a jsp. In this case to execute the modified
code also, either we need to explicitly compiled or we need to
remove .class file

Jsp Life Cycle


1) Jsp is translated to a servlet
2) The servlet is compiled
3) The servlet is loaded into memory
4) An object is created for the servlet
5) jspInit() method is called
6) _jspService(-,-) method is called
7) jspDestroy() method is called
(above steps are divided into 4-phases )
) When a jsp is converted to a servlet, the servlet class extends a
base class provided by the container. That class extends from
HttpServlet class. So we can say that the internal servlet is an
HttpServlet
) A jsp can handle only http protocol request

JSP life cycle can be divided into four phases: Translation,


Initialization, execution and finalization.
Translation
In the translation phase, JSP engine checks for the JSP syntax
and translate JSP page into its page implementation class if the
syntax is correct. This class is actually a standard Java servlet.
After that, JSP engine compiles the source file into class file
and ready for use.
If the container receives the request, it checks for the changes
of the JSP page since it was last translated. If no changes was
made, It just loads the servlet otherwise the process of check,
translate and compile occurs again. Because the compilation
process takes time so JSP engine wants to minimize it to
increase the performance of the page processing.

Initialization
After the translation phase, JSP engine loads the class file and
create an instance of the servlet to handle processing of the
initial request.
JSP engines will call a method jspInit() to initialize the a
servlet. jspInit method is generated during the translation
phase which is normally used for initializing application-level
parameters and resources.
You can also overide this method by using declaration.
<%!
public void jspInit(){
// put your custom code here
}
%>

Execution
After the initialization phase, the web container calls the
method _jspService() to handle the request and returning a
response to the client.
Each request is handled is a separated thread.
Be noted that all the scriptlets and expressions end up inside
this method.
The JSP directives and declaration are applied to the entire
page so the are outside of this method.

Finalization
In the finalization phase, the web container calls the method
jspDestroy().
This method is used to clean up memory and resources.
Like jspInit() method, you can override the jspDestroy()
method also to do your all clean up such as release the
resources you loaded in the initialization phase....
<%!
public void jspDestroy(){
// put your custom code here
// to clean up resources
}
%>

Jsp Life Cycle


The life cycle methods of jsp are provided by HttpJspPage
interface. This interface is part of JSP api and it is given in
javax.servlet.jsp.*; package
HttpJspPage is exentended from JspPage interface and it has
provide two life cycle methods called jspInit() and
jspDestroy()

Jsp Tags (Elements)


Jsp tags are divided into the following
1)Scripting Tags
declaration, expression, scriptlets
2)Directivies
Include, page, taglib
3)Stand Actions
<jsp:forward> <jsp:include> <jsp:param> <jsp:params>
<jsp:plugin> <jsp:fallback> <jsp:useBean> <jsp:setProperty>
<jsp:getProperty>
4)Custom Tags

JSP Scripting Elements


JSP scripting elements enable us to insert java code
into JSP files.
There are three types of elements
Expressions <%= Java Expression %>
Scriptlets <% Java Code %>
Declarations<%! Field/Method %>

JSP declaration tag


This tag is used for define variables and creating methods in a jsp page
If we define any variable or methods then these variables and methods will become
instance variables and instance methods of the internal servlet class
This tag starts with <%! and ends with %>
Syntax: (html format)
<%! Instance or global variables
define method
%>
Syntax: (xml format)
<jsp:declaration>
Instance or global variables
define method
</jsp:declaration>
The variables defined in this tag will become global to the entire jsp. It means we can use
those variables at every where in the jsp
The declaration tag will be executed for only once but not for each request
The code inserted into declaration will be placed into servlet class during translation time

JSP declaration tag


<% !
int count=0;
count=conut+1;;
%>
First request count=1
Second request count=1
Third request count=1
..
..
nth request count=1
(declaration1.jsp)

JSP declaration tag


In declaration tag we can override jspInit(0 and jspDestroy() methods.
_jspService(-,-) override is not possible. _jspService(-,-) always written
by the container
<%!
public void jspInit()
{
.
.
}
public void jspDestoroy()
{
.
.
}
%>

JSP declaration tag


In a jsp, the only one tag which allows jsp programmers to define
methods is declaration tag
If we define a method in a declaration tag then it can be called from
any number of times from an expression tag and scriplet tag of jsp
(declaration2.jsp)
We cant use implicit objects of a jsp in declaration tag. Because the
declaration tag code goes out of _jspService(-,-) method
<%!
public int add(int a, int b)
{
out.println(inside add());
return(a+b);
}
%>

JSP declaration tag


For scripting elements of a jsp, nesting of tags ate not allowed
<%!
.
.
<%!

%>
%>
The code is an error because nesting is not allowed
<%!
.
.
<%

%>
%>
It is an error because insert one scriptnig element into another scripting element is wrong

Examples on declaration tag


declaration1.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%!
int count=0;
Int count1=count+1;
%>
<%= count1 %>

Examples on declaration tag


declaration2.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%!
public int add(int a, int b)
{
return(a+b);
}
int c;
%>
<%=
c=add(10,20)
%>
<%
int x=add(25,35);
out.println(x);
%>

JSP Expressions
An expression tag is used for evaluating the given expression and
then printing or displaying result on to the browser
Each expression tag will be internally converted to out.println()
method statements during translation time and then that statements
will be inserted into _jspService() method
Expression tag will be executed for each request, because an
expression tag goes inside of _jspService() method
We can use implicit objects of jsp in an expression tag. Because its
code goes into _jspService(0 method
A JSP expression is used to insert java code directly into the output.

JSP Expression
Syntax
<%= Expression %> (html syntax)
<jsp:expression > expression </jsp:expression> (xml syntax)

Eg:
Current Time: <%= new java.util.Date() %>
Output:
Current Time: Tue Aug 22 21:05:47 IST 2006
The expression is evaluated, converted to string and inserted into
the page.

Jsp Expressions
Example
1) <%=a+b,a-b%> out.print(a+b,a-b) //invalid
2) <%=a+b+ +a-b%> out.print(a+b+ +a-b)//valid
3) <%=this.a*this.b %> out.print(this.a*this.b);
4) <%=this.a+page.a%> out.print(this.a+page.a);
page.a equls this.a
5) <%=a+b;%>out.print(a+b;); //invalid
6) <%=a,b%>out.print(a,b);//invalid
7) <%= request.getParameter(uname)%>
out.println(request.getParameter(uname));

Jsp Expressions example


<%@ page language="java" contentType="text/html;
charset=ISO-8859-1 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%!
int a=100;
int b=200;
%>
<%= "Sum="+(a+b) %>

JSP Scriptlets
This tag is used for inserting some java code into a jsp page
and this java code goes into _jspService(-,-) method. So the
code implemented in a scriplet tag is executed for each
request.
In a scriplet tag we can declare variables. These variables are
called local variables because the scriplet code goes into
_jspService(-,-) method
We cant define methods in a scriplet tag, but we can call the
methods defined in a declaration tag
A scriplet starts with <% and ends with %>

5/
12
/1
5

JSP Scriptlets
Syntax:
<% Java Code %> (html synatx)
<jsp:scriplet> java code</jsp:scriplet> (xml syntax)
Eg:
<%
String str = request.getParameter(name);
out.print(Name : +str);
%>

JSP Scriptlets
<%
int sum(int a, int b)
{

}
%>
The above code is invalid

Jsp Scriplet
<%!
int sum(int a, int b)
{
return (a+b);
}
%>
<%
int k=sum(10,20);
%>
The above code is correct

Jsp Scriplet
We can create a variable with same name in declaration tag
and also in a scriptlet tag. Because declaration tag variables
goes to out of _jspService(-,-) and scriplet tag variable goes to
inside of _jspService(-,-)
<%!
int x=100;
%>
<%
int x=50;
%>
<%= x %>
<%= this.x %>

Comments in Jsp
Html Comments
Jsp Comments
Java Comments
Html comments startsswith <!- - and end with - - >
Example: <!- - one.html- ->
A Jsp comment starts with <% - - and ends with - -%>
Example: <%- -one.jsp - -%>
We cant write any type of comment in an expression tag
We call jsp comments as hidden comments. Because these
comments are not visible in internally generated servlet source
code

Important Points
The internally generated servlet file is located at
C:\tomact6.0\work\catellina\localhost\jsp1\org\apache\jsp
If we open the source code of servlet and if we modify the
source code then the changes are not effected on the browser
If we want to make the changes effected on browser we are
responsible compile it manually. To compile it we need to set
the following 3-jar files
1) Servlet-api.jar
2) Jsp-api.jar
3) Jasper.jar

Html to Jsp Communiaction


While communicating from a html to jsp, either we can use jsp
filename or url pattern of jsp as a form action
If jsps configured in web.xml then we can put its url pattern
otherwise we can put its name directly in form action

Jsp Dirctives
Directives will provide information to containers, during
translation time and execution time
Directives will give direction to a container, during translation
time and execution time about how to ok work this this jsp page
For example, a directive informs the container that, if any
exception is occurred in the current jsp execution, then move
the control to some other jsp
We have 3-directives in jsp
1) include
2) page
3) taglib
) Taglib directive is used while working with custom tage and
JSTL

include Directive
This directive is for including source code of one jsp into
another jsp
At translation time only destination file source code will be
included in the servlet of source file. It means the page
compiler generates a single servlet internally for both source
file and destination file
We also called this include directive as a static including.
Because the inclusion is done at translation time only, not at
request processing time

include Directive
Syntax:
<%@ include file=destination file name %> (html syntax)
<%@ include file="b.jsp" %>

a.jsp(source)

b.jsp(destination)

< jsp:directive directive-name attributes /> (xml syntax)

include Directive
In a jsp, we can include any number of destination pages or we
can call include same destination page for number of times
Include directive reduces number of servlet objects in a server
because internally a single servlet will be generated for both
source and destination pages. It means include directive
reduces burden on a server

page Directive
This directive is used for setting important behavior for a jsp like session
management, buffer, MIME types, imports exceptions handling etc.,
Syntax:
<%@ page attributes %>
Attribute values
1) language
2) import
3) session
4) errorPage
5) isErrorPage
6) isThreadSafe
7) buffer
8) autoFlush
9) contentType
10) extends
11) info
12) isELIgnored

language Attribute
This attribute is used to set scripting language for jsp tags
The default value and the only one available value for this
attribute is java
This attribute is added to set language name, when multiple
languages are supported by a jsp
< %@ page language=java %>

import Attribute
This attribute is used to execute a predefined or an user
defined packages into a jsp apge
There is no default value for this attribute
We can import either a single or multiple packages at a time
into our jsp using this import attribute
< %@ page import=java.lang.* %> (single)
< %@ page import=java.lang.*; java.sql.* %>(multiple)
In a jsp a package can be imported anywhere it means in a jsp
there is no rule that all packages must be imported at top of the
jsp
During translation, the page compiler assimilates all imports from
jsp page and places them at top of the internal servlet

import Attribute
We can repeat import attribute for any number of times with in
a jsp page with different values
< %@ page import=java.lang.* %>
.

< %@ page import=java.sql.* %> (single)


..
...
< %@ page import=java.io.* %> (single)
.
.

import Attribute
The difference between other attributes of the jsp page
directive and import attribute is, we can repeat other attributes
also in a jsp, but the attribute value should same.
Where as, incase of import we can repeat for any number of
times with different values

session Attribute
This attribute is used to either enable or disable a session
management in a jsp
The default value of this attribute is true. It means by default
every jsp participate in session tracking
If we want to disable session tracking in a jsp then we need to
make session=false
If a jsp participating is session tracking then only an implicit
object called session is available to the jsp, otherwise we cant
use session object in jsp
If session object is available then we can get session and state
information from a session object by calling methods on it

session Attribute
Example1:
< %@ page session=true %>
Session Id Is:<%=session.getId()%>
Expire Time Is:<%=session.getMaxInactiveInterval() %>
Example2:
Session Id Is:<%=session.getId()%>
Expire Time Is:<%=session.getMaxInactiveInterval() %>
The above 2-jsps are one and same because by default a session
attribute is true only

errorPage attribute
This attribute is used to inform the container that, if any
exception is occurred while executing a jsp then move the
control to other jsp page, instead of printing exception stack
trace on a browser
In a jsp exception handling can be done either locally or
globally
If we add errorPage attribute for page directive in a jsp then it
is called local exception handling in jsp
If <error-page> tag is added in web.xml then it is called global
exception handling
Example
<%@page errorPage=b.jsp%>

isErrorPage Attribute
This attribute is used to inform the container whether a jsp is
acting as an errorPage or not
The default value of this attribute is false. It means by default
a jsp doesnt act as an errorPage
To make a jsp as an errorPage then we need to make
isErrorPage=true
If a jsp is acting like an errorPage then only the implicit object
exception is available in that page

isThreadSafe Attribute
This attribute is used to inform the container, whether multiple
threads are allowed to access the jsp or not
The default value of isThreadSafe is true. It means multiple
threads are allowed simultaneously to access the jsp
If we make isThreadSafe=false then container allows only a
single thread at a time to access a jsp
If we make isThreadSafe=false then at the time of translation,
the container implements internal servlet class from
SingleTHreadModel interface
<%@ page isThreadSafe=false %>

buffer Attribute
This attribute is used to set the buffer size used by JspWriter
class
The default value of this attribute is 8kb. But we can increase
or decrease or remove the buffer
In jsp, the implicit object out is an object of JspWriter class,
and it writes the response data into buffer, before writing it
into the response object
In case of PrintWriter, it directly writes the response data into
response object, by without using any buffer (below)
out.println(.)
out.println(.)
response object
out.println(.)

buffer Attribute
In Jsp
out.println(.)
out.println(.)
out.println(.)

buffer

response object

JspWriter is a derived class of PrintWriter and uses buffer


If buffer is removed then both JspWriter and PrintWriter
becomes equal
If buffer is used then performance is increased because very
time no need of hitting response object
To make JspWriter and PrintWriter as equal, we use
buffer=none
<%@ page buffer=none%>

autoFlush Attribute
This atribute is used to transfer the data stored in a buffer into
response object. We call this operation as flushing
The default value of this attribute is true. It means
automatically flushing will be done when the buffer is full
If we make autoFlush=false then we need to explicitly call
out.flush(), to transfer the data from buffer to response object
If autoFlush=false and if out.flush() is not called then when
the buffer is full then container throws an exception
If buffer is none then we should not make autoFlush=false

contentType Attribute
This attribute is used to set MIME(Multipurpose Internet Mail
Extension) type for response
Default value of this attribute is text/html
In a jsp, we can set MIME type in 2-ways
1) By using scriplet with response object
<% response.setContentType(text/html) %>
2)By using page directive
<%@ page contentType=text/html%>
Note: If we set in both ways with different MIMIE types then
container throws an exception

extends Attribute
This attribute is used to inform the container that extends the
internal servlet class of jsp from our user defined class
In order to specifie our user defined class name, first of all we
need to crate our class by extending HttpServlet and by
implementing from HttpJspPage interface
<%@ page extend=MyServlet%>
MyServlet extends from HttpServlet and implements from
HttpJspPage which is extends from JspPage

info Attribute
This attribute is used to write some description about a jsp
We can also write description in a comment, but a comment cant be
read but a info can be read
If we add info attribute for page directive then at translation time, the
container inserts a method getServletInfo() in internally generated
servlet class
In a jsp page, we can read the description added for info attribute ether
in a scriplet or in an expression by calling getServletInfo() method
<%@ page info=This is a.jps%>

<%String s=getServletInfo();
out.println(s);
%>

isELIgnored Attribute
This attribute is used either enable or disable expression
language in jsp
The default value of this attribute is true it means expression
language is ignored by default
To enable expression language in a jsp then we need to make
isELIgnored=false
<%@ page isELIgnored=false %>

page directive total attributes


S.NO

ATTRIBUTE NAME

DEFAULT VALUE

language

Java

import

No default value

session

true

errorPage

No default value

isErrorPage

false

isThreadSafe

true

buffer

8kb

autoFlush

true

contentType

Text/html

10

extends

No default value

11

Info

No default value

12

isELIgnored

true

Standard Actions
Jsp developers given commonly required functionalities for
jsp programmers while developing jsp pages in the form of
standard actions
Standard actions will reduce burden on jsp programmer
because a programmer no need to implementing java code for
that functionality
Standard actions separates business logic from presentation
logic of the jsp
Each standard action contains fixed logic and input values are
required to execute that logic those values are accepted from
jsp programmer
Standard actions doesnt contain html syntax. Contains only
xml syntax

Standard Actions
1)
2)
3)
4)
5)
6)
7)
8)
9)

<jsp:forward>
<jsp:include>
<jsp:param>
<jsp:params>
<jsp:plugin>
<jsp:fallback>
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>

<jsp:forward>
While developing web application, suppose huge amount of
code is required in a file, then instead of writing total code in
one page we divide that code into multiple pages and then
transfer the request from one page to another page we need to
use forwarding technique
For forwarding technique, we use <jsp:forward> standard
action. This tag forwarding a client request from source to a
destination
When forwarding from a source to a destination, the
destination can be either a servlet or a jsp or a html
This standard action contains a single attribute called page

<jsp:forward>
To forward to jsp
<jsp:forward page=b.jsp/>
To forward to servlet use servlet url-pattern
<jsp:forward page=/serv/>
To forward to html file
<jsp:forward page=two.htm/>
While forwarding, the source and destination resources may
be in same web application or at different web application but
must be in same server it means forwarding is not possible
across the servers
If destination is available in some other web application of
same server then we need to pass url as a value of page
attribute
<jsp:forward page=/webappliaction2/b.jsp/>

<jsp:param>
While forwarding a request from a jsp to a destination using
<jsp:forward> tag, it is possible to ass some parameters also
from source to a destination along with a request.
If we want to add parameters while forwarding then we need
to use <jsp:param> as a sub element of <jsp:forward> tag
Example
a.jsp
<jsp:forward page=b.jsp>
<jsp:param name=p1
value=100/>
</jsp:forward>

b.jsp
<%
String
s1=request.getParameter(p1);

.
%>

<jsp:param>
a.jsp

<% int c=a+b; %>


<jsp:forward
page=b.jsp>
<jsp:param name=p1
value=c/>
</jsp:forward>
In above code c character
goes to b.jsp not c-vale

a.jsp

<% int c=a+b; %>


<jsp:forward
page=b.jsp>
<jsp:param name=p1
value=<%=c
%>
</jsp:forward>
In above code c value
goes to b.jsp dynamically

<jsp:params>
While forwarding a request, we can also add more than one
parameter. For this, we need to use <jsp:params> tag
a.jsp
<jsp:forward page=b.jsp>
<jsp:params>
<jsp:param name=p1
value=100/>
<jsp:param name=p2
value=200/>
</jsp:params>
</jsp:forward>

b.jsp
<%
String s1=request.getParameter(p1);
String s2=request.getParameter(p2);

%>

<jsp:param> and <jsp:params> standard actions must be used


inside of some other standard action tags. But we cant use it
directly in a jsp page

Example
Flow diagram
salary.html
salary is
entered
in this form

salary.jsp
request

calculate 'DA'
from
given salary and
forward the
request
to
SalaryServlet.java

forward
browser
displays
Salary
DA
HRA

response

calculate 'HRA'and gets


'DA' from salary.jsp and
prints Salary, DA and HRA
on browser

<jsp:include>
This standard action is used to include response of a
destination into a source
In a jsp, we have 2-types of including
1) Code including
2) Response including
) Source code inclusion is done using include directive and
response including is done using include action
<jsp:include> response included (dynamic including)
<%@ include..%> code is included (static including)

<jsp:include>
In include action, internally for both source and destination jsp
pages, individual servlets are created and after that response of
destination page will be included into response of source page
a.jsp(source)

b.jsp(destination)

b_jsp.java
internal servelt
for b.jsp

a_jsp.java
internal servelt
for a.jsp

response

included

response

<jsp:include>
While including also, the control is forwarded internally to
destination page. Along with control automatically request
parameters are forwarded
We can also add additional parameters along with the control,
while including the response
To add additional parameter, we need to use sub element as
<jsp:param> tag
<jsp:include page=b.jsp>
<jsp:param name=p1 value=100/>
</jsp:include>
Note:
<%@ include file=/servlet1/> (servlet1 is url-pattern)
It is wrong because in include directive destination is a file
(html or jsp) but not servlet

Example
Flow Diagram
numberdisplay.jsp

datedisplay.jsp

Display Numbers

Display Date

include
browser

request

include
include.jsp

From browser if we execute


Include Date and Numbers
Include.jsp it generate
And generate hello world
Response as Date, Numbersresponse message
And hello world

Difference between include directive and directive action


S.No

include Directive

include Action

It is called static including. In this It is called dynamic including. In this


source code is including at translation response is included at runtime
time

In include directive internally a single In include action internally individual


servlet is created for both source and servlets are created for both source and
destination pages at translation
destination pages at runtime

In include directive, the destination In include action the destination can be


resource should be a jsp page or an a jsp, a servlet, or a html
html page. But shouldnt a servlet

In include directive we cant pass any In include action


parameters while including the parameters while
destination page
destination page

In include directive if any changes are In include action if any changes are
done in destination after inclusion done in destination the changes are
then the changes are not effected
effected in source because it is a
dynamic inclusion

Include directive can be written Include action can be written only xml
thriugh html or xml syntax
syntax

we can pass
including the

<jsp:plugin>
This standard action is used for integrating a jsp with a applet
A jsp integrates with applet, whenever the result of jsp wants
to be shown in the form of graphical representation on browser
Syntax:
<jsp:plugin type=applet code=classname
width=value hight=value>
..
..
</jsp:plugin>

<jsp:fallback>
While integrating a jsp with an applet, if any problem is
occurred then we can display an alternate text, in place of an
applet on browser.
For this we need to use a sub tag of <jsp:plugin> called
<jsp:fallback>
Syntax:
<jsp:plugin type=applet code=classname
width=value hight=value>
..
..
<jsp:fallback>some text</jsp:fallback>
</jsp:plugin>

While integrating a jsp with an applet we can pass parameters


to an applet using<jsp:param> tag inside <jsp:plugin> tag
If we pass more than one parameter to applet then we need to
use <jsp:params> tag
The sub elements of <jsp:plugin> tag are
1) <jsp:fallback>
2) <jsp:param>
3) <jsp:params>
Note:
<jsp:fallback> can be used only with <jsp:plugin>
In a pplet, if we want to read the parameters send by jsp page
then we need to call a method getParameter

Example
a.jsp
<jsp:plugin type=applet
code=TestApplet
width=300
height=300>
<jsp:param name=s1
value=welcome/>
</jsp:plugin>

TestApplet.java
Public class TestApplet extends Applet
{
String msg;
public void init()
{
msg=getParameter(s1);
}
public void paint(Graphics g)
{
Fnt f=new Font(Helvitica, Font.BOLD,15);
g.setColor(color.red);
g.fillOval(50,100,150,50);
g.setColor(color.blue);
g.setFont(f);
g.drawString(msg,80,120);
}
}

<jsp:useBean>
Requirement
a.jsp

b.jsp

contains
business
logic
and
presentati
on
logic

Here a.jsp and b.jsp need same business logic and different
presentation logic
Above business logic in a.jsp is not a reusable logic

<jsp:useBean>
Solution

Presentation
logic

Presentation
logic

a.jsp

b.jsp
Business
logic

bean class

JavaBean Class
To make a java class as a JavaBean Class the following rules
to be followed
1) The class must be public
2) The class must contains a public default constructor
3) All properties of the class should be private
4) Each property should contain a public setter and getter
method
5) The class can optionally implement serializable interface

JavaBean Class
public class TestBean
{
public TestBean(int x, int y)
{
.
.
}
}
It is not a JavaBean because of
parameterized constructor

public class TestBean extends


Thread
{
public TestBean()
{
.
.
}
public TestBean(int x, int y)
{
.
.
}
}
It is not a JavaBean

JavaBean Class
Public class TestBean implements
Serilizable
{
public TestBean(int x, int y)
{

}
public TestBean()
{

}
}
It is a JavaBean class

JavaBean Class
public class TestBean extends DemoBean
{
public TestBean(int x, int y)
{

.
}
public TestBean()
{

.
}
}
The above class is a JavaBean class or not depends on DemoBean
class. Suppose DemoBeaan class is JavaBean class then the above
class JavaBean class otherwise the above class is not a JavaBean
class

POJO (Plan Old Java Object)


To make a java class as a POJO then that class shouldnt
extend any predefined base class and shouldnt implement any
predefined interface except serilizable interface
Every JavaBean is a POJO but every POJO is not a JavaBean
public class TestBean
implements TestInter
{
.
.
}
Here, TestInter is extends from
any predefined interface so the
above class is POJO class

public class TestBean


implements Runnable
{
.
.
}
Here, TestBean is implemented
from a predefined interface
called Runnable so the above
class is not POJO class

Jsp to JavaBean Communication


In jsp, it is possible for us to separate presentation logic of jsp
from its business logic
In jsp, we implement business logic in a JavaBean and we call
that business logic from a jsp
We have the following advantages if business logic is
separated from the presentation logic of a jsp
1) Business logic becomes reusable. It means multiple jsps can
call the business logic implemented in the same JavaBean
2) Burden on jsp programmers will be reduced
3) Division of work is possible. So an application development
time will be reduced
Note : To use a java class object in a jsp page, then the java class
must be stored with in a package

<jsp:useBean>
This standard action is used for creating on object of a java
bean in a jsp
While creating an object, the object will be stored in some
scope
Syntax
<jsp:useBean id=objectName
class=fully qualified class name of javabean
scope=scope name/>
The available scopes of bean are
page(default)
request
session
application

<jsp:setProperty>
This standard action is used for setting input values into a java
bean by calling setter methods of the bean class
<jsp:setProperty> must be used at inside of <jsp:useBean> tag
Syntax
<jsp:useBean id=objectName
class=fully qualified class name of javabean
scope=scope name/>
<jsp:setProperty ../>
</jsp:useBean>

<jsp:setProperty>
<jsp:setProperty> tag calls setter methods of the bean class,
for setting input values into properties of the bean class
A bean class cant accept the input values from browser.
Because, from a browser a request is transferred by using Http
protocol and a java bean unknown about http protocol.
So, jsp act as a mediator, takes input values and then transfers
the input values to bean by calling the setter methods using
<jsp:setProperty> tag

<jsp:setProperty>
While setting input values to java bean by a jsp, if request
parameters names and bean class variables names are same
then we use property=* in <jsp:setProperty> tag
having to
textboxes
having
names as
'uname'
and 'pwd'
a.jsp
input.html

package pack1;
public class LoginBean
{
private String uname,pw
---->setters
---->getters
}

<jsp:useBean id=id1
class=pack1.LoginBean>
<jsp:setProperty name=id1
property=* />
</jsp:useBean>

LoginBean

<jsp:setProperty>
While using <jsp:setProperty> tag, name attribute value
should be equal to id attribute of <jsp:useBean> tag
<jsp:useBean id=id1
class=pack1.LoginBean>
<jsp:setProperty name=id1
property=* />
</jsp:useBean>

<jsp:setProperty>
If request parameter names and bean class variable names are
not matched then we need param attribute in
<jsp:setProperty> tag
having to
textboxes
having
names as
'uname'
and 'pwd'

a.jsp

input.html
<jsp:useBean id=id1
class=pack1.LoginBean>
<jsp:setProperty name=id1 property=s1
param=uname/>
<jsp:setProperty name=id1 property=s1
param=uname/>
</jsp:useBean>

package pack1;
public class LoginBean
{
private String s1,s2;
---->setters
---->getters
}

LoginBean

<jsp:setProperty>
A jsp can directly set value into a property of bean class. For
this we need to add an attribute called value with
<jsp:setProperty> tag
having to
textboxes
having
names as
'uname'
and 'pwd'

a.jsp

input.html
<jsp:useBean id=id1 class=pack1.LoginBean>
<jsp:setProperty name=id1 property=s1
param=uname/>
<jsp:setProperty name=id1 property=s1
param=uname/>
<jsp:setProperty name=id1 property=s3
value=ram>
</jsp:useBean>

package pack1;
public class LoginBean
{
private String s1,s2,s3;
---->setters
---->getters
}

LoginBean

<jsp:setProperty>
<jsp:setProperty> tag contains totally 4-attributes, in that
name and property attributes are mandatory and we use can
use either param or value but not both at a time
name, property----------> valid
name, property, param---------- valid
name, property, value----------- valid
name, property, param, value---------- invalid

<jsp:getProperty>
This standard action is used for reading a property of a java bean
class in a jsp
<jsp:getProperty> tag calls getter method of the bean class
<jsp:getProperty> should be used at outside of <jsp:useBean> tag
We cant store the value returned by <jsp:getProperty> tag into a
variable in a jsp page
String str=<jsp:getProperty name=id1 property=uname/>
(The above code is invalid)
We cant use property=* in <jsp:getProperty> tag
<jsp:getProperty name=id1 property=*/>
(The above code is wrong)
<jsp:getProperty> tag contains only 2-attributes called name and
property
Syntax: <jsp:getProperty name=id1 property=uname/>

Example
Flow Diagram

having to
textboxes
having
names as
'uname'
and 'pwd'
input.html

set

get
a.jsp
response

Username:
Passsword:
LoginBean

Example-2
Flow Diagram
having one textbox
for enter sql command
Request
and one submit button
to perform an action
enterCommand.html

Set
Get

ReadCommand.jsp

DatabaseBean.java

Response

Browser
Database

Scopes in Jsp
<jsp:useBean> standard action having an attribute called
scope. The following are the available values for scope
attribute
1) page
2) request
3) session
4) application

page scope
The default scope of bean object is page scope
If a bean object is associated with page scope then that bean
object is available to that jsp page only
If the response is transferred from current jsp page to another
jsp page then the bean object is not sharable in the other jsp
page
The least scope of a bean object is a page scope. If bean object
is stored in page scope then it is removed from server
whenever the control goes out of the jsp page

page scope
a.jsp
<jsp:useBean id=id1
class=pack1.LoginBean
Scope=page/>
<jsp:forward page=b.jsp/>

b.jsp
<jsp:useBean id=id1
class=pack1.LoginBean
Scope=page/>

The above example result is forwarded from a.jsp to b.jsp. In


a.jsp the bean object is created and it will be stored in page
scope
When the result is forward then the control goes out a.jsp. So
that page scope is removed and in b.jsp new object is created
stored in page scope
When a bean objevt is page scope then for every jsp page a
new bean object will be created

request Scope
When a bean object is stored in request scope then a bean
object is sharable to another jsp page also if the request
forwarded to other jsp
Request scope is continued until the request is completed. It
means until the response is given back to the client
a.jsp
<jsp:useBean id=id1
class=pack1.LoginBean
Scope=request/>
<jsp:forward page=b.jsp/>

b.jsp
<jsp:useBean id=id1
class=pack1.LoginBean
Scope=request/>

In the above example, request is forwarded from a.jsp to b.jsp.


In a.jsp bean object is created stored in request scope. So the
bean object is available to b.jsp also. The request scope is
continued until response is given back to the client

session Scope
If a bean object is stored in session scope then that object is
sharable in current jsp page and in the forward jsp and also
other jsp page visited by same client
Session scope is greater than request scope. But if the request
scope is sharable with in a single request, but session scope is
sharable in the current request and also next request given by
the same client
a.jsp

b.jsp

c.jsp

<jsp:useBean id=id1
class=pack1.LoginBean
Scope=session/>
<jsp:forward
page=b.jsp/>
<jsp:forward
page=c.jsp/>

<jsp:useBean id=id1
class=pack1.LoginBean
Scope=session/>

<jsp:useBean id=id1
class=pack1.LoginBean
Scope=page/>

application Scope
If a bean object is stored in application scope then it is
sharable in all pages and all clients of a web application
We call application scope as a global scope to a web
application
Application scope destroyed, either when an application is
removed from the server or when the server is closed or
shutdown

a.jsp
b.jsp
c.jsp
<jsp:useBean id=id1
class=pack1.LoginBean
Scope=application/>
<jsp:forward
page=b.jsp/>
<jsp:forward
page=c.jsp/>

Implicit Objects Of Jssp


S.NO

OBJECT NAME

AVAILABLE PACKAGE

request

javax.servlet.http.HttpServletRequest

response

javax.servlet.http.HttpServletResponse

out

javax.servlet.jsp.JspWriter

session

javax.servlet.http.HttpSession

exception

java.lang.Throwable

page

java.lang.Object

config

javax.servlet.ServletConfig

application

javax.servlet.ServletContext

pageContext

javax.servlet.jsp.PageContext

Implicit Objects in Jsp


session object and exception object both are not directly
available in a jsp page. The remaining 7-objects are available
in every jsp page
session object is available when session is true and by default
every jsp contains session=true
exception object is available when the jsp is acting like an
error page. By default a jsp doesnt act as an error page. To use
exception object in a jsp, we need to make isErrorPage=true

config Implicit Object


By using this readymade object we can read the following 3types of information
Logical name of the jsp
Init parameterss of the jsp
Context reference
If a jsp is not configured in web.xml or a jsp is configured in
web.xml and it is accessed by using name of the jsp page then
logical name will be taken as jsp and init parameters will be
printed as empty (null)
If a jsp is configured in web.xml and it is accessed by using
<url-pattern> of the jsp page then we can read logical name
and init parameters using config object

Custom Tags in Jsp


While creating jsp pages, apart from predefined tags given by
the technology, we can also create and use user defined tags in
a jsp page. We call such user defined tags as custom tags
For each predefined tag given by jsp, there is a predefined
meaning and during translation time the tag meaning is
executed and finally the jsp is translated into equivalent servlet
In case of custom tags, the translator is unknown about the
user defined tags. So during translation time an exception will
be generated. In order to inform the meaning of a custom tag
to the translator, we need to create some helper class for our
jsp page. We call such helper classes as TagHandler classes in
jsp

Custom tags in Jsp


A jsp page may contain any number of custom tags and
multiple tag handler classes are created for the custom tags. To
inform the translator about which class is belong to which tag,
a special mapping file should be created called TLD
(Tag Library Descriptor) file
A container cant read a TLD file directly. So we need to
configure the tld file in web.xml
A container reads web.xml and identifies the location of tld
file
To work with custom tags, the followwing files are required
1) Jsp Page
2) TLD File
3) Tag Handler Class
4) web.xml

Creating a Tag Handler Class


A tag handler class is helper of jsp, which contains the
definition of a custom tag
We can create a tag handler class, either by extending
TagSupport or by extending BodyTagSupport classes
TagSupport is a class implemented from Tag interface
BodyTagSupport is class implemented from BodyTag interface
Instead of extending the class, we can also implement the
interfaces directly. But it increases the burden on programmer
has to override all the methods of that interface
interface,
BodyTag
interface,
TagSupport,
Tag
BodyTagSupport
classes
all
are
given
in
javax.servlet.jsp.tagext package

Creating a Tag Handler Class


Instead of implementing interfaces we choose extending
classes. Because we no need of overriding all the methods in
our class given by the interface
We extends our tag handler class from TagSupport class if our
custom tag doesnt contain boby
<talent:hello/> [ no body tag]
We extends our tag handler class from BodyTagSupport class
if our custom tag contains body
<talent:hello> </talent:hello> [empty body]

Extending TagSupport Class


In a jsp, if we write a custom tag with self closing then we
extend our tag handler class from TagSupport
If we extend TagSupport class, then we need to override the
following 2-methods in the class
1) doStartTag()
2) doEndTag()
) The logic implemented in doStartTag() method will be
executed by the container when a custom tag is opened and the
logic implemented in doEndTag() will be executed when the
tag is closed
) The above 2-methods returns int and these int values are
predefined constants

Extending TagSupport Class


doStartTag() method returns any one of the following 2constants
1) SKIP_BODY
2) EVAL_BODY_INCLUDE
) SKIP_BODY is used to inform the container that skip the
body execution of a custom tag
) When a custom tag is self closing tag then we must return
SKIP_BODY for doStartTag() method
) If a custom tag contains body then to inform the container that
to execute body content, we need to return
EVAL_BODY_INCLUDE

Extending TagSupport Class


doEndTag() method returns any one of the following
1) SKIP_PAGE
2) EVAL_PAGE
) If doEndTag() return SKIP_PAGE then the container doesnt
execute the remaining jsp after close the custom tag
) If doEndTag() method reurns EVAL_PAGE then the container
will execute the remaining jsp page after closing the custom
tag

TLD File (tag library descriptor)


The custom tags used in a jsp page are configured in a tld file
In a jsp, all custom tags with a same prefix will be configured
into same tld file. It means the number of tld files required will
depends on the number of prefixes used for a custom tags in a
jsp
In tld file, we write mapping between tag name to tag class
and also we configure body content and attributes of the jsp

TLD File
<! DOCTYPE.>
<taglib>
<tlib-veersion>1.1</tlib-version>
<jsp-version> 1.2</jsp-version>
<tag>
<name> custom tagname</name>
<tag-class>fully qualified class name</tag-class>
<body-content>empty/jsp</body-content>
</tag>
</taglib>
Save as <anyname.tld> in WEB-INF folder of web application

Configuring TLD file in web.xml


<web-app>
<taglib>
<taglib-uri>some uri</taglib-uri>
<taglib-location>/WEB-INF/tld file name </taglib-location>
</taglib>
</web-app>
Save as web.xml in WEB-INF folder of web application

Flow
a.jsp
<%@ taglib uri= uri1 prefix=s
%>
..
.. 1
<s:hello/>
.

one.tld
<taglib>
<tlib-veersion>1.1</tlib-version>
<jsp-version> 1.2</jsp-version>
<tag>
<name> hello</name>
4
<tag-class>p1.HelloTag</tag-class>
<body-content>empty/jsp</body-content>
</tag>
</taglib>

web.xml
<web-app>
<taglib>
2<taglib-uri>uri1</taglib-uri>
<taglib-location>/WEB-INF/one.tld
</taglib-location> 3
</taglib>
</web-app>
HelloTag.java
package p1
..
public class HelloTag eextends
TagSupport
{
public int doStratTag()
{}
public int doEndTag()
{}
}

Example1
<%-- custom1.jsp--%>
<%@ taglib uri=myuri prefix=talent%>
<talent:hello/>
<hr>
<br>
<font color=blue>
This is normal text from html
</font>

Exmple1
<!- -web.xml- ->
<web-app>
<taglib>
<taglib-uri> myuri</taglib-uri>
<taglib-location>/WEB-INF/one.tld</taglib-location>
</taglib>
</web-app>

Example1
<!- - one.tld - ->
<taglib>
<tlib-version>1.1</tlib-version>
<jsp-version>1.2</jsp-versin>
<tag>
<name>hello</name>
<tag-class>mytags.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

Example1
//HelloTag.java
package mytags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
Public class HelloTag extends TagSupport
{
public int doStartTag() throws JspException
{
try{
JspWriter out=pageContext.getOut();
out.println(Welcome to talent <br>);
}
Catch(exception e){ }
return SKIP_BODY;
}
Public int doendTag() throws JspException
{
try
{
JspWriter out=pageContext.getOut();
out.println(Bye to talent <br>);
}
Catch(exception e){ }
return EVAL_PAGE ;
}
}

Example1
In the above tag handler class, we have used pageContext object
directly in doStartTag() and doEndTag() methods.
Actually. pageContext object is an implicit object of jsp and
whenever an object of tag handler class is created by the container,
then it will call the first life cycle method of a tag handler class
called setPageContext() and this life cycle method stores local
pageContext object in a global pageContext object. This logic is
available in base class of our tag handler class called TagSupport
In TagSupport class pageContext variable created as public. So we
can use the pageContext of base class in our class directly
pageContext is a special implicit object of jsp, which contains all
other implicit objects of jsp. So we called getOut() to get out object
from it, for writing a text on a browser
To compile the above tag handler class, we need to set class path
jsp-api.jar

Adding attributes to a custom tag


Like predefined tags in jsp, even for user tags also we can create/add
attributes
To add attributes to a custom tag, the following 2-changes are required
In a tag handler class, create a variable and generate setter and getter
methods for it. Here, attribute name and variable name should be same
In a tld file, configure attribute also along with tag
<attribute>
<name>attributename</name>
<required>true/false</required>
<rtexprvalue>true/false</rtexprvalue>
</attribute>
If required is true then the attribute is mandatory for the tag. If it is false then
the attribute is optional for the tag
If rtexprvalue is true then both static and dynamic values are allowed for the
attribute. If it is false then only static values are allowed, but dynamic values
are not allowed for that attribute

Extending BodyTagSupport class


If a custom tag in a jsp contains body content then the tag
handler class should extend BodyTagSupport class
If we extends our class from BodyTagSupport then we need to
override the following 4-methods in our class
doStratTag()
doInitBody()
doAfterBody()
doEndTag()
doInitBody() method is executed, just before going to start
body content of a custom tag
doAfterBody() method is executed after compilation of body
content of a custom tag

Extending BodyTagSupport class

doInitBody() returns void, and doAfterBody() returns int.


The return values of doAfterBody() are
SKIP_BODY
EVAL_BODY_AGAIN
If we return EVAL_BODY_AGAIN then the body content of
the custom tag will be executed for once again. It means we
can execute body content of a custom tag for more than one
also by returning EVAL_BODY_AGAIN value

Attributes in JSP
Attributes in web application are used for sharing the data
across multiple files of a web application
An attribute will be in the form of a key-value pair and to
retrieve the value we use its key
To share the data across multiple files of a web application we
attach some scope for the data
In jps, we have 4-scopes for sharing the data
1) page
2) request
3) session
4) application
) page scope is newly added in jsp and if any attributes are
stored in page scope then those attributes become non sharable

Attributes in JSP
To store attributes in request, session and application scopes, we
need implicit objects. But, we cant store attributes in page scope
by using page object
If we want to store an attribute in page scope then we need
pageContext object
pageContext object is not only used for storing attributes in page
scope, but also we can use it to store attributes in any scope
Example
pageContext.setAttribute(k1, talent);
(Above attribute is stored in page scope)
pageContext.setAttribute(k2, sprint,3);
(Above attribute is stored in session scope. Above statement is equal
to)
session.setAttribute(k2,sprint);

Attributes in JSP
PageContext class contains the following four public static
final variables for scopes
1) PAGE_SCOPE----------->1
2) REQUEST_SCOPE----------->2
3) SESSION_SCOPE----------->3
4) APPLICATION_SCOPE----------->4
) The following statements are used to store an attribute in page
scope
)pageContext.setAttribute(k1, talent);
)pageContext.setAttribute(k1, talent,1);
) pageContext.setAttribute(k1, talent,PageContext.PAGE_SCOPE);

Attributes in JSP
The following statements are used to store an attribute in
request scope
request.setAttribute(k1,jsp);
pageContext.setAttribute(k1,jsp,2);
pageContext.setAttribute(k1,jsp,PageContext.REQUEST_SCOPE );
The following statements are used to store an attribute in
session scope
session.setAttribute(k1,java);
pageContext.setAttribute(k1,java,3);
pageContext.setAttribute(k1,java,PageContext.SESSION_SCOPE);
The following statements are used to store an attribute in application scope
application.setAttribute(k1,java);
pageContext.setAttribute(k1,java,4);
pageContext.setAttribute(k1,java,PageContext.APPLICAATION_SCOPE);

Attributes in JSP
To read value of an attribute from a particular scope then we
can use either pageContext objects or an object representing
that scope
Example
To read a value of attribute stored in a request scope , we can
use any one of the following 3-statements
Object o=pageContext.getAttribute(k1,2);
Object o=pageContext.getAttribute(k1,PageContext.REQUEST_SCOPE)

Object o=request.getAttribute(k1);
pageContext object contains another method for reading value
of an attribute called findAttribute()

Difference between getAttribute() and findAttribute() methods

The difference between getAttribute() and findAttribute()


method is, in findAttribute() the searching for an attribute will
be done from the given scope to its next level of scopes. It not
found then null is returned. But in getAttribute() the search
will be done exactly in the given scope only. If not found then
null is returned
Example
Object o=pageContext.findAttribute(k1);
For the above statement the container starts searching for an
attribute called k1 from page scope, if not found then enter
into request scope, then to session scope and then finally
application scope. If the attribute is not found all these scopes
then it returns null

Difference between getAttribute() and findAttribute() methods

Object o=pageContext.findAttribute(k13);
The container will search for an attribute called k1 in session
scope and if not then in application scope. If not found then
returns null

Expression Language
While working with jsp, we use java code for reading
attributes or request parameters
To write java code in jsp, we use scriptlet tags. But as a jsp
programmer, it is our responsibility to avoid java code as
much as possible in a jsp page
In order to avoid the java code for reading attributes and
parameters in a jsp, we got expression language
Expression Language is mostly used in the development of
JSTL applications
Expression Language avoids the calling of the methods like
getParameter() and getAttribute
Expression Language uses 2-special symbols called $ and
{} for reading the value of an attribute or a parameter

Implicit Objects in Expression Language


1) pageScope
2) requestScope
3) sesionScope
4) applicationScope
5) param
6) paramValues
7) cookie
8) header
9) headerValues
10) ..

Expression Language
To read the value of an attribute using EL, we use the synatx $
{attributename}
If you want to read value of an attribute from particular scope
then we use ${object.attributename}
Example
To read the value of an attribute called k1 from any scope
then we use EL statement as
${k1}
The above EL statement searching for k1 from page scope to
application scope. If not found then returns empty space (not
null)

Expression Langage
To read the value of an attribute called k1 from request scope
only then we use the EL statement as
${requestScope.k1}
If k1 is not found in request scope then returns empty space (not
null)
To read value of request parameter submitted by a client, we use
the following statement in jsp
String str=request.getParameter(uname);
To avoid the above statement in a jsp, we use the following EL
expression ${param.uname}
If multiple values are send along with a request parameter then to
read the one by one value of the request parameter, we use an
implicit object called paramValues
${paramValues.hobbies[0]}

Jsp Standard Tag Library (JSTL)


JSTL is a library which contains a set of custom tags given by
SUN
Actually JSTL tags are predefined tags only but the tags will
look like custom tags
JSTL library is separately released by SUN, not as a part of jsp
technology
SUN released JSTL, to make a jsp page as 100% java code
less. It means JSTL completely eliminated scripting elements
of jsp, that is in a jsp, we no need of writing any line of java
code
JSTL is added in jsp1.2 (2.0) and the libraries of JSTL are
standard.jar
jstl.jar

JSTL
A web server or application server , doesnt have in build
knowledge of JSTL. So we need to add jar files of JSTL to
server
To get the jar files of JSTL, download and install JWSDP(Java
Web Service Developers Pack) software and copy the jar files
of JSTL into lib folder of a server

Types of JSTL Tags


1)
2)
3)
4)
5)

Core tags
Sql tags
Function tags
Formatting tags
Xml tags

Core Tags
Core tags are used to avoid conditional and iteration
statements from a jsp page
To use core tags in jsp, we need a standard uri to be added
with in the taglib directive of a jsp
<%@ taglib uri=http://java.sun.com/jstl/core prefix=c%>
Here, uri is fixed, but prefix can be modified
While translating a jsp into servlet, the container verifies
whether the uri added in jsp page and the uri given in jar files
is matching or not

Core Tags
In a jsp, if we want store an attribute we use the following
statement
pageContext.setAttribute(k1, talent);
Some thing is done by using JSTL core tag called <c:set>
<c:set>
This JSTL tag is used to store an attribute in some scope
If any scope is not added for this tag then it will be stored in page
scope
Example
<c:set var=k1 value=talent/>
Here, k1 attribute is stored in page scope
To store an attribute in some scope then we need to add scope
attribute for the tag
<c:set var=k1 value=talent scope=session/>

Core Tags
<c:out>
This core tag is used for printing a static value or the value of
an expression statement on browser
<c:out value=ram/>
<c:set var=k1 value=talent/>
<c:out value=${k1}/>

Core Tags
<c:if>
This tag is used to replace simple if statement of java
To put condition, we need to use an attribute called test
<c:if test:condition>

</c:if>
Example
<c:set var=k value=sprint/>
<c:if test=${ k eqsprint}>
<c:out value=success/>
</c:if>

Core Tags
<c:choose> <c:when><c:otherwise>
This tags are for replacing switch statement of java.
Each case is represented with <c:when> and if no case is matched then <c:otherwise> will be
executed
Syntax:
<c:choose>
<c:when test=condition1
.
.....
</c:when>
<c:when test=condition2
.
.....
</c:when>
<c:otherwise>

</c:otherwise>
</c:choose>

Core Tags
<c:forEach>
This tag is a tag for replacement of for loop of java in a jsp
In java we have 2-types of for loops. So we can use
<c:forEach> tag in both cases
for(int i=0;i<=10;i++)
{
System.out.println(i);
}

<c:forEach var=i begin=1 end=10>


<c:out value=${i}/>
</c:forEach>

int[] x={10,20,30};
for(int k : x)
{
System.out.println(k);
}

<c:set var=x value=10,20,30/>


<c:forEach var=k items=${x}>
<c:set value=${k}/>
</c:forEach>

Core Tags
<c:forTokens>
This tag is replacement for StringTokenizer class of java.
By using this tag we retrieve one by one word form a given
string
<c:set var=str value=This is a Funny World/>
<c:forTokens var=k items=${str} delimeter= >
<c:out value=${k}/>
</c:forTokens>

Core Tags
<c:redirect>
This tag of JSTL is a replacement for response.sendRedirect()
In a jsp we have a standard action for forwarding the request from one
jsp to other jsp called <jsp:forward>
In JSTL for direction we got <c:redirect>. While redirecting the
destination resource may be in the same web application or a different
web application or a different server
<c:redirect url=b.jsp/> [same web application]
<c:redirect url=webapp2/c.jsp/> [different web application]
<c:redirect url=http://localhost:7001/webapp2/b.jsp /> [different server>
While redirection control from one jssp to other jsp we can attcaah
some additional parameters also along the redirection by using
<c:param> tag
<c:redirect url=b.jsp>
<c:param name=p1 value=100/>
</c:redirect>

Sql Tags of JSTL


To use sql tags of JSTL in a jsp we need to add the following
taglib jsp dirctive in jsp
<%@ taglib uri=http://java.sun.com/jstl/sql%>
Tag

Description

<sql:setDataSource>

Used to collect JDBC connection properties

<sql:query>

Executes the SQL query defined in its body or through the


sql attribute.

<sql:update>

Executes the SQL update defined in its body or through


the sql attribute.

<sql:param>

Sets a parameter in an SQL statement to the specified


value.

<sql:dateParam>

Sets a parameter in an SQL statement to the specified


java.util.Date value.

<sql:transaction >

Provides nested database action elements with a shared


Connection, set up to execute all statements as one
transaction

<sql:setDataSource>
Attribute

Description

driver

Name of the JDBC driver class to be registered

url

JDBC URL for the database connection

user

Database username

password

Database password

dataSource

Database prepared in advance

var

Name of the variable to represent the database

scope

Scope of the variable to represent the database

<sql:query>
Attribute

Description

sql

SQL command to execute (should return a ResultSet)

dataSource

Database connection to use (overrides the default)

maxRows

Maximum number of results to store in the variable

startRow

Number of the row in the result at which to start recording

var

Name of the variable to represent the database

scope

Scope of variable to expose the result from the database

<sql:update>
Attribute

Description

sql

SQL command to execute (should not return a


ResultSet)

dataSource

Database connection to use (overrides the default)

var

Name of the variable to store the count of affected


rows

scope

Scope of the variable to store the count of


affected rows

Date Class
Java provides the Date class available in java.util package,
this class encapsulates the current date and time.
Constructors of Date Class
Date()
The first constructor initializes the object with the current date
and time.
Date(long millisec)
The following constructor accepts one argument that equals
the number of milliseconds that have elapsed since midnight,
January 1, 1970

Example on Date Class


import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date.toString());
}
}
Output:Tue Nov 05 09:46:53 IST 2013

Date Comparison

There are following three ways to compare two dates:


1) You can use getTime( ) to obtain the number of milliseconds
that have elapsed since midnight, January 1, 1970, for both
objects and then compare these two values.
2) You can use the methods before( ), after( ), and equals( ).
Because the 12th of the month comes before the 18th, for
example, new Date(99, 2, 12).before(new Date (99, 2, 18))
returns true.
3) You can use the compareTo( ) method, which is defined by
the Comparable interface and implemented by Date.
An int larger than 0 if the date the method is called on is later than the
date given as parameter.
An int value of 0 if the dates are equal.
An int value less than 0 if the date the method is called on is earlier
than the date given as parameter.

Example:1
import java.util.*;
public class DateComparision {
public static void main(String[] args) {
// create two dates
Date date = new Date(98, 5, 21);
Date date2 = new Date(99, 1, 9);
// make 3 comparisons with them
int comparison = date.compareTo(date2);
int comparison2 = date2.compareTo(date);
int comparison3 = date.compareTo(date);
// print the results
System.out.println("Comparison Result:" + comparison);
System.out.println("Comparison2 Result:" + comparison2);
System.out.println("Comparison3 Result:" + comparison3);
}
}

Example:2
import java.util.*;
public class DateComparision1 {
public static void main(String[] args) {
// create 2 dates
Date date = new Date(70, 1, 10);
Date date2 = new Date(70, 1, 10);
//Check if they are equal
boolean check = date.equals(date2);
// print the result
System.out.println("Dates are equal:" + check);
}
}

Methods of Date Class

long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.
int hashCode( )
Returns a hash code for the invoking object.
void setTime(long time)
Sets the time and date as specified by time, which represents an elapsed time
in milliseconds from midnight, January 1, 1970
String toString( )
Converts the invoking Date object into a string and returns the result.

Example on Date Class Methods


import java.util.*;
public class DateMethods {
public static void main(String[] args) {
// create a date
Date date = new Date(2013, 1, 23);
long diff = date.getTime();
int i = date.hashCode();
date.setTime(10000);
System.out.println("If date is 23-01-1997, " + diff + " have passed.");
System.out.println("The current date shows: " + date.toString());
System.out.println("A hash code for this date is: " + i);
System.out.println("Time after setting: " + date.toString());
}
}

Date Formatting using SimpleDateFormat

SimpleDateFormat is a concrete class for formatting and


parsing dates in a locale-sensitive manner.
SimpleDateFormat allows you to start by choosing any userdefined patterns for date-time formatting.

Example using SimpleDateFormat Class


import java.util.*;
import java.text.*;
public class DateFormat1 {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a
zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
Output:Current Date: Tue 2013.11.05 at 10:19:57 AM IST

Simple DateFormat format codes:


Character

Description

Example

Era designator

AD

Year in four digits

2001

Month in year

July or 07

Day in month

10

Hour in A.M./P.M. (1~12)

12

Hour in day (0~23)

22

Minute in hour

30

Second in minute

55

Millisecond

234

Day in week

Tuesday

Day in year

360

Day of week in month

2 (second Wed. in July)

Week in year

40

Week in month

A.M./P.M. marker

PM

Hour in day (1~24)

24

Hour in A.M./P.M. (0~11)

10

Time zone

Eastern Standard Time

'

Escape for text

Delimiter

"

Single quote

Date Formatting using printf:

Date and time formatting can be done very easily using printf
method.
You use a two-letter format, starting with t and ending in one
of the letters of the table given below.

Date and Time Conversion Characters


Character

Description

Example

Complete date and


time

Mon May 04 09:51:52


CDT 2009

ISO 8601 date

2004-02-09

U.S. formatted date


(month/day/year)

02/09/2004

24-hour time

18:05:19

12-hour time

06:05:19 pm

24-hour time, no
seconds

18:05

Four-digit year (with


leading zeroes)

2004

Last two digits of the


year (with leading
zeroes)

04

First two digits of the


year (with leading
zeroes)

20

Full month name

February

Abbreviated month
name

Feb

Two-digit month (with


leading zeroes)

02

Two-digit day (with


leading zeroes)

03

Two-digit day (without


leading zeroes)

Date and Time Conversion Characters


a

Abbreviated weekday name

Mon

Three-digit day of year (with leading zeroes)

069

Two-digit hour (with leading zeroes), between 00 and 23

18

Two-digit hour (without leading zeroes), between 0 and 23

18

Two-digit hour (with leading zeroes), between 01 and 12

06

Two-digit hour (without leading zeroes), between 1 and 12

Two-digit minutes (with leading zeroes)

05

Two-digit seconds (with leading zeroes)

19

Three-digit milliseconds (with leading zeroes)

047

Nine-digit nanoseconds (with leading zeroes)

047000000

Uppercase morning or afternoon marker

PM

Lowercase morning or afternoon marker

pm

RFC 822 numeric offset from GMT

-0800

Time zone

PST

Seconds since 1970-01-01 00:00:00 GMT

1078884319

Milliseconds since 1970-01-01 00:00:00 GMT

10788843190
47

Sleep Time Example


import java.util.*;
public class SleepTime {
public static void main(String args[]) {
try {
System.out.println(new Date( ) + "\n");
Thread.sleep(5000);
System.out.println(new Date( ) + "\n");
} catch (Exception e) {
System.out.println("Got an exception!");
}
}
}

Calendar Class
Java's java.util.Calendar class is used to do date and time
arithmetic.
Whenever you have something slightly more advanced than
just representing a date and time, this is the class to use.
The java.util.Calendar class is abstract, meaning you cannot
instantiate it.
The reason is that there are more than one calendar in the
world.
For instance, the Arab calendar uses a different year as year 0
than the Gregorian calendar used by most western countries.

Instantiating a GregorianCalendar
Java only comes with a Gregorian calendar implementation,
the java.util.GregorianCalendar class.
Here is how you instantiate a GregorianCalendar:
Calendar calendar = new GregorianCalendar();
A new GregorianCalendar has the date and time set to "now",
meaning the date and time it was created

Example

Das könnte Ihnen auch gefallen