Java Beans Document

infestationwatchΛογισμικό & κατασκευή λογ/κού

28 Οκτ 2013 (πριν από 3 χρόνια και 9 μήνες)

59 εμφανίσεις

Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

1

of
10

Background


In the open systems environment, there appears to be plenty of different technologies to
choose from. After all there are Applets, Servlets, Java Beans, Session EJBs, and Entity
EJBs . So why does one need JSP (Java Server Pages)?


Let us lo
ok at the above technologies. Only one works with browsers. All of the others
are Java back end technologies. When Applets were first introduced, they were quite the
rage. They enabled animation and there was a lot of excitement. However, then came
Jav
a 2. What happened is the new Java API (Application Program Interface) included
swing classes. Then the lawsuit between Sun and Microsoft over Java stopped the ability
of Applets to run in a browser if they used the swing classes.


In an intranet, the
problem is solvable. Just install the plug in to Internet Explorer when
one installs the latest SDK (System Development Kit).
1

But in a business to consumer
model, this will not work. This leaves simple HTML as the only medium for web pages.
Frequentl
y HTML pages talk to the back end server through the use of Servlets. The
problem is HTML is limited in its ability. This is particularly true when compared to the
competition (Microsoft’s Active Server Pages).


The outcome was an open source scripting l
anguage called Java Server Pages. Instead of
using a standard HTML page, we now use an HTML page with embedded Java. The
extension is “jsp”.
2


Developing JSP


Unless one has access to a good IDE such as IBM Web sphere Studio, good low cost
editors do no
t yet exist for JSP. Thus all of my JSP pages were created in Text Pad.
During the fall of 2002 my advanced Java class also developed JSP pages and almost
students had no difficulty.


A first JSP page. Instead of using hello world, I will use a page that

displays today’s
formatted date. The date will be created and formatted in Java. The documentation in
the page shows the key to inserting JSP. All script lets as they are called are inserted in
between a pair of delimiters: <% %>


There are also spec
ial delimiters to insert one
-
line expressions. They are:




@ for imports



! for declarations



= to return a string for use on the html page




1

The SDK use to be called the JDK (Java Development Kit)
.

2

It is very important at this time to make sure this is not confused with Java Script. Java Script was written
by Netscape and is a very different language.

Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

2

of
10

See Table 1. Once any Java is inserted it is remembered throughout the page. This is
true even if one leaves the
expressions or scriptlets.



Table 1


A sim灬e gpm⁐age

㱨tml>




摡te⹪s瀠

>




gpm⁴hat is just a⁢ t m潲e useful than hell漠 w潲l搠


@⁩s f潲 java im灯pt


!⁩s f潲 java 摥clarati潮o


㴠=s f潲 java ex灲essi潮s; the m潳t c潭m潮 way t漠oet a⁳tring

t漠the we戠灡ge


Auth潲: B潢⁓tum灦

>

㱨ea搾

㱴itle㹊pm Cl潣欠aem漼otitle>

㰯hea搾

㱢潤<>

㰥@灡ge im灯pt 㴠=java⹵til⹄ate"%>

㰥@灡ge im灯pt 㴠=java⹴ext.aatecormat"%>

㰥!aatec潲mat 摡tec潲mat;%>

㰥摡tec潲mat 㴠=atec潲mat⹧etaatefnstance();%>

㱨ㄾ1pm C
l潣欠aem漼ohㄾ

Current Time: 㰥㵤=tec潲mat⹦潲mat(湥w aate())%>

㰯扯摹>

㰯html>


T漠runⰠuse a we戠berver engine that su灰潲ts gpm⁡n搠扥ans⸠⁔he m潳t 灯灵lar 潮e is
A灡che T潭cat⸠
3


Using Java Beans


It will not take too long to discover that writing J
ava as a scriptlets is difficult. Thus the
better approach is to use a Java Bean that is developed in a traditional Java

environment.
4

This way they can be debugged with a real debugger. Also the same
Java Bean can be used with ordinary Java and Serv
lets. In my CIS 424 class the same
Data Access Bean is used in a Java applicat ion, Servlet and a JSP page.


