+ All Categories
Home > Documents > Developing Web Applications Using Ada, JGNAT, JavaServer Pages, and JDBC to Build Web Applications...

Developing Web Applications Using Ada, JGNAT, JavaServer Pages, and JDBC to Build Web Applications...

Date post: 17-Dec-2015
Category:
Upload: kevin-cooper
View: 217 times
Download: 1 times
Share this document with a friend
Popular Tags:
125
Developing Web Applications Using Ada, JGNAT, JavaServer Pages, and JDBC to Build Web Applications Terry Westley
Transcript

Developing Web Applications

Using Ada, JGNAT, JavaServer Pages,and JDBC to Build Web Applications

Terry Westley

SIGAda 2001

Developing Web Applications with Ada 2

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 3

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 4

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 5

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 6

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 7

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 8

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 9

Static HTML

Browser Server

Page Request

Page

Image

Developing Web Applications with Ada 10

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 11

Common Gateway Interface (CGI)

Browser Server

Page Request

Page

CGI Program

HTTP Request

Page

Spawn

Developing Web Applications with Ada 12

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 13

JavaScript

Browser Server

Page Request

Page

Image

Developing Web Applications with Ada 14

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 15

Java Applets

Browser Server

Page Request

Page

Applet

Java VirtualMachine

Applet

User Interface

Developing Web Applications with Ada 16

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 17

Dynamic HTML (DHTML)

Browser Server

Page Request

Page

Image

Developing Web Applications with Ada 18

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 19

Java Servlets

Browser Server

Page Request

PagePage

Java ServletContainer

SpawnServletThread

HTTP Request

Developing Web Applications with Ada 20

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 21

Template Systems

Browser Server

Page Request

PagePage

TemplateProcessor

HTTP Request

Developing Web Applications with Ada 22

Template Systems

• ColdFusion• Microsoft Active Server Pages (ASP)• Server Side JavaScript• PHP• WebMacro• Apache Velocity• JavaServer Pages

Developing Web Applications with Ada 23

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 24

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 25

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 26

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 27

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 28

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 29

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 30

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/

gnat/distrib/jgnat/

• Install on development computer only

Developing Web Applications with Ada 31

JGNAT Environment Variables

• Remove:– ADA_INCLUDE_PATH– ADA_OBJECTS_PATH

• Add to PATH:– SET PATH=C:\JGNAT-1.1P\BIN;%PATH%

• Add CLASSPATH:– SET CLASSPATH=.;C:\JGNAT-1.1P\LIB\JGNAT.JAR;%CLASSPATH%

Dot is important; don’t leave it out!

Developing Web Applications with Ada 32

Test JGNAT Installation

• Create file hello.adb:with Ada.Text_IO;procedure HelloJGNAT isbegin – 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 33

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 34

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 35

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 36

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 37

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 38

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 39

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 40

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 41

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 42

My First JSP

<HTML><BODY>Hello, World!</BODY></HTML>

• JSP example

Developing Web Applications with Ada 43

Interactive JSP

<HTML><BODY><% String visitor = request.getParameter("name"); if (visitor == null) visitor = "World";%>

Hello, <%= visitor %></BODY></HTML>

Script

Tag

See Interactive JSP example

Developing Web Applications with Ada 44

JSP Processing

Browser Server

Page Request

PagePage

JSPContainer

CompilePage

HTTP Request

SpawnServletThread

Developing Web Applications with Ada 45

Factorial

• Another JSP example

• Compute and display factorials

• All Java code in JSP document

Developing Web Applications with Ada 46

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 47

JSP Bean Processing

Browser Server

Page Request

Page Page

JSPContainer

Compile Page

HTTP Request

Spawn Servlet Thread

BeansetProperty

Create

getProperty

Developing Web Applications with Ada 48

JSP Script Tags

• Declarations<%! String visitor %>

• Scriptlets<% visitor = request.getParameter("name"); if (visitor == null) visitor = "World"; %>

• Expressions<%= visitor %>

Developing Web Applications with Ada 49

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 50

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 51

Dynamic Web Technologies

