DOC

Java Beans

By Sue Rodriguez,2014-04-24 12:18
8 views 0
Java Beans

    Brown Bag Discussion Java Server Pages

    Wednesday, April 23, 2003

    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 look 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 Java 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.

    Frequently 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 language 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 not 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 special 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). 251277538.doc by Professor Stumpf 4/24/10 1 of 10 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

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 simple JSP Page

    

    -- date.jsp -->

    -- JSP that is just a bit more useful than hello world

     @ is for java import

     ! is for java declarations

     = is for java expressions; the most common way to get a string to the web page

     Author: Bob Stumpf -->

    

    JSP Clock Demo

    

    

    <%@page import = "java.util.Date"%> <%@page import = "java.text.DateFormat"%> <%!DateFormat dateFormat;%>

    <%dateFormat = DateFormat.getDateInstance();%>

JSP Clock Demo

    Current Time: <%=dateFormat.format(new Date())%>

    

    

To run, use a web server engine that supports JSP and beans. The most popular one is

    Apache Tomcat.

    3

Using Java Beans

It will not take too long to discover that writing Java 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 Servlets. In my CIS 424 class the same Data

    Access Bean is used in a Java application, 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. Also a documentation

    technique is to put a comment each time one enters html and a scriptlet.

351277538.doc by Professor Stumpf 4/24/10 2 of 10 All of the demonstrations are done in Tomcat 4.0. 4 All Java Beans developed herein wer created in Eclipse.

    Brown Bag Discussion Java Server Pages

    Wednesday, April 23, 2003

    Table 2 Use a a Java Bean to add two numbers

    -- adder.jsp -->

    -- JSP that processes a "get" request containing two numbers

     JSP uses a Java Bean to do the processing

     Note the use of comments to enter html and scriptlets

     Author: Bob Stumpf -->

    <%@ page import = "AdderBean" %>

    

    Adder JSP Example

    

    

    -- enter scriptlet -->

     <%

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

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

     int number1;

     int number2;

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

     {

     number1 = Integer.parseInt(strNumber1);

     number2 = Integer.parseInt(strNumber2);

     adder.setNumber1(number1);

     adder.setNumber2(number2);

     %>

    -- enter html -->

    

    

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

    

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

    

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

    

    -- enter scriptlet -->

     <%

     }

     else

     {

     %>

    -- enter html -->

    

    

Type your two numbers and press Submit

    

    

    

    

    -- enter scriptlet -->

     <%

     }

     %>

    -- enter html -->

    

    

    51277538.doc by Professor Stumpf 4/24/10 3 of 10

    Brown Bag Discussion Java Server Pages

    Wednesday, April 23, 2003

    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 due to an if

    then else statement. The bean is in Table 3.

    Table 3 Java Bean to Add Two Numbers /**

     * 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.number2 = 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 51277538.doc by Professor Stumpf 4/24/10 4 of 10 programmers use. Most of the time a series of combo boxes are used. I had one student use

    Brown Bag Discussion Java Server Pages

    Wednesday, April 23, 2003

    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 uses 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 work 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 Obtaining Data for a Combo Box from a Database

    

    -- 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" %> ataBean"/>

    

    Rate JSP Example

    

    

    -- enter scriptlet -->

    <%

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

     String rate;

     if (txtRate != null)

     {

     rate = txtRate;

     %>

    -- enter html -->

    

    

Rate is <%=rate %>

    

    -- enter scriptlet -->

     <%

     }

     else

     { 51277538.doc by Professor Stumpf 4/24/10 5 of 10 %>

    Brown Bag Discussion Java Server Pages

    Wednesday, April 23, 2003

-- enter html -->

    

    

Select your rate and press Submit

    

     Rate

    

    

    

     >

    -- enter scriptlet -->

     <%

     }

     %>

    -- enter 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 code is very simple. The

    overhead of opening and closing code is done in other methods.

    Table 5 Java Method to get Car Rental Rates from a Database // Return a string for rate combo box from database

    public String getRates() throws SQLException {

     // obtain list of rates

     getRates = connection.prepareStatement

     ("SELECT Description FROM Rate");

     ResultSet results = getRates.executeQuery();

     String rates = "";

     // get row data

     while (results.next())

     {

     rates += ";

     rates += results.getString(1);

     }

     return rates;

     //

    }

Obtaining a Complete SQL Table from a Database

    51277538.doc by Professor Stumpf 4/24/10 6 of 10

    Brown Bag Discussion Java Server Pages

    Wednesday, April 23, 2003

The task of showing a complete table from a database seems daunting. However, Paul 5Deitel came up with a very nice presentation. He used a styles with a table to make what 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 method in the Java Bean is also

    fairly short. It is shown in Table 7.

    Table 6 Obtaining a Table from a Database

    -- viewReservations.jsp -->

    -- JSP that processes a "get" request containing two numbers

     JSP uses a Java Bean to do the processing

     Note the use of comments to enter html and scriptlets

     Author: Bob Stumpf -->

    <%@ page errorPage = "reservationErrorPage.jsp" %> <%@ page import = "java.util.*" %>

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

     class = "myjspbeans.ReservationDataBean" />

    Reservation List

    -- Thanks to Paul Deitel for this style -->

    

    >

    

    

Reservation List

    

    

    

    

    

551277538.doc by Professor Stumpf 4/24/10 7 of 10 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

    

    

    

    

    

    

    

    -- enter scriptlet -->

     <%

     List reservationList = reservationData.getReservationList();

     Iterator reservationListIterator = reservationList.iterator();

     ReservationBean reservation;

     while ( reservationListIterator.hasNext() )

     {

     reservation = ( ReservationBean ) reservationListIterator.next();

     %>

     -- enter html -->

    

    

    

    

    

    

    

    

    -- enter scriptlet -->

     <%

     } // end while

     %>

    -- enter html -->

    

    

ReservationNumberName Phone NumberDate OutDate InRate
<%= reservation.getReservationNumber() %><%= reservation.getName() %><%= reservation.getPhoneNumber() %><%= reservation.getDateOut() %><%= reservation.getDateIn() %><%= reservation.getRate() %>

    

    

    Table 6 - Java Method to get Car Rental Resrvations from a Database // return an ArrayList of reservations

    public List getReservationList() throws SQLException {

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

     List reservationList = new ArrayList();

     // obtain list of titles

     ResultSet results = getRecords.executeQuery(); 51277538.doc by Professor Stumpf 4/24/10 8 of 10 // get row data

    Brown Bag Discussion Java Server Pages

    Wednesday, April 23, 2003

     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(reservation);

     }

     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 Bean 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 SQLException

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 excellent 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:

    51277538.doc by Professor Stumpf 4/24/10 9 of 10

    Brown Bag Discussion Java Server Pages

    Wednesday, April 23, 2003

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

Bob Stumpf

Comments: rvstumpf@csupomona.edu

51277538.doc by Professor Stumpf 4/24/10 10 of 10

Report this document

For any questions or suggestions please email
cust-service@docsford.com