The easiest example to learn Java Beans with is to add two numbers in a bean. Table 2
shows such code. Note the minimum number of scriptlets. A
lso a documentat ion
technique is to put a comment each time one enters html and a scriptlet.








3

All of the demonstrations are done in Tomcat 4.0.

4

All Java Beans developed herein wer crea
t ed in Eclips e.

Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

3

of
10

Table 2


rse a⁡ gava Bean t漠o摤⁴w漠num扥rs

<html>

<!
--

adder.jsp
--
>

<!
--


JSP that processes a "get" request containing two numbers


JSP uses a Java Bea
n to do the processing


Note the use of comments to enter html and scriptlets


Author: Bob Stumpf
--
>

<%@ page import = "AdderBean" %>

<jsp:useBean id = "adder" class = "AdderBean"/>

<head>

<title>Adder JSP Example</title>

</head>

<body>

<!
--

enter scriptl
et
--
>



<%



String strNumber1 = request.getParameter( "number1" );



String strNumber2 = request.getParameter( "number2" );



int number1;



int number2;



if ( strNumber1 != null && strNumber2 != null )



{



n
umber1 = Integer.parseInt(strNumber1);



number2 = Integer.parseInt(strNumber2);



adder.setNumber1(number1);



adder.setNumber2(number2);



%>

<!
--

enter html
--
>



<h1>



<p>number 1 is <%= adder.getNumber1() %></p>



<p>number 2 is <%= adder.getNumber2() %></p>



<p>answer is <%= adder.getSum() %></p>



</h1>

<!
--

enter scriptlet
--
>



<%



}




else



{



%>

<!
--

enter html
--
>




<form action = "adder.jsp" method = "get">





<p> Type your two numbers and press Submit</p>





<p><input type = "text" name = "number1"></p>




<p><input type = "text" name = "number2"></p>





<p><input type = "submit" value = "Submit"></p>




</form>

<!
--

enter scriptlet
--
>



<%



}



%>

<!
--

enter html
--
>

</body>

</html>


Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

4

of
10


The code is written recursively. Each time the users clicks submit on the form, the page
is invoked. An
if statement

checks to see if the form is filled out (really checking for null
values). If it is, JSP is used
to parse the data and then the data is sent to a Java bean for
processing. Lastly an expression gets the answer from the Java Bean and a different html
page is presented.


This is a fairly standard to invoke Beans. The scriptlet is entered three times du
e to an
if
then else

statement. The bean is in Table 3.


Table 3


gava Bean t漠o摤dTw漠Num扥rs

/**


*

Bean

to

add

two

numbers


*

@author

Bob

Stumpf


*/

public

class

AdderBean

{


// data


private

int

number1,

number2;


// constructor


public

AdderBean(
)


{}


// methods


public

int

getSum()


{



return

number1

+

number2;


}


// accessors


public

void

setNumber1(
int

number1)


{



this
.number1

=

number1;


}


public

int

getNumber1()


{



return

number1;


}


public

void

setNumber2(
int

number2)


{



this
.numb
er2

=

number2;


}


public

int

getNumber2()


{



return

number2;


}

}



Obtaining a Date from a Form


If you look at a lot of JSP pages, you will find they do not have a calendar like Microsoft
programmers use. Most of the time a series of combo boxes are

used. I had one student
Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

5

of
10

use a calendar by mixing JSP and Java Script. The code worked but was extremely hard
to follow. Also it may not run on all browsers due to Java Script lack of standardized
date logic. I wrote a simple JSP page that uses a Java
Bean to construct a date using the
Gregorian Calendar Class. Because it has many drop down list boxes, the code is lengthy
as in web pages, each of the 31 days is a line in the web page. It is called
dateSelect.jsp
and is available on the web page. It u
ses a bean called
myjspbeans.DateBean.java


Obtaining Data for a Combo Box from a Database


Obtaining the data for a combo box from a database is a fairly common task. For this
example, I used a collection of car rental classes (Economy, Compact, Midsize
etc). Like
the adder JSP page, it uses an
if then else
structure. It appears in Table 4. The key
expreseion is:



<%= rateBean.getRates() %>


