Beruflich Dokumente
Kultur Dokumente
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
Session Management
request-1
token
response+token
Request(2)+token
response
Client-1
Server
State Management
client-1
session object
to store client-1
data
session object
to store client-2
data
client-2
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
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
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
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
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(
-,-)
{
---------
http://localhost:8080/app1/one.jsp
request
one.jsp
response
object
_jspService(
-,-)
{
---------
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
}
%>
%>
%>
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
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 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
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)
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.* %>
.
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
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 %>
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
a.jsp
<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);
%>
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
<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
include Directive
include Action
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>
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
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
<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/>
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/>
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/>
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
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
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
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()
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
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]}
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
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);
}
int[] x={10,20,30};
for(int k : x)
{
System.out.println(k);
}
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>
Description
<sql:setDataSource>
<sql:query>
<sql:update>
<sql:param>
<sql:dateParam>
<sql:transaction >
<sql:setDataSource>
Attribute
Description
driver
url
user
Database username
password
Database password
dataSource
var
scope
<sql:query>
Attribute
Description
sql
dataSource
maxRows
startRow
var
scope
<sql:update>
Attribute
Description
sql
dataSource
var
scope
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
Date Comparison
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);
}
}
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.
Description
Example
Era designator
AD
2001
Month in year
July or 07
Day in month
10
12
22
Minute in hour
30
Second in minute
55
Millisecond
234
Day in week
Tuesday
Day in year
360
Week in year
40
Week in month
A.M./P.M. marker
PM
24
10
Time zone
'
Delimiter
"
Single quote
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.
Description
Example
2004-02-09
02/09/2004
24-hour time
18:05:19
12-hour time
06:05:19 pm
24-hour time, no
seconds
18:05
2004
04
20
February
Abbreviated month
name
Feb
02
03
Mon
069
18
18
06
05
19
047
047000000
PM
pm
-0800
Time zone
PST
1078884319
10788843190
47
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