JSP - Javasiva

milklivereddeepInternet and Web Development

Nov 13, 2013 (3 years and 11 months ago)

148 views


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
92

of
111

8.

JSP


A JSP

page is a text
-
based document that contains two types of text: static template data, which
can be expressed in any text
-
based format, such as HTML,SVG, WML, and XML; and JSP elements,
which construct dynamic content.

In many Java servlet
-
based application
s, processing the request
and generating the response are both handled by a single servlet class.

Disadvantages with Servlets:
When we are developing servlets,we need to have many things in
to consideration like overriding service methods and entries in we
b.xml.And also I am listing out
the some of disandvantages.



Thorough Java programming knowledge is needed to develop and maintain all aspects of
the application, since the processing code and the HTML elements are dumped together.



Changing the look and f
eel of the application, or adding support for a new type of client
(such as a WML client), requires the servlet code to be updated and recompiled.



It's hard to take advantage of web
-
page development tools when designing the application
interface. If such

tools are used to develop the web page layout, the generated HTML must
then be manually embedded into the servlet code, a process which is time consuming, error
prone, and extremely boring.

Aim of JSP:

Separation of request processing, business logic,
and presentation
.
And also providing
below benefits.



Auto
transition and compilation.Means we need not recompile every time when we
do changes in JSP.



There is no deployment descritpor for JSP.



Multiple deployment is avoided.
Means on the fly we can do chang
es to JSP Pages.



JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA
servlets.



JSP uses simplified scripting language based syntax for embedding HTML into JSP.



JSP containers provide easy way for accessing standard objec
ts and actions.



JSP reaps all the benefits provided by JAVA servlets and web container environment,
but they have an added advantage of being simpler and more natural program for web
enabling enterprise developer



JSP use HTTP as default request /response c
ommunication paradigm and thus make
JSP ideal as Web Enabling Technology.

We can observe that how JSP coding simplifying the servelt code.

Helloworldservlet