Technology UserInteraction

AccessTo Server

Language Separation Other

Static HTML No No None N/A Fast loadCGI Yes Yes Any Yes CPU-

expensiveJavaScript Yes No JavaScript No Fast loadJava Applet Yes Yes Java, Ada Yes Slow loadJava Servlet Yes Yes Java, Ada NoJSP Script Yes Yes Java NoJava Beans Yes Yes Java, Ada Yes

Developing Web Applications with Ada 52

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 53

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 54

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 55

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 56

JSP Bean Processing

Browser Server

Page Request

Page Page

JSPContainer

Compile Page

HTTP Request

Spawn Servlet Thread

BeansetProperty

Create

getProperty

Developing Web Applications with Ada 57

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 58

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 59

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 60

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 61

Using a Java Bean

<jsp:useBean id="dice" class="randombean$typ"/>

The <jsp:useBean> tag

Local bean name

Class name of the bean

Developing Web Applications with Ada 62

UseBean Tag Attributes

Attribute Value Default Example

id Java identifier None dice

class Java class name None randombean$typ

scope page, request, session, application

page session

Developing Web Applications with Ada 63

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 64

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 65

Initializing a Java Bean

<jsp:setProperty name="dice" property="minint" value="1"/>

The <jsp:setProperty> tag Local bean name

Property nameProperty value

Developing Web Applications with Ada 66

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 67

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 68

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 69

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 70

Java Bean Properties

<jsp:getProperty name="dice" property="int"/>

The <jsp:getProperty> tag Local bean name

Property name

Developing Web Applications with Ada 71

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 72

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 73

Java Bean ScopeScope Accessibility Life span

Page Current page Until page is displayed

Request Current page and included or forwarded pages

Until request has been processed and response sent to user

Session Current request and subsequent requests from same browser window

User’s session

Application Current and future requests that are part of same web application

Application

Developing Web Applications with Ada 74

Writing Java Beans

• What is a Bean?

• Bean constructor

• Initializing Beans

• Bean properties

• Testing with JUnit

Developing Web Applications with Ada 75

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 76

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 77

A Java Bean is a Java Class

with Java.Lang.Object;with Java.Util.Random;

package RandomBean is

type Typ is new Java.Lang.Object.Typ with record Random : Java.Util.Random.Ref; MinInt : Java.Int; MaxInt : Java.Int; end record; type Ref is access all Typ'Class;

Developing Web Applications with Ada 78

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 79

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 80

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 81

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 82

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) isbegin – SetMinInt This.MinInt := Min;end SetMinInt;

Developing Web Applications with Ada 83

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 84

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 isbegin – GetInt return Java.Util.Random.NextInt (This.Random, This.MaxInt-This.MinInt+1) + This.MinInt;end GetInt;

Developing Web Applications with Ada 85

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 86

JSP Type Conversions

Type Conversion to String Conversion from String

Boolean Java.lang.Boolean.toString Java.lang.Boolean.valueOf

Byte Java.lang.byte.toString Java.lang.byte.valueOf Char Java.lang.character.toString Java.lang.character.valueOf Double Java.lang.double.toString Java.lang.double.valueOf Int Java.lang.integer.toString Java.lang.integer.valueOf

Float Java.lang.float.toString Java.lang.float.valueOf

Long Java.lang.long.toString Java.lang.long.valueOf

Developing Web Applications with Ada 87

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 88

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 89

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 specsfor f in *.ads ; do jgnatmake -I/JSP/java-APIs/java $fdone

• See jar2ada.sh script

Developing Web Applications with Ada 90

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 91

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 92

Introduction to JDBC

• Establishing a connection

• JDBC statements

• Creating a table

• Updating a table

• Query

• Result sets

• Prepared statements

Developing Web Applications with Ada 93

Establishing a Connection

• Load the driverObj := Java.Lang.Class.NewInstance ( Java.Lang.Class.forName( +"org.gjt.mm.mysql.Driver"));

• Make the connectionCon := Java.Sql.DriverManager. getConnection( URL, User, Password);

Developing Web Applications with Ada 94

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 95

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 96

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 97

