Brown Bag Discussion - Java Server Pages Wednesday, April 23, 2003
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 (Microsofts 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 todays 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 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.
1 2
The SDK use to be called the JDK (Java Development Kit). 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.
62318802.doc
by Professor Stumpf
7/6/11
1 of 9
Brown Bag Discussion Java Server Pages Wednesday, April 23, 2003
Table 1 A simple JSP Page <html> <!-- 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 --> <head> <title>JSP Clock Demo</title> </head> <body> <%@page import = "java.util.Date"%> <%@page import = "java.text.DateFormat"%> <%!DateFormat dateFormat;%> <%dateFormat = DateFormat.getDateInstance();%> <h1>JSP Clock Demo</h1> Current Time: <%=dateFormat.format(new Date())%> </body> </html> 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.
All of the demonstrations are done in Tomcat 4.0. All Java Beans developed herein wer created in Eclipse.
62318802.doc
by Professor Stumpf
7/6/11
2 of 9
Brown Bag Discussion Java Server Pages Wednesday, April 23, 2003
<!-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" %> <jsp:useBean id = "adder" class = "AdderBean"/> <head> <title>Adder JSP Example</title> </head> <body> <!-- 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 --> <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>
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 62318802.doc by Professor Stumpf 7/6/11 3 of 9
Brown Bag Discussion Java Server Pages Wednesday, April 23, 2003
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 programmers use. Most of the time a series of combo boxes are used. I had one student 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
62318802.doc
by Professor Stumpf
7/6/11
4 of 9
Brown Bag Discussion Java Server Pages Wednesday, April 23, 2003
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
<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.ReservationDataBean"/> <head> <title>Rate JSP Example</title> </head> <body> <!-- enter scriptlet --> <% String txtRate = request.getParameter("rate"); String rate; if (txtRate != null) { rate = txtRate; %> <!-- enter html --> <h1> <p>Rate is <%=rate %> </h1> <!-- enter scriptlet --> <% } else { %> <!-- enter html -->
62318802.doc
by Professor Stumpf
7/6/11
5 of 9
Brown Bag Discussion Java Server Pages Wednesday, April 23, 2003
<form action = "rateSelect.jsp" method = "get"> <p> Select your rate and press Submit</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 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 += "<option>"; rates += results.getString(1); } return rates; // }
Obtaining a Complete SQL Table from a Database The task of showing a complete table from a database seems daunting. However, Paul Deitel 5came 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
5
Harvey Deitel, Deitel, Paul, and Santry S., Advanced Java 2 Platform How to Program, Prentice Hall, 2002, ISBN 0-13-089560-1.
62318802.doc
by Professor Stumpf
7/6/11
6 of 9
Brown Bag Discussion Java Server Pages Wednesday, April 23, 2003
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 <html> <!-- 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" %> <jsp:useBean id = "reservationData" scope = "request" class = "myjspbeans.ReservationDataBean" /> <head> <title>Reservation List</title> <!-- Thanks to Paul Deitel for this style --> <style type = "text/css"> body {font-family: tahoma, helvetica, arial, sans-serif;} table, tr, td, th { text-align: center; font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> </head> <body> <p><h2>Reservation List</h2></p> <table> <thead> <tr> <th>ReservationNumber</th> <th>Name</th> <th>Phone Number</th> <th>Date Out</th> <th>Date In</th> <th>Rate</th> </tr> </thead> 62318802.doc by Professor Stumpf 7/6/11 7 of 9
Brown Bag Discussion Java Server Pages Wednesday, April 23, 2003
<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.getReservationNumber() %></td> <td><%= reservation.getName() %></td> <td><%= reservation.getPhoneNumber() %></td> <td><%= reservation.getDateOut() %></td> <td><%= reservation.getDateIn() %></td> <td><%= reservation.getRate() %></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 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(); // get row data 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()));
62318802.doc
by Professor Stumpf
7/6/11
8 of 9
Brown Bag Discussion Java Server Pages Wednesday, April 23, 2003
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: http://www.csupomonoa.edu/!rvstumpf/brownbag Bob Stumpf Comments: [email protected]
62318802.doc
by Professor Stumpf
7/6/11
9 of 9