Developing Web Applications
Using Ada, JGNAT, JavaServer Pages,
and JDBC to Build Web Applications
Terry Westley
SIGAda 2001
What Will You Learn?
• Overview of dynamic web technologies
• Create HTML pages that use JavaServer
Pages (JSP) technology to access and
display dynamic web content
• Write Java Beans and Java servlets in Ada
• Use JDBC in Ada to create, maintain, and
query a relational database
Developing Web Applications with Ada
2
Tutorial Prerequisites
• We assume you are familiar with:
– Creating static HTML pages
– Programming in Ada
• But, not:
– Programming in Java
– SQL
– JavaServer Pages
Developing Web Applications with Ada
3
References
• DuBois, Paul, MySQL, New Riders, Indianapolis, IN, 2000.
• Fields, Duane K., Kolb, Mark A., Web Development with
JavaServer Pages, Manning Publications Co., Greenwich, CT,
2000.
• Goodman, Danny, Dynamic HTML, The Definitive Reference,
O'Reilly and Associates, Sebastopol, CA, 1998.
• Horstmann, Cay S., Cornell, Gary, Core Java 1.1, Volume I -Fundamentals, Prentice Hall, Upper Saddle River, NJ, 1997.
• Lemay, Laura, Perkins, Charles L., Morrison, Michael, Teach
Yourself Java in 21 Days, Professional Reference Edition, Sams
Publishing, Indianapolis, IN, 1996.
Developing Web Applications with Ada
4
Table of Contents
Dynamic Web Technologies
• Required Components
• Introduction to JSP
• Introduction to Java Beans
• Introduction to JDBC
• Building a Web Application
Developing Web Applications with Ada
5
What is a Dynamic Web?
What do I mean by "dynamic?"
• User interaction affects the HTML page
• Data from a server affects the HTML page
Developing Web Applications with Ada
6
Dynamic Web Technologies
•
•
•
•
•
•
•
Static HTML pages
Common Gateway Interface (CGI)
JavaScript
Java applets
Dynamic HTML (DHTML)
Java servlets
Template systems
Developing Web Applications with Ada
7
Static HTML
• Browser requests an HTML document
• Server finds the file and sends it to browser
via HTTP
• Server sends image files separately
• Static HTML example
Developing Web Applications with Ada
8
Static HTML
Browser
Server
Page Request
Page
Image
Developing Web Applications with Ada
9
Common Gateway Interface (CGI)
• Server-side processing
• Usually used in conjunction with HTML forms
• HTTP request is passed to a separate program
which processes it and generates a response
• David Wheeler's AdaCGI:
– http://www.dwheeler.com/
• CGI example
Developing Web Applications with Ada
10
Common Gateway Interface (CGI)
Browser
Server
Page Request
Spawn
CGI Program
HTTP Request
Page
Developing Web Applications with Ada
Page
11
JavaScript
• Client-side processing (in browser)
• First introduced by Netscape
• Object-based language with access to
Document Object Model (DOM)
• Small application whose source code is
embedded in an HTML page and interpreted
by the browser
• JavaScript example
Developing Web Applications with Ada
12
JavaScript
Browser
Server
Page Request
Page
Image
Developing Web Applications with Ada
13
Java Applets
• Client-side processing
• Small applications that server sends to browser as
a separate file
• Browser invokes the Java Virtual Machine to
execute the applet
• Applet may or may not have a user interface
• Applet is discarded when user switches to another
page
• Java Applet example
Developing Web Applications with Ada
14
Java Applets
Java Virtual
Machine
Browser
Server
Page Request
Page
Applet
Applet
User Interface
Developing Web Applications with Ada
15
Dynamic HTML (DHTML)
• Client-side processing
• DHTML is a combination of World Wide
Web Consortium (W3C) standards for:
–
–
–
–
HTML 4.0
JavaScript
Document Object Model (DOM)
Cascading Style Sheets (CSS)
Developing Web Applications with Ada
16
Dynamic HTML (DHTML)
Browser
Server
Page Request
Page
Image
Developing Web Applications with Ada
17
Java Servlets
• Server-side processing
• Small Java applications that server executes
• Similar to CGI except does not require
spawning a new process
• Servlet processes the HTTP request and
generates the response
• Java servlet example
Developing Web Applications with Ada
18
Java Servlets
Browser
Java Servlet
Container
Server
Page Request
HTTP Request
Page
Spawn
Servlet
Thread
Page
Developing Web Applications with Ada
19
Template Systems
• Server-side processing
• Embedded in HTML file:
– Special tags request dynamic content
– Scripts generate more HTML
• Server processes the HTML file, filling in
the dynamic content and executing the
scripts, then passing the page to the browser
Developing Web Applications with Ada
20
Template Systems
Browser
Template
Processor
Server
Page Request
HTTP Request
Page
Page
Developing Web Applications with Ada
21
Template Systems
•
•
•
•
•
•
•
ColdFusion
Microsoft Active Server Pages (ASP)
Server Side JavaScript
PHP
WebMacro
Apache Velocity
JavaServer Pages
Developing Web Applications with Ada
22
Why JavaServer Pages?
• Platform-independent technology
• Java-based technology
– Full object-oriented programming model
– Access to Java platform, including all Java
APIs
• Improved performance over CGI and
scripting languages
Developing Web Applications with Ada
23
Why JavaServer Pages (2)
• A programming model which provides for
– Separation of presentation and implementation
– Reusable component model: Java Beans
– Tag extension mechanism
• Last, but not least:
– Use Ada to code Java Beans and Java servlets
– Complete set of free tools
Developing Web Applications with Ada
24
Table of Contents
• Dynamic Web Technologies
Required Components
• Introduction to JSP
• Introduction to Java Beans
• Introduction to JDBC
• Building a Web Application
Developing Web Applications with Ada
25
Required Components
• Java Software Development Kit (SDK)
• Ada to JVM compiler
– JGNAT
– Aonix ObjectAda
• Relational database – MySQL
• JDBC driver
• JSP-enabled web server – Jakarta Tomcat
Developing Web Applications with Ada
26
Java SDK
• Get “Java 2 Standard Edition”
– Windows version: j2sdk1_3_0-win.exe
– http://java.sun.com
• Install on
– server
– development computer
Developing Web Applications with Ada
27
Test Java SDK Installation
• Create file HelloJavaWorld.java:
class HelloJavaWorld {
public static void main (String args[]) {
System.out.println ("Hello Java World!");
}
}
• Compile it:
javac HelloJavaWorld
• Execute it:
java HelloJavaWorld
• Should display:
Hello Java World!
Developing Web Applications with Ada
28
Ada to JVM Compiler
• Ada compiler targeted to the Java Virtual
Machine (JVM)
– JGNAT by Ada Core Technologies
– Aonix ObjectAda
Developing Web Applications with Ada
29
JGNAT
• Get JGNAT
– Windows version: jgnat-1.1p-nt.exe
– ftp://ftp.cs.nyu.edu/pub/gnat/jgnat/
– ftp://ftp.freesoftware.com/pub/ada/compiler/gna
t/distrib/jgnat/
• Install on development computer only
Developing Web Applications with Ada
30
JGNAT Environment Variables
• Remove:
– ADA_INCLUDE_PATH
– ADA_OBJECTS_PATH
Dot is important;
don’t leave it out!
• Add to PATH:
– SET PATH=C:\JGNAT-1.1P\BIN;%PATH%
• Add CLASSPATH:
– SET CLASSPATH=.;C:\JGNAT1.1P\LIB\JGNAT.JAR;%CLASSPATH%
Developing Web Applications with Ada
31
Test JGNAT Installation
• Create file hello.adb:
with Ada.Text_IO;
procedure HelloJGNAT is
begin – HelloJGNAT
Ada.Text_IO.Put_Line (“Hello, JGNAT World!");
end HelloJGNAT;
• Compile it:
jgnatmake hellojgnat
• Execute it:
java hellojgnat
• Should display:
Hello, JGNAT World!
Developing Web Applications with Ada
32
Get MySQL
• MySQL is an open-source (GPL) relational database
(http://www.mysql.com)
• Also available with non-GPL commercial license
• Support available from TcX DataKonsult AB
• See excellent user reference manual in Docs
directory for installation, testing instructions and a
tutorial
• Install on server and development computers
Developing Web Applications with Ada
33
MySQL Security
• Remove anonymous user
– mysql> delete from mysql.user where user=“”;
• Give root a password
– shell> mysqladmin –u root password <password>
• Require passwords of all users and grant only
needed privileges
– Generally, only select, update, delete, and insert
– mysql> grant select, update, delete, insert on
<database> to <user> identified by “<password>”;
Developing Web Applications with Ada
34
JDBC Driver
• Java driver that supports Java API for using
ODBC to connect to relational databases
• Check http://www.mysql.com/ for available JDBC
drivers for MySQL
• For this tutorial, we will use Mark Matthews'
driver found at
http://www.worldserver.com/mm.mysql/
• Install on server and development computers
Developing Web Applications with Ada
35
Get Jakarta Tomcat
• An open-source (Apache Software
Foundation) implementation of Sun's
reference edition JSP-enabled web server
– http://jakarta.apache.org/
• Can be run stand-alone or from within
Apache
• Install on server and development computers
Developing Web Applications with Ada
36
Tomcat Environment Variables
• Set environment variables
– SET TOMCAT_HOME=C:\PROGRA~1\JAKARTA-TOMCAT
– SET JAVA_HOME=C:\JDK1.3
Developing Web Applications with Ada
37
Windows 95/98/ME
• Use bin\startup.bat to start Tomcat
• Use bin\shutdown.bat to stop Tomcat
• May have to increase "Initial environment"
memory size of startup.bat and
shutdown.bat scripts to 2816
Developing Web Applications with Ada
38
Windows 2000/XP
• Can run Tomcat as a service
• See instructions in Tomcat documentation
for installation and configuration
– wrapper.tomcat_home
– wrapper.java_home
– wrapper.class_path
• Example: wrapper.properties
Developing Web Applications with Ada
39
Test Tomcat
• Start web server using startup.bat script from
Tomcat bin directory
• Start web browser
• Go to http://localhost:8080/ to see local Tomcat
home page
• Try out some of the JSP and servlet examples
• To shutdown web server, use shutdown.bat script
from Tomcat bin directory
Developing Web Applications with Ada
40
Table of Contents
• Dynamic Web Technologies
• Required Components
Introduction to JSP
• Introduction to Java Beans
• Introduction to JDBC
• Building a Web Application
Developing Web Applications with Ada
41
My First JSP
<HTML>
<BODY>
Hello, World!
</BODY>
</HTML>
• JSP example
Developing Web Applications with Ada
42
Interactive JSP
<HTML>
<BODY>
<% String visitor =
Script
request.getParameter("name");
if (visitor == null)
visitor = "World";
%>
Hello, <%= visitor %>
</BODY>
</HTML>
Tag
See Interactive JSP example
Developing Web Applications with Ada
43
JSP Processing
Browser
JSP
Container
Server
Page Request
HTTP Request
Page
Page
Developing Web Applications with Ada
Compile
Page
Spawn
Servlet
Thread
44
Factorial
• Another JSP example
• Compute and display factorials
• All Java code in JSP document
Developing Web Applications with Ada
45
The Bean Edition
<html>
<body>
<jsp:useBean id="hello"
class="hellobean$typ"/>
<jsp:setProperty name="hello"
property="name"
param="name"/>
Hello,
<jsp:getProperty name="hello"
property="name"/>!
</body>
</html>
See Bean example
Developing Web Applications with Ada
46
JSP Bean Processing
Browser
JSP
Container
Server
Page Request
HTTP Request
Compile Page
Spawn Servlet Thread
Create
Page
Developing Web Applications with Ada
Page
Bean
setProperty
getProperty
47
JSP Script Tags
• Declarations
<%! String visitor %>
• Scriptlets
<% visitor = request.getParameter("name");
if (visitor == null)
visitor = "World"; %>
• Expressions
<%= visitor %>
Developing Web Applications with Ada
48
JSP XML Tags
• Declarations
<jsp:declaration> String visitor </jsp:declaration>
• Scriptlets
<jsp:scriptlet>
visitor = request.getParameter("name");
if (visitor == null)
visitor = "World";
</jsp:scriplet>
• Expressions
<jsp:expression> visitor </jsp:expression>
Developing Web Applications with Ada
49
JSP Bean Tags
• Create a bean
<jsp:useBean id="hello"
class="hellobean$typ"/>
• Set bean property
<jsp:setProperty name="hello"
property="name"
param="name"/>
• Get bean property
<jsp:getProperty name="hello"
property="name"/>
Developing Web Applications with Ada
50
Dynamic Web Technologies
T ech n olog y
U ser
A ccess
In tera ction T o S erve r
L a n g ua g e
S epa ra tion
O th er
Fast load
C PUexp en sive
Fast load
S lo w load
S tatic H T M L
CGI
No
Y es
No
Y es
N on e
Any
N /A
Y es
JavaS crip t
Java A p p let
Java S ervlet
JS P S crip t
Java B ean s
Y es
Y es
Y es
Y es
Y es
No
Y es
Y es
Y es
Y es
JavaS crip t
Java, A d a
Java, A d a
Java
Java, A d a
No
Y es
No
No
Y es
Developing Web Applications with Ada
51
Table of Contents
• Dynamic Web Technologies
• Required Components
• Introduction to JSP
Introduction to Java Beans
• Introduction to JDBC
• Building a Web Application
Developing Web Applications with Ada
52
Introduction to Java Beans
• Software components written in Java Ada
• A Java Bean is a Java class that adheres to
the JavaBeans API specification
– http://java.sun.com/products/javabeans/
Developing Web Applications with Ada
53
Bean Containers
• Tools that provide Bean composition and
Bean execution
• Each implementation has its own limitations
on how it interacts with Beans, but…
• Interaction is primarily through Bean
properties and their set and get operations
Developing Web Applications with Ada
54
Bean Properties
• Properties can be pretty much any data type
• They can be indexed to provide access
collections of values
• Some properties trigger behavior
• The JSP container is one such Bean container
Developing Web Applications with Ada
55
JSP Bean Processing
Browser
JSP
Container
Server
Page Request
HTTP Request
Compile Page
Spawn Servlet Thread
Create
Page
Developing Web Applications with Ada
Page
Bean
setProperty
getProperty
56
JSP Scriptlets and Beans
• Can call any function in the bean interface
• Can call set and get properties returning any
data type
• Expressions returning primitive types are
converted to String type by the JSP
container
• But, you're really writing Java code
• See Roll Dice example
Developing Web Applications with Ada
57
JSP XML Tags
• JSP XML tags treat all properties as String
data type exclusively
• Works well with HTML!
• For all properties, the Bean must provide
String type set and get operations
• See Roll Dice example
Developing Web Applications with Ada
58
Bean Types
• Visual components
– Implement graphical user interface elements
– Not compatible with JSP
• Data storage
– An object that provides access to information
• Service beans
– Implement the behavior of a JSP application
Developing Web Applications with Ada
59
Using Java Beans
•
•
•
•
•
Using a Java Bean
Initializing a Java Bean
Java Bean properties
Mixing Bean tags and scriptlets
Java Bean scope
Developing Web Applications with Ada
60
Using a Java Bean
The <jsp:useBean> tag
<jsp:useBean id="dice" class="randombean$typ"/>
Local bean name
Class name of the bean
Developing Web Applications with Ada
61
UseBean Tag Attributes
A ttrib u te
V a lu e
D efa u lt
E x a m p le
id
Jav a id en tifier
N one
d ice
class
Jav a class n am e
N one
ran d o m b ean $ ty p
sco p e
p ag e, req u est,
p ag e
sessio n , ap p licatio n
Developing Web Applications with Ada
sessio n
62
UseBean Tag Example
<html>
<head>
<title> Roll Dice </title>
<link rel="stylesheet" type="text/css" href="dice.css">
</head>
<body>
<jsp:useBean id="dice" class="randombean$typ"/>
<jsp:setProperty name="dice" property="minint" value="1"/>
<jsp:setProperty name="dice" property="maxint" value="6"/>
<table>
<tr>
<td> <%= dice.getint() %>
<td> <jsp:getProperty name="dice" property="int"/>
</table>
</body>
</html>
Developing Web Applications with Ada
63
The useBean Tag
• Creates an instance of a bean
– Executes the object constructor
• Assigns an ID local to the page
• Can have more than one instance of a bean
on a page
• Its lifetime has scope
Developing Web Applications with Ada
64
Initializing a Java Bean
The <jsp:setProperty> tag
Local bean name
<jsp:setProperty name="dice"
property="minint"
value="1"/>
Property value
Developing Web Applications with Ada
Property name
65
Initializing Bean Example
<html>
<head>
<title> Roll Dice </title>
<link rel="stylesheet" type="text/css" href="dice.css">
</head>
<body>
<jsp:useBean id="dice" class="randombean$typ"/>
<jsp:setProperty name="dice" property="minint" value="1"/>
<jsp:setProperty name="dice" property="maxint" value="6"/>
<table>
<tr>
<td> <%= dice.getint() %>
<td> <jsp:getProperty name="dice" property="int"/>
</table>
</body>
</html>
Developing Web Applications with Ada
66
Initializing Bean Alternative
<html>
<head>
<title> Roll Dice </title>
<link rel="stylesheet" type="text/css" href="dice.css">
</head>
<body>
<jsp:useBean id="dice" class="randombean$typ">
<jsp:setProperty name="dice" property="minint" value="1"/>
<jsp:setProperty name="dice" property="maxint" value="6"/>
</jsp:useBean>
<table>
<tr>
<td> <%= dice.getint() %>
<td> <jsp:getProperty name="dice" property="int"/>
</table>
</body>
</html>
Developing Web Applications with Ada
67
Initializing a Java Bean
• Constructor methods called by JSP do not
have any parameters
• Initialization of bean must be done through
properties
• Use a Set property function to initialize any
property
Developing Web Applications with Ada
68
Using Request Parameters
Request is:
<a href="HelloBean.jsp?name=Westley">Java Bean</a>
Can initialize bean property from request parameter:
<jsp:setProperty name="hello"
property="name"
param="name"/>
Developing Web Applications with Ada
69
Java Bean Properties
The <jsp:getProperty> tag
Local bean name
<jsp:getProperty name="dice" property="int"/>
Property name
Developing Web Applications with Ada
70
Mixing Bean Tags and Scriptlets
<html>
<head>
<title> Roll Dice </title>
<link rel="stylesheet" type="text/css" href="dice.css">
</head>
<body>
<jsp:useBean id="dice" class="randombean$typ"/>
<jsp:setProperty name="dice" property="minint" value="1"/>
<jsp:setProperty name="dice" property="maxint" value="6"/>
<table>
<tr>
<td> <%= dice.getint() %>
<td> <jsp:getProperty name="dice" property="int"/>
</table>
</body>
</html>
Developing Web Applications with Ada
71
Java Bean scope
• Can specify that a Bean’s “life” extends
beyond the scope of the current page
• Use the scope attribute in the
<jsp:useBean> tag
• Choices: page, request, session, application
Developing Web Applications with Ada
72
Java Bean Scope
S co p e
A ccessib ility
L ife sp a n
P ag e
C u rren t p ag e
U n til p ag e is d isp lay ed
R eq u est
C u rren t p ag e an d in clu d ed o r
fo rw ard ed p ag es
S essio n
C u rren t req u est an d
su b seq u en t req u ests fro m
sam e b ro w ser w in d o w
C u rren t an d fu tu re req u ests
th at are p art o f sam e w eb
ap p licatio n
U n til req u est h as b een
p ro cessed an d resp o n se
sen t to u ser
U ser’s sessio n
A p p licatio n
Developing Web Applications with Ada
A p p licatio n
73
Writing Java Beans
•
•
•
•
•
What is a Bean?
Bean constructor
Initializing Beans
Bean properties
Testing with JUnit
Developing Web Applications with Ada
74
What is a Bean?
• A Java class that follows a set of naming
and design conventions
• Not required to inherit from a specific class
or implement a specific interface
• Just follow the conventions
Developing Web Applications with Ada
75
Bean Conventions
• Java Bean is a Java class
• Implement a constructor that takes no arguments
– May implement other constructors as well
• Define Bean properties by defining access and
update methods
– Implement public method with property name prefixed
by set and get as needed
• May define other methods, such as indexed
properties, but they are not accessible via JSP tags
Developing Web Applications with Ada
76
A Java Bean is a Java Class
with Java.Lang.Object;
with Java.Util.Random;
package RandomBean is
type Typ is
Random :
MinInt :
MaxInt :
end record;
type Ref is
new Java.Lang.Object.Typ with record
Java.Util.Random.Ref;
Java.Int;
Java.Int;
access all Typ'Class;
Developing Web Applications with Ada
77
Bean Constructor Specification
An Ada function with these characteristics:
– Result type is an access type designating a class-wide type
– Only one parameter, named This, whose type is the same
as the result type and has a null default value
– Specifies pragma Java_Constructor
function new_RandomBean (
This : Ref := null) return Ref;
pragma Java_Constructor (new_RandomBean);
Developing Web Applications with Ada
78
Bean Constructor Body (1)
First statement of a Java constructor must be either a call
to another constructor of the class or a call to a
constructor of the superclass
function new_RandomBean (
This : Ref := null) return Ref is
Super : Java.Lang.Object.Ref :=
Java.Lang.Object.new_Object (
Java.Lang.Object.Ref (This));
begin -- new_RandomBean
This.Random := Java.Util.Random.New_Random;
This.MinInt := 1;
This.MaxInt := Java.Int'Last;
return This;
end new_RandomBean;
Developing Web Applications with Ada
79
Bean Constructor Body (2)
Then, initialize the object and return it
function new_RandomBean (
This : Ref := null) return Ref is
Super : Java.Lang.Object.Ref :=
Java.Lang.Object.new_Object (
Java.Lang.Object.Ref (This));
begin -- new_RandomBean
This.Random := Java.Util.Random.New_Random;
This.MinInt := 1;
This.MaxInt := Java.Int'Last;
return This;
end new_RandomBean;
Developing Web Applications with Ada
80
Bean Constructor is Invoked
<html>
<head>
<title> Roll Dice </title>
<link rel="stylesheet" type="text/css" href="dice.css">
</head>
<body>
<jsp:useBean id="dice" class="randombean$typ"/>
<jsp:setProperty name="dice" property="minint" value="1"/>
<jsp:setProperty name="dice" property="maxint" value="6"/>
<table>
<tr>
<td> <%= dice.getint() %>
<td> <jsp:getProperty name="dice" property="int"/>
</table>
</body>
</html>
Developing Web Applications with Ada
81
Initializing Beans
Since the constructor must have no arguments,
you will likely need to call property setter
functions to initialize the Bean.
procedure SetMinInt (This : access Typ;
Min : in Java.Int) is
begin – SetMinInt
This.MinInt := Min;
end SetMinInt;
Developing Web Applications with Ada
82
Initializing Bean
<html>
<head>
<title> Roll Dice </title>
<link rel="stylesheet" type="text/css" href="dice.css">
</head>
<body>
<jsp:useBean id="dice" class="randombean$typ"/>
<jsp:setProperty name="dice" property="minint" value="1"/>
<jsp:setProperty name="dice" property="maxint" value="6"/>
<table>
<tr>
<td> <%= dice.getint() %>
<td> <jsp:getProperty name="dice" property="int"/>
</table>
</body>
</html>
Developing Web Applications with Ada
83
Bean Properties
Now that our Bean is initialized, use a property
getter function to fetch a property value and
insert it into the JSP page.
function GetInt (This : access Typ)
return Java.Int is
begin – GetInt
return
Java.Util.Random.NextInt (This.Random,
This.MaxInt-This.MinInt+1) +
This.MinInt;
end GetInt;
Developing Web Applications with Ada
84
Bean Properties
<html>
<head>
<title> Roll Dice </title>
<link rel="stylesheet" type="text/css" href="dice.css">
</head>
<body>
<jsp:useBean id="dice" class="randombean$typ"/>
<jsp:setProperty name="dice" property="minint" value="1"/>
<jsp:setProperty name="dice" property="maxint" value="6"/>
<table>
<tr>
<td> <%= dice.getint() %>
<td> <jsp:getProperty name="dice" property="int"/>
</table>
</body>
</html>
Developing Web Applications with Ada
85
JSP Type Conversions
Type
C o n v ersio n to S trin g
C o n v ersio n fro m S trin g
B o o lean
Jav a.lan g .B o o lean .to S trin g
Jav a.lan g .B o o lean .v alu eO f
B y te
Jav a.lan g .b y te.to S trin g
Jav a.lan g .b y te.v alu eO f
C h ar
Jav a.lan g .ch aracter.to S trin g
Jav a.lan g .ch aracter.v alu eO f
D o u b le
Jav a.lan g .d o u b le.to S trin g
Jav a.lan g .d o u b le.v alu eO f
In t
Jav a.lan g .in teg er.to S trin g
Jav a.lan g .in teg er.v alu eO f
F lo at
Jav a.lan g .flo at.to S trin g
Jav a.lan g .flo at.v alu eO f
Long
Jav a.lan g .lo n g .to S trin g
Jav a.lan g .lo n g .v alu eO f
Developing Web Applications with Ada
86
Testing with JUnit
• JUnit is a regression testing framework
– http://www.junit.org/
• For languages other than Java, see
– http://www.xprogramming.com/software.htm
• For Ada, see Ed Falis’ AUnit
Developing Web Applications with Ada
87
Generating Ada Specs
• JUnit is a jar file, junit.jar, from which we
need to generate Ada package specs
• JGNAT includes the tool, jvm2ada, for this
purpose
Developing Web Applications with Ada
88
Using jvm2ada
• Create a directory and copy junit.jar into the
directory
• Unzip junit.jar and rezip without file compression
• Generate Ada package specs
jvm2ada junit.jar
• Compile all the package specs
for f in *.ads ; do
jgnatmake -I/JSP/java-APIs/java $f
done
• See jar2ada.sh script
Developing Web Applications with Ada
89
Using JUnit with Ada
• Create an Ada package with a tagged type
derived from JUnit.Framework.TestCase
• Add appropriate constructor
• Add setUp method
• Add one test method for each test case
• RandomBeanTest example
Developing Web Applications with Ada
90
Table of Contents
• Dynamic Web Technologies
• Required Components
• Introduction to JSP
• Introduction to Java Beans
Introduction to JDBC
• Building a Web Application
Developing Web Applications with Ada
91
Introduction to JDBC
•
•
•
•
•
•
•
Establishing a connection
JDBC statements
Creating a table
Updating a table
Query
Result sets
Prepared statements
Developing Web Applications with Ada
92
Establishing a Connection
• Load the driver
Obj := Java.Lang.Class.NewInstance (
Java.Lang.Class.forName(
+"org.gjt.mm.mysql.Driver"));
• Make the connection
Con := Java.Sql.DriverManager.
getConnection(
URL, User, Password);
Developing Web Applications with Ada
93
JDBC Statements
• A Statement object sends SQL statements to
the database server
• Create a statement, then execute it
• You must choose the appropriate execute
method:
– executeQuery for SELECT statements
– executeUpdate for statements that update or
modify tables
Developing Web Applications with Ada
94
Create a Statement Object
declare
Con : Java.Sql.Connection.Ref;
Stmt : Java.Sql.Statement.Ref;
begin
Con := Java.Sql.DriverManager.
getConnection(
URL, User, Password);
Stmt := Java.Sql.Connection.
createStatement (Con);
Developing Web Applications with Ada
95
Execute a Statement
Stmt := Java.Sql.Connection.
createStatement (Con);
Result := Java.Sql.Statement.
executeUpdate(Stmt,
+("drop table messages"));
• Full Example: DropMessages
Developing Web Applications with Ada
96
Creating a Table
Result := Java.Sql.Statement.
executeUpdate(Stmt, +(
"create table messages (" &
"
MessageID int unsigned not
"
auto_increment primary
"
Posted
timestamp
"
Subject
varchar(255) not
"
Body
text
not
null " &
key, " &
," &
null," &
null)"));
• Full Example: CreateMessages
Developing Web Applications with Ada
97
Updating a Table
Result := Java.Sql.Statement.
executeUpdate (Stmt, +(
"INSERT INTO Messages " &
"(Subject, Body) VALUES " &
"('test subject', 'test body')"));
• Full Example: InsertMessages
Developing Web Applications with Ada
98
Query
Result := Java.Sql.Statement.
executeQuery (Stmt, +(
"SELECT * FROM Messages");
• Where are the rows that are returned?
Developing Web Applications with Ada
99
Result Sets
• JDBC returns results from SELECT in a
ResultSet
• Must declare an instance of ResultSet
• Execute a query
• Iterate over the Result Set, fetching the data
• Example: QueryMessages
Developing Web Applications with Ada
100
Result Sets
• Get methods for Java types: byte, short, int,
long, float, double, boolean, string, date,
time, et. al.
• Match get method with database type
• Can use column name instead of position:
Java.Sql.ResultSet.GetInt (
Results, +“MessageID”);
Developing Web Applications with Ada
101
Prepared Statements
• For when you need to repeat the same SQL
statement many times
• A Prepared Statement is given an SQL
statement when it is created:
Stmt := Java.Sql.Connection.
PrepareStatement (Con, +(
"INSERT INTO Messages " &
"(Subject, Body) VALUES " &
"(?, ?)"));
Developing Web Applications with Ada
102
Prepared Statement
• Supply field values:
Java.Sql.PreparedStatement.
SetString (Stmt, 1, +"subject 3");
Java.Sql.PrepareStatement.
SetString (Stmt, 2, +"body 3");
• Execute the Prepared Statement
Rows := Java.Sql.PreparedStatement.
ExecuteUpdate (Stmt);
• Example: PrepInsertMessages
Developing Web Applications with Ada
103
Table of Contents
• Dynamic Web Technologies
• Required Components
• Introduction to JSP
• Introduction to Java Beans
• Introduction to JDBC
Building a Web Application
Developing Web Applications with Ada
104
Building a Web Application
• Model-View-Controller architecture
• Page-centric design
• Servlet-centric design
Developing Web Applications with Ada
105
Model-View-Controller
• Model
– Models data and business process
• Controller
– Mediates between Model and View
– Controls application’s flow
• View
– Client side display (HTML or XHTML)
Developing Web Applications with Ada
106
Page-Centric Design
• Application is composed of a set of related
JSP pages
• All application logic is hard-coded in the
JSP pages through its scripts, beans, and
expressions
• Each page has a specific role to play
• Example: Discussion Group
Developing Web Applications with Ada
107
View
index.html
Discussion Group
Post New Message
post.html
Controller
post.jsp
Model
Message
Controller
Developing Web Applications with Ada
Message
Table
Database
108
View
Discussion Group
Read Messages
index.html
Controller
msgindex.jsp
Message
Bean
read.jsp
Model
Message
Controller
Developing Web Applications with Ada
Message
Table
Database
109
Servlet-Centric Design
• JSP pages used only for presentation (view)
• All application logic (model and controller)
is implemented in servlets
• Requests are routed through one or more
servlets which control application flow and
which pages are displayed when
• Still use beans for communication between
servlet and a JSP page
Developing Web Applications with Ada
110
Servlet Functions
• Perform actions on behalf of a JSP page
• Deliver data for display to a JSP page
• Control application flow between related
JSP pages
Developing Web Applications with Ada
111
Servlet Benefits
• Provides better separation of presentation
and application logic
• Reduces complexity of JSP page code
• Better control of error handling
• Example: HelloFromServlet
• Example: Discussion Group
Developing Web Applications with Ada
112
Discussion Group – Post New Message
View
Controller
index.html
ForumServlet
Model
Message
Bean
postform.jsp
Message
Table
postconfirm.jsp
Database
Developing Web Applications with Ada
113
JSP and Servlet
Deployment
JSP pages
H T M L d o c u m e n ts
im a g e file s
a p p -n a m e
JSP pages
H T M L d o c u m e n ts
im a g e file s
C o n te n t
d ire c to rie s
W E B -IN F
w e b .x m l
Create this JSP
web application
directory
structure
C la s s file s
c la s s e s
C la s s file s
Package
d ire c to rie s
lib
Developing Web Applications with Ada
J A R file s
Adapted from [Fields, Kolb]
114
Servlet Configuration
• Web application configuration file: web.xml
– Stored in WEB-INF directory
– Identifies servlets and initialization parameters
– Minimal example:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN“
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
</web-app>
Developing Web Applications with Ada
115
Web.xml: Optional Elements
<display-name>
SIGAda 2001 Tutorial
</display-name>
<description>
Examples and source code for
tutorial presentation
</description>
<welcome-file-list>
<welcome-file>
index.html
</welcome-file>
</welcome-file-list>
Developing Web Applications with Ada
116
Web.xml: Servlet Identification
<servlet>
<servlet-name>
helloservlet
</servlet-name>
<servlet-class>
helloservlet$typ
</servlet-class>
</servlet>
Developing Web Applications with Ada
117
Web.xml: Servlet Mapping
<servlet-mapping>
<servlet-name>
helloservlet
</servlet-name>
<url-pattern>
/helloservlet
</url-pattern >
</servlet-mapping>
Developing Web Applications with Ada
118
Web.xml: Example
• SIGAda 2001 Tutorial
–
–
–
–
Hello Servlet
Hello from Servlet
Forum Servlet
Java Servlet
Developing Web Applications with Ada
119
Tomcat Server Configuration
• Configure Tomcat to recognize the application we
just created: TOMCAT_HOME\conf\server.xml
<Context
path="/sigada2001"
docBase="C:\JSP\Tutorial\app"
crossContext="false"
debug="0"
reloadable="true"
trusted="false" >
</Context>
Developing Web Applications with Ada
120
Negatives of JSP
• JSP code does not appear in browser
– Harder to debug
• Complexity of edit-transform-compile-loadrun cycle
– Need javac compiler in production machine
– Left-over compilation “crud”
Developing Web Applications with Ada
121
Negatives of JSP
• Error handling
– Different types of errors from transformcompile-load phases of development cycle
– JSP pages don’t easily catch certain errors such
as OutofMemoryError
– Mysterious errors: CastClassException
Developing Web Applications with Ada
122
An Alternative – Velocity
• Velocity is a Java-based template engine
• One of the subprojects of Jakarta Apache
• Does not embed Java code in web pages,
but uses the Velocity Template Language
• Uses a simple model of a Context (a hash
table) for passing information between web
pages and Java code
Developing Web Applications with Ada
123
Velocity
• Can also be used as a general-purpose
template engine, not just for web pages
• Example: Discussion Group
Developing Web Applications with Ada
124
More to Learn
• How to use JAR files
• How to use Java packages as subdirectories
• Handling Java exceptions
Developing Web Applications with Ada
125
Descargar

TASH (Tcl Ada Shell) An Ada binding to Tcl/Tk