public class HelloWorldServlet implements
servelet{


public void service(ServletRequest request,



ServletResponse response)



throws ServletException,
IOException {



response.setContentType(“text/html”);
=
=
=
偲mntt物te爠
out=牥sponse.gettrite爨F;
=
=
=
out.println(“<html>”
F
;
=
=
=
out.println(“ <head>”
F
;
=
=
=
out.println (“ <title>Hello
world</title>”
F
;
=
=
=
out.println(“ </head>”
F
;
=
=
=
out.println(“ <body>”
F
;
=
=
=
out.println(“ <h1>Hello
to牬d<
y
h1>”
F
;
=
=
=
out.println(“ It's ”+ (new
橡j愮util.d慴eEF.to却ringEFF=H
=
=
=
=
=
+ “and all is well”);
=
=
=
out.println(“ </body>

F
;
=
=
=
out.println(“</html>”
F
;
=
=
}
=
}
=
HelloworldJSPPage

<html>


<head>


<title>Hello world


<
\
title>


</head>


<body>


<h1>Hello World<
\
h1>


It,s<%=new
java.util.date().toString() %>


and all is well.


</body>

</html>


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
93

of
111

8.1.

JSP Processing



Ever JSP page will be converted into a servlet.Here is the process of JSP.


Whenever a .jsp is requested for the first time, the server does the following:



Translates the .jsp page into a servlet


Compiles the servlet into a class file


Executes the
servlet (response is sent to the client)


Subsequent requests (as long as the .jsp page is unchanged) use the same loaded class
file.


Note:
Please refer Classes and Objects topic in EasyJava book for getting info on
instantiation and initialization.


8.2.


A
natomy/Structure of a JSP Page


A JSP page is a mixture of standard HTML tags, web page content, and some dynamic
conte
nt that is specified using JSP Elements and implicit objects
. Everything except the
JSP constructs is called Template Text

which can be t
ext or HTML
.

Everything in the page
that isn't a JSP element is called template text. Template text can be any text: HTML,
WML, XML, or even plain text.

<HTML>


<HEAD>


<TITLE>JSP

Color Program
</TITLE>


</HEAD>


<% String
bgColor = request.getParameter("COLOR"); %>


<% if (bgColor == null) { %>




<BODY BGCOLOR="FFFFFF" >



<% } else { %>


<BODY BGCOLOR="<%= bgColor %>" >


<
% } %>




</BODY>


</HTML>

JSP Elements

Template Text

Mixture of JSP Elements and
Tempate text


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
94

of
111


When a JSP page request is processed, the template text and dynamic content generated
by the JSP elements are merged, and the result is sent as the response to the browser.


8.3.


JSP Elements



There are
six
types of JSP elements you can use

and they are:


a.

Declaration Element
: A JSP element provides the capability of inserting Java
declaration statements into the Servlet class. Here is the syntax for the declaration
element.


<
%! Java decalaration statements %>


b.

Scriptlet Element
: A JSP element provides the capability of embedding Java
expressions to be evaluated as part of the service method of the Servlet class. An
scripting element can be written in two ways:


<% Java

statements %>


c.

Expression Element:

A JSP element provides the capability of embedding Java
expressions to be evaluated as part of the service method of the Servlet class. An
expression element can be written in two ways:


<% Java expressoins %>


d.

Comments Element
:
This elements helps the developer to write documentation of the
statements for better understanding of the program.Below is the syntax:


<%
--


description of process
--
%>


e.

Directive elements
:
These will be considered at the time of
translation.The directive
elements, shown in
Table
, specify information about the page itself that remains the
same between requests.For example, if session tracking is required or not, buffering
requirements, and the name of a page that should be used to
report errors, if any.




Directive

elements



Description

<%@ page ... %>

Defines page
-
dependent attributes, such as session tracking,
error page, and buffering requirements

<%@include ... %>

Includes a file during the translation phase

<%@ taglib ...
%>

Declares a tag library, containing custom actions, that is used in
the page


Page directive:
Page directive are having these attributes

and here I am listing out
the some of important attributes


import

:
Import is used to import java classes and
package methods.This
translates JSP engine to include classes in JSP servlet.

Comma is used to
separation between classes and package.



<%@page import="java.sql.*,java.text.SimpleDateForamt"%>


errorPage
:
errorPage=”relativeURL”
.
When an exception is
occur in JSP, errorPage
transfer the control of page to defined URL which is set in errorPage. This is
customized presentation of errors to user. If relativeURL found blank, exception will
throw on same page.


<%@ page errorPage="error.jsp" %>


isErrorPage
:

isErrorPage=”false | true”

.
isErrorPage in JSP translate JSP engine
to display exception or not. If set false, we can not use exception objects in JSP
page. Default value is true.


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
95

of
111



<%@ page isErrorPage="true" %>


isThreadSafe
:
isThreadSafe="true |

false"

.
This attribute translate as JSP class is
thread safe or not. In multiple threads, concurrent number of users can request to
JSP page. JSP process this request, this results in using variable, code at a same
time. We can synchronize request to JSP
with this attribute. If

isThreadSafe is
false, one request process to JSP at same time, and implement as
SingleThreadModel. We suggest to use isThreadSafe in rare cases when really need
it.


<%@ page isThreadSafe="true" %>


Buffer
:
buffer="none | 8k |

size"

.
buffer in page directive specify the buffer size of
out object to print on client browser. Default size of buffer is 8k, can change to as
requirement.



<%@ page buffer="16kb" %>


autoFlush
:
autoFlush=”true | false”

.
when buffer get full it i
s automatically flush,
if it is set as true. In false case, it throws exception of overflow.



<%@ page autoFlush="true" %>


s
ession
:
s
ession=”true | false”
.
Session attribute in page translate to JSP engine
to use session object in current JSP page.

If session attribute set as false in page
directive we can not use session in current JSP.By default it is true.



<%@ page session="true" %>


e
xtends
:
extends=”class.package.ClassName”

.
extends is used to override the
class hierarchy provided by J
SP container. It is something like to deploy own our
classes instead of using JSP container classes. It should be used with precaution
unless you know it clearly. It is used when we need tag libraries.



<%@ page extends="com.myapp.ClassName" %>


f.

ac
tion elements:

These will be considered at the time of execution.Means action
elements typically perform some action based on information that is required at the
exact time the JSP page is requested by a browser. An action can, for instance, access
paramet
ers sent with the request to do a database lookup. It can also dynamically
generate HTML, such as a table filled with information retrieved from an external
system.The JSP specification defines a few standard action elements, listed in Table.


action eleme
nts



Description

<jsp:useBean>

Makes a JavaBeans component available in a page

<jsp:getProperty>

Gets a property value from a JavaBeans component and
adds it to the response

<jsp:setProperty>

Sets a JavaBeans component property value

<jsp:include>

Includes the response from a servlet or JSP page during
the request processing phase

<jsp:forward>

Forwards the processing of a request to servlet or JSP
page

<jsp:param>

Adds a parameter value to a request handed off to
another servlet or JSP page using

<jsp:include>

or
<jsp:forward>

<jsp:plugin>

Generates HTML that contains the appropriate browser
-
dependent elements (OBJECT or EMBED) needed to
execute an applet with the Java Plug
-
in software


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
96

of
111



8.4.


Implicit Obects


Implicit objects in jsp are the
objects that are created by the container automatically and
the container makes them available to the developers, the developer do not need to create
them explicitly. Since these objects are created automatically by the container and are
accessed using sta
ndard variables; hence, they are called implicit objects. The implicit
objects are parsed by the container and inserted into the generated servlet code. They are
available only within the jspService method and not in any declaration. Implicit objects are
u
sed for different purposes. Our own methods (user defined methods) can't access them
as they are local to the service method and are created at the conversion time of a jsp into
a servlet. But we can pass them to our own method if we wish to use them local
ly in those
functions.

There are nine implicit objects. Here is the list of all the implicit objects:


1.

out
: is javax.servlet.jsp.JspWriter class use for printing. Out is Output Stream use
response.getWriter() to send output to client

<%


out.write("Thi
s is use for print output stream on client");

%>


2.

page
: is used by java.lang.Object class. Page is instance of JSP page’s Servlet.

<%


Object page = this;

%>


3.

pageContext
:pageContext instance that contains all data’s information, which is
associated with JSP page. This helps to access attribute and other field’s object
set in JSP page. pageContext is in javax.servlet.jsp.PageContext class.
pageContext is to managed vario
us scope of attribute in shared information
object.This object will be useful in custom tag development.Method of
pageContext are following:


pageContext.getException() Exception Get current value of the exception Object

pageContext.getOut() JspWriter Ge
t current value of out object

pageContext.getRequest() ServletRequest Get current value of request object

pageContext.getResponse() ServletResponse Get current value of response
object

pageContext.getServletConfig() ServletConfig Get any initialization
parameters
and startup configuration for this servlet

pageContext.getServletContext() ServletContext Gets the context from the
servlet's ServletConfig object

pageContext.getSession() HttpSession Return the current value of session object


4.

request
:
The

H
ttpServletRequest

object that
javax.servlet.http.HttpServletRequest interface is provided to access request
objects in JSP. The HTTP request is send to server through request object.


5.

response
:The HttpServletResponse object that
javax.servlet.http.HttpServ
letResponse interface is provided to send response
object in JSP. The HTTP response is send to client through response object
.



6.

session
:Session object is used to track information about a user, session is
interface and maintain by HttpSession javax.serv
let.http.HttpSession.


7.

config
:is related to get servlet’s configuration information. It is in
javax.servlet.ServletConfig interface. Servlet configuration object is used to pass
information of servlet to Servlet container during initialization of servlet.
This is
defined in web.xml file with <init
-
param> and method is used to get
getServletConfig()


<servlet>


<servlet
-
name>ServletName</servlet
-
name>


<servlet
-
class>com.myapp.servlet.ServletName</servlet
-
class>


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
97

of
111


<init
-
param>


<param
-
name>dbUserName</param
-
name>


<param
-
value>root</param
-
value>


</init
-
param>

</servlet>


Method use to get init param is getInitParameter() to get value inside <param
-
value> and getInitParameterNames() to get name of <param
-
name>


8.

application
:is used to share information for all JSPs and Servlets in the
application context. Application is in javax.servlet.ServletContext.


9.

exception
:Exceptions are condition that can be caught and recovered from it. If
exception is not caught it should throw on

error page. Exception when throw on
error page it should be isErrorPage= true at in directive page.

<%@ page errorPage="error.jsp" %>

<%@ page isErrorPage="true" %>


Example1:
Demonstration of using JSP declaration,scriptlets, expression and comments.

<%!

int i=10;

int j=10;

public int getSum()

{


return i+j;

}

%>

<%=getSum()%><br>

<%

out.println(getSum());

%>

<br>

<
!
--

Html Comments
--
>

<%
--

SP Comments
--
%>


<%

for(int
k
=1;
k
<=10;
k
++)


{


%>


<%=k
%><br>


<%}%>


Output:



Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
98

of
111

Example
2
:
Exception Implicit object in JSP

exception.jsp

<%@ page errorPage = "error.jsp" %>

<%

int i=Integer.parseInt("23a");

out.print(i);

%>


error.jsp

<%@ page isErrorPage="true" %>

<html>

<head>

<title>Implicit Exception Error page</title>

</head>

<body>

The
Exception is <strong><%= exception.toString() %></strong><br>

Message : <strong><%=exception.getMessage()%></strong><br>

</body>

</html>


8.5.


Session Programming


Session object is medium to interact with client and server. Session is a connection
between user and server, involving exchange of information between user’s computer and
server. Server knows information about each other by these session object. Web serve
r
put information of user in session object and whenever it needs information gets it from
these session objects. This session object stores information in key value pair, just like
hashtable.


Today programming without session cannot

be

thinkable. Most o
f web application is user
based, somewhat use transaction (credit card, database transaction), shopping cart,
email, and this needs session. Web server should know who is doing this transaction. This
session object helps to differentiate users with each ot
her, and increase application’s
security. Every user have unique session, server exchange information with session
objects until it get expired or destroyed by web server.



When to use
Session
:
Mostly session is work with user base application, when
login
screen is used then set session if login is successful. It set for maximum
time provided by web
.xml

or defined by application.



When to destroy Session:
When user has done their work and want to close
browser, it should be expire or destroy forcefully by u
ser, ensure no other person
can use his session.



Usage of Session:
To get HttpSession obect, we need to call getSession() on
request obect like below:


HttpSession session = request.getSession(true);


Def between getSession(true) /ge
tSession() and getSession(false
)
:
Both
request.getSession()
and
request.getSession(true)
are same.They
will return the
current session and if one does not exist, a new session will be cretaed.


If we

use request.getSession(false), it will return the current

session if one exists
and if one DOES NOT exist
,

a new one will NOT be cretaed.


session.setAttribute("
name
",
value
) is use to set new session variable. If we need
to retrieve session variable, have to use session.getAttribute
(“name”)
. In this we
have to get it by session variable name here we are using
“name”

is session
variable as key.New session can be find by isNew() method of session, when first
time session is created, that is new session.



Inactivate Session Automatically:
To inactivate session at runtime, use
session.setMaxInactiveInterval(2700), this

will

set maximum session time. 2700 is

Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
99

of
111

time in number. In this period, if user don’t do anything session get expired
automatically.
we can also specify the session period in we
b.xml like below:


<session
-
config>


<session
-
timeout>


30


</session
-
timeout>

</session
-
config>



Expire Session

Forcefully

or
Remove
All
Session Variables
:
When session is
no long needed, should be removed forcefully by user. This
can be done by calling
session method of invalidate method

session.invalidate();

This method expires
session for current user, who request for log out.


Example3
:
Demonstration of using session object for marriage details.

bride.html

<form name="f1" method=
"ge
t" action="
/
Marriage
/ses1.jsp">


<table border=
1
>



<tr><td>Bride</td><td><input type=text name="txt
Bride
"

value="" ></td></tr>


<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>


</table>


</form>


ses1.jsp

<%


String st=request.getParameter("
txt
Bride
");


session.setAttribute("bride",st);


%>


<form name="f1" method="ge
t" action="
/
Marriage
/
ses2.jsp">


<table border=
1
>


<tr><td>BrideGrome</td><td><input type=text name="txtBG"

value=""
></td><
/tr>


<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>


</table>


</form>


s
es
2
.jsp

<%

session.setAttribute("BG",request.getParameter("txtBG"));

%>

<center>

<form name="f1" met
hod="get" action="
/
Marriage
/
ses3.js
p">

<table border=
1
>

<tr><td>BrideAge</td><td><input type=text name="
Bage
"

value="" ></td></tr>

<tr><td>Groom Age</td><td><input type=txt name="
BGage
" value=""></td></tr>


<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>


</table>

</form>


s
es3.jsp

<table border="1" align="center">


<thead>


<tr><th>Marriage</th><th>Name</th><th>Age</th></tr>


</thead>


<tbody>


<tr>


<td>Bride</td>


<td><%=session.getAttribute("bride")%></td>


<td><%=request.getParameter("
Bage
")%></td>


</tr>


<tr>


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
100

of
111


<td>BrideGroom</td>


<td><%=session.getAttribute("BG")%></td>


<td><%=request.getParameter("
BGage
")%></td>


</tr>


</tbody>

</tabl
e>


Output

of the above application like below:







8.6.


Cookie

Programming


Cookie a small data file reside in user’s system. Cookie is made by web server to identify
users. When user do any request send to web server and web server know information of
user by these cookie. After process request, web server response back to reques
t by
knowing through this cookie. JSP provides cookie classes, javax.servlet.http.Cookie, by
this classes we can create and retrieve cookie. Once we set value in cookie, it lived until
cookie gets expired. Cookie plays a big role in session, because maximu
m session is
tracked by cookie in
Servlets
.



creating Cookie
:

Cookie cookie = new Cookie ("
key
",
value
);


Then we are adding in cookie of res
ponse object like:
response.addCookie(cookie);



Expire cookie
:
To destroy the cookie we need to create the

cookie with the same
name and we need to their maximum age like below:


Cookie cookie = new Cookie ("cookieSet",cookieSet);

cookie setMaxAge(0);


This will expire cookie.,with 0 second.



Retrieve cookie
:
Cookie is in array object, we need to get i
n reques
t.getCookies()
of array like below:


Cookie[] cookies = request.getCookies();

for (int i=0; i<cookies.length; i++) {


out.println(cookies[i].getName()+" : "+cookies[i].getValue()+"<br/>");

}


Example4
:
Demonstration of using
Cookie’s

for marriage details.

bride.html

<form name="f1" method="get" action="http://localhost:8084/cooki/cook1.jsp">



<table border="1" >


<tr><td>Bride</td><td><input type=text name="txt
Bride
" value="" ></td></tr>


<tr><td colspan=2 align=center><input

type="submit" name="sub"
value="Go"></td></tr>


</table>


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
101

of
111


</form>


cook1.jsp

<%


String st=request.getParameter("
txt
Bride
");


Cookie c1=new Cookie("bride",st);


response.addCookie(c1);


%>


<form name="f1" method="get" action="http://loc
alhost:8084/cooki/cook2.jsp">


<table border="1" >



<tr><td>BrideGrome</td><td><input type=text name="txtBG" value=""
></td></tr>


<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>


</table>


</form>


cook2.jsp

<form name="f1" method="get" action="http://localhost:8084/cooki/cook3.jsp">


<table border=1>



<tr><td>BrideAge</td><td><input type=text name="
Bage
" value="" ></td></tr>


<tr><td>Groom Age</td><td><input type=txt name="
BGage
"
value="
"></td></tr>


<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>


</table>


cook3.jsp

<% Cookie ck[]=request.getCookies();%>

<table border="1" align="center">


<thead>


<tr><th>Marriage</th><th>Name</th><
th>Age</th></tr>


</thead>


<tbody>


<tr>


<td>Bride</td>


<td><%=ck[0].getValue()%></td>


<td><%=request.getParameter("
Bage
")%></td>


</tr>


<tr>


<td>BrideGroom</td>


<td><
%=ck[1].getValue()%></td>


<td><%=request.getParameter("
BGage
")%></td>


</tr>


</tbody>

</table>


Output

of the above application like below:







Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
102

of
111




8.7.


Include
s

and Forwards


We can include a file at transalation and execution time.


D
irective

include
:

is used to include any file’s content into other desired file. This process
is useful when need a separate header, footer, menu bar, or any common content need to
reuse on other pages.This JSP include can be static or dynamic.Static include in JSP does
in
clude one file content into desired file at translation time, after that JSP page is
compiled.



action include
:
This include execute first file and then output of this file include in desired
file.
It will be happen at runtime.If you observe the below examp
le; it will include the
output of the B.jsp in A.jsp every time A.jsp page is requested.

We can send parameters
to including file also.


a
ction forward
:
<jsp:
forward>

will forward the request to
called

page same like
<jsp:include>,but here the control
will
never come back to the caller
page
where

as
in
case of <jsp:include>,
the
control will come back to the
caller

page.


Example5:
Demonstration of using directive and action includes.

A.jsp

<jsp:include page="/B.jsp">


<jsp:param name="
book
" value="
EasyJavaWeb
"/>


</jsp:include>


<%@include file="
footer
.jsp"%>


B.jsp

Here Is the interested book for Java WebTechnologies.<br>


<%


out.println("Favourite Book is "+request.getParameter("book"));


%>


f
ooter.jsp

<h1> This is Footer</h1>


8.8.


JavaBeans


The JavaBeans specification defines a set of programming conventions for Java classes
that should be used as pluggable components. Bean is a reusable component which mostly
contains the setter and getter values, we also called it as mutators
.
To work with java
components we will use <jsp:useBean> which l
ocates or instantiates a Bean with a
specific name and scope.

Syntax

<jsp:useBean



id="beanInstanceName"



scope="page|request|session|application"



class="package.class"

>
child

tags </
jsp:useBean>


The <jsp:useBean> tag attempts to locates a Bean, or if the Bean does not exist,
instantiates it from a class or serialized template. To locate or instantiate the Bean,
<jsp:useBean> takes the following steps, in this order:


Attempts to
locate a Bean with the scope and name you specify

OR
d
efines an
object reference variable with the name you specify.


If it finds the Bean, stores a reference to it in the variable. If you specified type,
gives the Bean that type.


If it does not find the
Bean, instantiates it from the class you specify, storing a
reference to it in the new variable

with scope you specify
.


if it has body tags (between <jsp:useBean> and </jsp:useBean>), executes the
body tags.


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
103

of
111

The body of a <jsp:useBean> tag often contains

a <jsp:setProperty> tag that defines
property values in the object.


Attributes
of useBean action
:
Here I am listing out some of frequently used attributes.


id
="beanInstanceName"
which
Names a variable that identifies the Bean in the scope you
specify. You can use the variable name in expressions or scriptlets in the same JSP file.


scope
="page|request|session|application"

which d
efines a scope in which the Bean exists
and the variable

named in id is available. The default value is page.


a.

page
: It means that we can use the Bean within the JSP page.

b.

request
: It means that we can use the Bean from any JSP page

which

processing
the same request.

c.

session
: It means that we use the Bean fro
m a
ny Jsp page in the same
session.Means it is per client.

d.

application
: It means that we use the Bean from any page in the same
application
.

Means it will be accessible to all clients.


class
="package.class"

which i
nstantiates a Bean from a class, using t
he new keyword
and the class constructor. The class must not be abstract and must have a public, no
-
argument constructor.


<jsp:
s
etProperty
>
:
It is a child tag of useBean.
We can call bean setter methods using
<jsp:setProperty>.Here is the syntax.


<jsp:set
Property name = "nameOfBeanInstance"

property="*"| propertyName

value=string | <%= expression%>

param=requestparameter name


>

When you use the <jsp:setProperty>

action, the container takes care automatically of the
conversion from text values to the Java types.

<jsp:
getProperty
>
:

It is a child tag of useBean.
we can call bean getter methods using
<jsp:setProperty>.Here is the syntax.


<jsp:getProperty
name="nameOfBeanInstance" property="propertyName"/>


POJO
:
Stands for Plain Old Java Object which should be coded before you are working with
<jsp:useBean>.


To collect this data, we define a Java class with fields "username", "email" and "age" and
we provi
de setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter"
method is just a method that starts with "set" followed by the name of the field. The first
character of the field name is upper
-
cased. So if the field is "email", its "sette
r" method
will be "setEmail". Getter methods are defined similarly, with "get" instead of "set". Note
that the setters (and getters) must be public.


package user;

public class UserData {


String username;


String email;


int age;



public

void setUsername( String value )


{


username = value;


}



public void setEmail( String value )


{


email = value;


}


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
104

of
111



public void setAge( int value )


{


age = value;


}



public String getUsername() { return username; }



public String getEmail() { return email; }



public int getAge() { return age; }

}


The method names must be exactly as shown. Once you have defined the class, compile
it and make sure it is ava
ilable in the
WEB
-
INF/classes folder
.


Example6:

Demonstrion of using useBean.

Input.html

<HTML>

<BODY>

<FORM METHOD=POST ACTION="
collect
.jsp">

name <INPUT TYPE=TEXT NAME=username SIZE=20><BR>

e
-
mail<INPUT TYPE=TEXT NAME=email SIZE=20><BR>

<INPUT TYPE=TEX
T NAME=age SIZE=4>

<INPUT TYPE=SUBMIT>

</FORM>

</BODY>

</HTML>


All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag. The
useBean tag will look for an instance of the "user.UserData" in the session. If the instance
is already t
here, it will update the old instance. Otherwise, it will create a new instance of
user.UserData (the instance of the user.UserData is called a bean), and put it in the
session.

The setProperty tag will automatically collect the input data, match names a
gainst the
bean method names, and place the data in the bean.

collect.jsp

<jsp:useBean id="user" class="user.UserData" scope="session">


<jsp:setProperty name="user" property="age" param=”age”/>

<jsp:setProperty name="user" property="username"
value="<
%=request.getParameter("kk")%>"
/>

<jsp:setProperty name="user" property="
email
" value="
siva@javasiva.in
"/>


</jsp:useBean>

<HTML>

<BODY>

<A HREF="NextPage.jsp">Continue</A>

</BODY>

</HTML>


The point to remember here is that if request parameter names and

bean field names are
equal then setter methods will be called automatically using
property=”*”
.


NextPage.jsp

<jsp:useBean id="user" class="user.UserData" scope="session"/>

<HTML>

<BODY>

You entered<BR>

Name: <%= user.getUsername() %><BR>

Email: <
jsp:get
Property name=”user”

property=”e
mail
”/
><BR>

Age: <%= user.getAge() %><BR>

</BODY>

</HTML>


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
105

of
111


Notice that the same useBean tag is repeated. The bean is available as the variable
named "user" of class "user.UserData". The data entered by the user is all coll
ected in the
bean.


8.9.


Memory Usage Considerations


You should be aware that all objects you save in the application and session scopes take
up memory in the server process. It's easy to calculate how much memory is used for the
application scope
because you have full control over the number of objects you place
there. But the total number of objects in the session scope depends on the number of
concurrent

sessions, so in addition to the size of each object, you also need to know how
many concurre
nt users you have and how long a session lasts. Let's look at an example.


If our site is having good amount of customers and each customer requires 56bytes, you
may have 20 users shopping per hour. The default timeout for a session is 30 minutes, so
let
's say that at any given moment, you have 10 active users and another 10 sessions that
aren't active but have not timed out yet. This gives a total of 20 sessions times 56 bytes
per session, a total of 1,120 bytes. In other words, roughly 1 KB
--

nothing t
o worry
about.


Now let's say our site becomes extremely popular, with 4,000 customers per hour. Using
the same method to calculate the number of concurrent sessions as before, you will have
4,000 sessions at 56 bytes; a total of roughly 220 KB
--

still

nothing to worry about.

However, if you store larger objects in each session, say the result of a database search
with an average size of 10 KB, it corresponds to roughly 40 MB for 4,000 sessions.


If this happens continuously then our application perfo
rmance will be degrade because
most of the server memory occupied for storing user related information.so we need to
take care of these aspects.


Here are some things you can do to keep the memory requirements under control:




Place only objects that real
ly need to be unique for each session in the session
scope. In the shopping cart example,
we can store
cart

in the session
,
but the
catalog bean should not be in session and it is better to place it in application scope
because these beans

are shared by al
l users.



Set the timeout period for sessions to a lower value tha
n the default. If you know
that your users le
ave the site for 30 minutes then

use a shorter period. You can
change the timeout for all sessions in an application through the application's
d
eployment descriptor, or by calling se
ssion.setMaxInactiveInterval( )
.



Provide a way to end the session explicitly. A good example is a logout function, or
invalidation of the session when something is completed (for instance when an order
form is submit
ted). In a JSP page, you can use the HttpSession invalidate( )
method
.

Invalidating a session makes all objects available for garbage collection
(the term used for when the Java runtime removes unused objects to conserve
memory).


8.10.

JSP Application Usin
g MVC


The Model
-
View
-
Controller, or MVC, method of programming is widely used in object
oriented programming and using J2EE. According to MVC, your JSP applications will be
easy to update, easy to break up (for the purpose of
scaling
), and easier to maint
ain when
you use this method.

The Model
-
View
-
Controller, or MVC, method of programming is well
-
known as a scalable
and modular approach for object
-
oriented programming. This method breaks up programs
into three sections: the Model, the View, and the Contro
ller. The Below figure shows a
basic diagram of the MVC method.


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
106

of
111




The
Model

is where the

business logic(

true logic
) of a program.Here it deals with
data for processing.



The
View

is what the application user sees. This is the layout or GUI (graphical user
interface), in which the user can enter data into the program and see results.



The
Controller

is the core of the program that controls all interactions within the
application. For example, if a user enters data, it is first sent to the Controller, which
sends the information to the appropriate area
(model)

to be processed. The results
are then sent

back to the Controller, which finally returns the results to the
appropriate display. The Controller is the
Special point of contact(SPOCP)

of an
application.


When we are

breaking up an application in this way, a programmer can easily make
changes to one

section of the code without having to affect any of the others. If you need
to change some logic, simply change the Model. If you need a new GUI, edit the View. If
you want to add a more granular security construct, edit the Controller.


If you want to ch
ange the GUI, you must
work

around both the Controller and Model
aspects of your JSP page. This can lead to unmanageable code and eventually requires a
total redo of your code.


In the J2EE environment, it is generally recommended to use a servlet as the C
ontroller.
JavaBeans, Java classes, and Enterprise JavaBeans (EJB) components are then used for
the Model. Then, JSP is reserved for the View.


Planning our JSP
-
MVC Application
:
The first
step is

to break up the design (View) logic
(Model), and Controller
parts of our application
.


MVC1 Model Architecture:
Here JSP will be act as a Controller and
View.Javabean will be
act as a Model.
Here the numbers along with flow lines are explaining that how the flow will
be happen.



Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
107

of
111

MVC
2

Model Architecture:

Here JSP wi
ll be act as a view,servlet will be act as controller
abd javabean will be act as a Model.This architecture is best.Struts framework following
MVC2 pattern only.

Here the numbers along with flow lines are explaining that how the
flow will be happen.



We
can develop our JSP application using any of the above architectures.
Here I am taking
MVC2 arthicture in my e
xample

like below.


Example7:
To describe the MVC2 architecture using JSP


Login.jsp

(VIEW)

<form name=login method=post action="/Cart/LoginCheck">


<table align=center>

<tr><td>UserName</td><td><input type=text name="uid"></td></tr>

<tr><td>Password</td><td><input type=password name=pwd></td></tr>

<tr><td
><input type=submit value=Login
></td>

</table>

</form>


LoginCheck.java


(CONTROLLER)

public
void doGet(HttpServletRequest req,HttpServletResponse res) throws………………

{

………………………

…………………………….

String su=request.getParameter("uid");

String sp=request.getParameter("pwd");

DataUtility dbutil=new DataUtility();

if(
dbutil.
isAuthenticated(su,sp))

{

respons
e.sendRedirect(“/Cart/Catalog.jsp”);

}

else

{

response.sendRedirect(“/Cart/
register
.
html
”);

}

……………….

}


DataUtility.java

(MODEL)

impot java.sql.*;

public class DataUtility

{

public boolean isAuthenticated(String usr,String pwd)

{

boolean isThere=false;

try{

Connection con=null;

Class.forName("oracle.jdbc.driver.OracleDriver");


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
108

of
111

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger");

PreparedStatement ps=con.prepareStatement("select * from customer where custname=?
and custp
wd=?");

ps.setString(1,usr);

ps.setString(2,pwd);

ResultSet rs=ps.executeQuery();


if(rs.next())

isThere= true;


else


isThere=false;

}catch(Exception e)


{


e.printStackTrace();


}

return isThere;

}

}


8.11.

Accessing Database

from JSP


It is very simple that how we are accessing database from servlets and applicaton
program,in the same we can access database from JSP.
Here I am taking an example to
check whether the user is authenticated or not.


Login.
html

<form name=login
method=post action="/Cart/LoginCheck
.jsp
">

<table align=center>

<tr><td>UserName</td><td><input type=text name="uid"></td></tr>

<tr><td>Password</td><td><input type=password name=pwd></td></tr>

<tr><td
><input type=submit value=Login
></td>

</table>

</form
>


LoginCheck.jsp

<%@page import="jav
a.sql.*" errorPage="/error.jsp"
%>


<%


String su=request.getParameter("uid");


String sp=request.getParameter("pwd");


Connection con=null;


Class.forName("oracle.jdbc.driver.OracleD
river");


con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger")
;


PreparedStatement ps=con.prepareStatement("select * from customer where
custname=? and custpwd=?");


ps.setString(1,su);


p
s.setString(2,sp);


ResultSet rs=ps.executeQuery();


if(rs.next())


{

out.print(“Authenticated”);


}


else


{

out.print(“Not Authenticated”);


}


%>


8.12.

Custom Tag


There are only handful of tags in JSP which may not be sufficient for each and every
working. You may require to make custom tags which will work according to user
requirement. This functionality can be achieved by making a customized tag. For making a

Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
109

of
111

cus
tomized tag you have to implement Tag interface and you are required to override
following methods in your tag class. These are as follows:

Tag Handler
:
The tag is defined in a handler class. TagSupport is the base class used for
simple tags. It can be fou
nd in the javax.servlet.tagext package. What your tag is
implementing will depend on what methods could potentially be called and what needs to
be implemented. TagSupport and TagBodySupport supply default implementations of the
methods listed below.


1.

The
tags may have the default values, so the default values are readed and after that
setPageContext()
,
setParent()

and the
setters
of all

the attributes are invoked.

2.

After the initialization of all the properties
doStartTag()
method is envoked. It may return
SKIP_BODY
or
EVAL_BODY_INCLUDE
.

3.


doEndTag()

is called if and only if the tag ends
and possible values are SKIP_PAGE and
EVAL_PAGE.

4.

release()
will be called to releases the resources which are allocated to the tag.

When and What to Use:

If your Tag Handler

You need to implement the following methods

has no attributes and no
body

doStartTag, doEndTag, release

has attributes

doStartTag, doEndTag, set/getAttribute1...N

has a body with no
interaction

doStartTag, doEndTag, release

has a body with interaction

doStartTag, doEndTag, release, doInitBody, doAfterBody


Algorithm:

To explain the creation and usage of a custom tag.

Step1
:Create Tag Handler like below.

package com.customtags;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.*;


Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
110

of
111

public class HelloTag extends TagSupport {


public int doStartTag() throws JspException {


try{


JspWriter out=pageContext.getOut();


out.print("Hello

World
<br>");


} catch(Exception e)


{





}




return SKIP_BODY;


}



public int doEndTag() throws JspException {


return EVAL_PAGE;


}

}


Step2
:Use .tld file to describe about the tag handler in Tag Library Descritptor like below:

<tag>


<nam
e>Hai</name>


<tag
-
class>com.customtags.HelloTag</tag
-
class>


<body
-
content>empty</body
-
content>


</tag>


The above content is placed in info.tld

Step3
:To use custom tag in JSP, then we need to follow either of the below procedures:

a.

By specifying taglib uri from web.xml
in JSP using taglib directive like below


<%@taglib uri="first" prefix="h"%>




<h:Hai></h:Hai>






b.

By specifying direct location of tld

in JSP like below:

<
%@taglib uri="/WEB
-
INF/info.tld" prefix="h"%
>

<h:Hai></h:Hai>

Here is my
simple words to explain that

how
a
cu
stom tag works, using the "Hai
" tag as
an example:


When "hello_tag.jsp" page is requested for the first time, server will translate the
JSP page into a java class.


When the <h:
Hai
/> custom tag is encountered during the translation, server will
follow the tld file to locate the HelloTag.class file. Note th
at the tld file
.



Then server will replace the custom tag with some Java code to instantiate an
object of the tag class, initialize the object, and call the doStartTag() method.


To output data into page, you can get an output stream from the pageContext
o
bject provided by the JSP tag extension facility, pageContext.getOut(). This is
how the "Hello world" message gets produced in the
Browser.


Example9:
Demonstration of
Custom Tag
with attributes.

HelloName.java

package com.customtags;

import javax.servlet.j
sp.tagext.*;

Web.xml

<taglib>


<taglib
-
uri>first</taglib
-
uri>

<taglib
-
location>/WEB
-
INF/info.tld</taglib
-
location>
</taglib>



Easy
Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
111

of
111

import javax.servlet.jsp.*;

public class HelloName extends TagSupport{


public String say;


public void setSay(String s)


{


say=s;


}


public String getSay()


{


return say;


}




public int doStartTag() throws JspException {


try{





JspWriter out=pageContext.getOut();


out.print("Hello"+getSay());


} catch(Exception e)


{




}




return SKIP_BODY;



}



public int doEndTag() throws JspException {


return EVAL_PAGE;


}

}


info.tld

<?xml version="1.0" encoding="UTF
-
8"?>

<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-
instance"
xsi:s
chemaLocation="http://java.sun.com/xml/ns/j2ee web
-
jsptaglibrary_2_0.xsd">


<tlib
-
version>1.0</tlib
-
version>


<short
-
name>info</short
-
name>


<uri>/WEB
-
INF/info</uri>




<tag>


<name>Hello</name>


<tag
-
class>com.customtags.HelloName<
/tag
-
class>


<body
-
content>empty</body
-
content>


<attribute>


<name>say</name>


<required>true</required>


<rtexprvalue>true</rtexprvalue>


</attribute>


</tag>


</taglib>



<r
equired

>
is to tell that

this attribute is mandatory.


<rtexprvalue>

is to tell that we can send value for this attribute through runtime
expression.


Tags.jsp

<%@taglib uri="/WEB
-
INF/info.tld" prefix="h"%>

<%

String s="PeddaNaidu”;

%>

<h:Hello say="Karka"></h:Hello><br>

<h:Hell
o say="<%=s%>"></h:Hello><br>