Note that the Java Bean is doing most of the work. This is an important principle in JSP.
The more wor
k that can be placed in a Java Bean, the less non
-
traditional debugging is
required. The Java Bean called ReservationDataBean contains the method
getRates
.


Table 4


l扴aini湧 aata f潲 a⁃潭扯bB潸 fr潭 a aata扡se


<html">

<!
--

rateSelect.jsp
--
>

<!
--


JSP that processes a "get" request for a combo box from a database



JSP uses a Java Bean to do the processing.



Author: Bob Stumpf.
--
>

<%@ page import = "myjspbeans.ReservationDataBean" %>

<jsp:useBean id = "rateBean" class = "myjspbeans.ReservationD
ataBean"/>

<head>

<title>Rate JSP Example</title>

</head>

<body>

<!
--

enter scriptlet
--
>

<%



String txtRate = request.getParameter("rate");



String rate;



if (txtRate != null)



{



rate = txtRate;



%>

<!
--

enter h
tml
--
>


<h1>



<p>Rate is <%=rate %>



</h1>

<!
--

enter scriptlet
--
>



<%



}


else



{



%>

Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

6

of
10

<!
--

enter html
--
>


<form action = "rateSelect.jsp" method = "get">


<p> Select your rate and press Subm
it</p>


<p>


Rate

<select name = "rate">




<%= rateBean.getRates() %>



<select>


</p>


<p>

<input type = "submit" value = "Submit" />


</p>


</form
>

<!
--

enter scriptlet
--
>



<%



}



%>

<!
--

enter html
--
>

</body>

</html>




Sorry for the long JSP page, but html has a lengthy way of doing things. The method get
rates is in Table 5 below. Not even though it is using SQL, the cod
e is very simple. The
overhead of opening and closing code is done in other methods.


Table 5


gava jeth潤ot漠oet Car⁒ental oates fr潭 a⁄ata扡se

// Return a string for rate combo box from database

public

String

getRates()

throws

SQLException

{


// obt
ain list of rates


getRates

=

connection.prepareStatement


(
"SELECT Description FROM Rate"
);


ResultSet

results

=

getRates.executeQuery();


String

rates

=

""
;


// get row data


while

(results.next())


{



rates

+=

"<option>"
;



rates

+=

results.getSt
ring(1);


}


return

rates;


//

}



Obtaining a Complete SQL Table from a Database


Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

7

of
10

The task of showing a complete table from a database seems daunting. However, Paul
Deitel
5
came up with a very nice presentation. He used a styles with a table to make w
hat
I think a very nice presentation. When you run the reservation view from the web, I think
you will agree that its appearance is excellent. Table 6 shows the JSP for this code. What
is surprising is that is it is only a page and a half in size. The m
ethod in the Java Bean is
also fairly short. It is shown in Table 7.


Table 6


l扴aini湧 a Ta扬e fr潭 a⁄ata扡se

㱨tml>




viewoeservations⹪s瀠

>





gpm⁴hat 灲潣esses a•get" re煵est c潮tai湩湧 tw漠num扥rs


gpm⁵ses a⁊ava Bean t漠摯⁴he 灲潣e
ssing


N潴e⁴he use 潦 c潭ments t漠enter html an搠scri灴lets


Auth潲: B潢⁓tum灦

>

㰥@⁰ ge err潲mage 㴠=reservatio湅rr潲mage.jsp" %>

㰥@⁰ ge im灯pt 㴠=java⹵til⸪" %>

㰥@⁰ ge im灯pt 㴠=myjs灢pans.oeservationaataBea渢 %>

㰥@⁰ ge im灯pt 㴠=myjs灢pans.o
eservationBea渢 %>

㱪s瀺useBean i搠㴠=reservationaata" sc潰o 㴠=re煵est"



class 㴠=myjs灢pans.oeservationaataBea渢 />

㱨ea搾

㱴itle㹒eser癡tion iist㰯title>




Than歳 t漠maul aeitel f潲 this style

>

㱳tyle ty灥 㴠=text/css">

†††

扯摹 {f潮t
-
fami
l示 tah潭aⰠ helveticaⰠ arialⰠ sans
-
serif;}


ta扬eⰠtrⰠt搬⁴h




††††††

text
-
ali杮g center;

††††††