Creating a Table

Result := Java.Sql.Statement. executeUpdate(Stmt, +( "create table messages (" & " MessageID int unsigned not null " & " auto_increment primary key, " & " Posted timestamp ," & " Subject varchar(255) not null," & " Body text not null)"));

• Full Example: CreateMessages

Developing Web Applications with Ada 98

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 99

Query

Result := Java.Sql.Statement. executeQuery (Stmt, +( "SELECT * FROM Messages");

• Where are the rows that are returned?

Developing Web Applications with Ada 100

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 101

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 102

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 103

Prepared Statement

• Supply field values:Java.Sql.PreparedStatement. SetString (Stmt, 1, +"subject 3");Java.Sql.PrepareStatement. SetString (Stmt, 2, +"body 3");

• Execute the Prepared StatementRows := Java.Sql.PreparedStatement. ExecuteUpdate (Stmt);

• Example: PrepInsertMessages

Developing Web Applications with Ada 104

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 105

Building a Web Application

• Model-View-Controller architecture

• Page-centric design

• Servlet-centric design

Developing Web Applications with Ada 106

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 107

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 108

Discussion GroupPost New Message

post.html

DatabaseMessage

ControllerMessage

Table

post.jsp

index.html

View

Controller

Model

Developing Web Applications with Ada 109

Discussion GroupRead Messages

msgindex.jsp

DatabaseMessage

ControllerMessage

Table

read.jsp

index.html

View

Controller

Model

MessageBean

Developing Web Applications with Ada 110

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 111

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 112

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 113

Discussion Group – Post New Message

postform.jsp

Database

ForumServlet

MessageTable

index.html

View Controller Model

MessageBean

postconfirm.jsp

Developing Web Applications with Ada 114

JSP and ServletDeployment

JSP pagesHTML documentsimage files

JSP pagesHTML documentsimage files

Contentdirectories

app-name

WEB-INF web.xml

lib

Class files

Packagedirectories

Class files

classes

JAR files

Create this JSP web application directory structure

Adapted from [Fields, Kolb]

Developing Web Applications with Ada 115

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 116

Web.xml: Optional Elements

<display-name>SIGAda 2001 Tutorial

</display-name><description>

Examples and source code fortutorial presentation

</description><welcome-file-list>

<welcome-file>index.html

</welcome-file></welcome-file-list>

Developing Web Applications with Ada 117

Web.xml: Servlet Identification

<servlet><servlet-name>

helloservlet</servlet-name><servlet-class>

helloservlet$typ</servlet-class>

</servlet>

Developing Web Applications with Ada 118

Web.xml: Servlet Mapping

<servlet-mapping>

<servlet-name>helloservlet

</servlet-name>

<url-pattern>/helloservlet

</url-pattern ></servlet-mapping>

Developing Web Applications with Ada 119

Web.xml: Example

• SIGAda 2001 Tutorial– Hello Servlet– Hello from Servlet– Forum Servlet– Java Servlet

Developing Web Applications with Ada 120

Tomcat Server Configuration

• Configure Tomcat to recognize the application we just created: TOMCAT_HOME\conf\server.xml

<Contextpath="/sigada2001"docBase="C:\JSP\Tutorial\app"crossContext="false"debug="0"reloadable="true"trusted="false" >

</Context>

Developing Web Applications with Ada 121

Negatives of JSP

• JSP code does not appear in browser– Harder to debug

• Complexity of edit-transform-compile-load-run cycle– Need javac compiler in production machine– Left-over compilation “crud”

Developing Web Applications with Ada 122

Negatives of JSP

• Error handling– Different types of errors from transform-

compile-load phases of development cycle– JSP pages don’t easily catch certain errors such

as OutofMemoryError– Mysterious errors: CastClassException

Developing Web Applications with Ada 123

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 124

Velocity

• Can also be used as a general-purpose template engine, not just for web pages

• Example: Discussion Group

Developing Web Applications with Ada 125

More to Learn

• How to use JAR files

• How to use Java packages as subdirectories

• Handling Java exceptions


Recommended