f潮t
-
size: ⸹.m;

††††††

扯b摥r: ㍰P gr潯oe;

††††††

灡摤dng: 㕰5;

††††††

扡c歧r潵nd
-
c潬潲: ⍤摤摤搻

††††
}

㰯style>

㰯head
>

㱢潤<>

†††

㱰<㱨㈾2eservation iist㰯h㈾2/瀾


㱴a扬e>

††

㱴hea搾

†††

㱴r>

†††††††
㱴h㹒eservationN畭扥r</th>

†††††††
㱴h㹎ame㰯th>

††††††††††††††††††††
††††

5

Harvey Deitel, Deitel, Paul, and Santry S.,
Advanced Java 2 Platform


How to Program
, Prentice Hall,
2002, ISBN 0
-
13
-
089560
-
1.

Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

8

of
10


<th>Phone Number</th>


<th>Date Out</th>


<th>Date In</th>


<th>Rate</th>




</tr>


</thead>


<tbody>

<!
--

enter scriptlet
--
>



<%


List reservationList = reservationData.getReservationList();


Iterator reservationListIterator = reservationList.iterator();



ReservationBean reservation;


while ( reservationListIterator.hasNext() )


{



reservation = ( ReservationBean ) reservationListIterator.next();


%>


<!
--

enter html
--
>



<tr>



<td><%= reservation.g
etReservationNumber() %></td>



<td><%= reservation.getName() %></td>




<td><%= reservation.getPhoneNumber() %></td>




<td><%= reservation.getDateOut() %></td>



<td><%= reservation.getDateIn() %></td>



<td><%= reservation.get
Rate() %></td>



</tr>

<!
--

enter scriptlet
--
>



<%



} // end while


%>

<!
--

enter html
--
>



</tbody>



</table>

</body>

</html>




Table 6
-

Java Method to get Car Rental Resrvations from a Database

// return an ArrayLi
st of reservations

public

List

getReservationList()

throws

SQLException

{


getRecords

=

connection.prepareStatement(
"SELECT * FROM
Reservation"
);


List

reservationList

=

new

ArrayList();


// obtain list of titles


ResultSet

results

=

getRecords.executeQuer
y();


// get row data

Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

9

of
10


while

(results.next())


{



ReservationBean

reservation

=

new

ReservationBean();



reservation.setReservationNumber(results.getInt(1));



reservation.setName(results.getString(2));



reservation.setPhoneNumber(results.getString(3));



reservation.setDateOut(



new

java.util.Date(results.getTimestamp(4).getTime()));



reservation.setDateIn(
new



java.util.Date(results.getTimestamp(5).getTime()));



reservation.setRate(results.getString(6));



reservationList.add(reservati
on);


}


return

reservationList;

}


Inserting a Record into a SQL Table in a Database


To insert a record is not very different from what we have seen. It is not repeated here a
it is six pages long. Again the primary work is done in a Java Bean. The B
ean is called
add reservation with the following signature:


public

void

addReservation




(ReservationBean

reservation)

throws

SQLException


It uses another bean called get last reservation number:


private

int

getLastReservationNumber()

throws

SQLExcept
ion



Other JSP pages are in support of the Database logic. One is the displaying of SQL
errors. It is called
sqlEerrorPage.jsp
. Also when a reservation is made the confirmation
is shown. It is called
reservationViewOne.jsp.


Summary


JSP pages are an e
xcellent way to create consumer to business web sites. The feature of
using a Bean for most of the Java is encouraged as it limits the amount of script to be
debugged.


There is not a lot of resources available. The books are few. The most popular ones

have
links on the web site. The Core Servlets one by Marty Hall I found disappointing. The
clearest one is the one referenced earlier by Paul Deitel.


Thank you very much for your support.


For a copy of all materials and source code information see:

Brown Bag Discussion


Java Server Pages

Wednesday, April 23, 2003


infestationwatch_4a2f2e32
-
45a5
-
40ee
-
83be
-
302938863ebd.doc

by Professor
Stumpf
10/29/13

10

of
10


http://www.csupomonoa.edu/!rvstumpf/brownbag


Bob Stumpf


Comments:
rvstumpf@csupomona.edu