You are on page 1of 25

JAVA

Introduction to Java
Java is an object-oriented programming language.
It runs within a Java Virtual Machine.
Everything is an object e.g. okButton is an object (an instance of the Button class)
Objects have methods e.g. okButton.setLabel("OK");
Java Class Libraries (core API) provide classes and methods for common programming tasks e.g. java.lang
(basic java functions), java.awt (fonts, graphics, GUI components), java.sql (SQL-based Database Access)
The Java source code goes through the compiler which creates intermediate code called bytecodes in the
form of class files. This does not get converted into machine executable instructions yet in Java but this
stage is instead delayed until runtime.
Java Development Kits (JDK)

Platform-specific.
Used by programmers to create Java software.
Consist of a compiler, core class libraries, tools for testing and debugging and a JVM.

Java Runtime Encironments (JRE)

Platform-specific.
Only provide what is necessary to run Java programs (i.e. a JVM).

Java Applications

Can run in network or standalone environments.


Require a platform-specific JVM.
Typically consist of several classes. At least one of the classes must have a main() method.

Java Applets

Embedded in web pages.


Downloaded from the server to the client along with images etc.
Run within the web browsers JVM.
Based on a core API known as java.applet.Applet and has many predefined methods (e.g. init(),
start(), paint(), stop(), destroy().

Java Servlets

Run within the servers JVM and sends HTML to the browser. No JVM is required at the browser
side.
Build the web pages that are sent to the client to be processed by the web browser.
Started either when the web server is started or when the URL is accessed for the first time.
Methods (e.g. init(), service(), destroy())

Java Compatible

Logo appearing on products that create or run Java software and have passed the certification
process.

100% Pure Java

Logo appearing on Java-based software products that run within a Java Compatible JVM.

AS/400 Development Kit for Java

Java compatible
Consists of Java compiler, Java class libraries, Tools and JVM for OS/400.

AS/400 Toolbox for Java

100% Pure Java i.e. not platform-specific


Consists of classes that allow access to AS/400 objects.

Getting Started with Java


Downloading the JDK
Java Development Kit (JDK) 1.1.8
Download from java.sun.com/products/jdk/1.1. as one large bundle, HTTP download.
Install by running downloaded EXE from Windows Explorer.
Components: Program Files, Library and Header Files, Demo Applets.
Create directory to store Java programs (e.g. ATSAJV1).
Modify PATH and CLASSPATH Environment Variables
PATH indicates where the JDK commands can be found.
CLASSPATH indicates where class files (particularly Java class libraries) can be found.

Change AUTOEXEC.BAT or create batch file (SETPATH.BAT) to be run as required:

AUTOEXEC:

Click Start. Run, type "sysedit", click OK.


Add 2 lines at the end.
Save file and exit editor.
Reboot PC.

Batch File:

Open a new file with text editor.


Add 2 lines.
Save file in ATSAJV1 with name SETPATH.BAT and exit editor.
Each time you open a command prompt to compile or test a Java program, run the SETPATH
batch command.

Lines to add:
SET PATH=C:\JDK1.1.8\BIN;%PATH%
SET CLASSPATH=C:\ATSAJV1;%CLASSPATH%
Create a simple test program open a text editor like Notepad and enter statements like Test.java. Save file.
Compiling a program

Open a DOS prompt window. If appears as a full screen, press Alt and enter to place it in a
window.
Doskey (so can use arrow keys to access previous commands or F7 to see all with F9 and number
to run a specific command)
cd \atsajv1 - to make ATSAJV1 the current directory.
Setpath if not changed autoexec.
javac Test.java. If the DOS prompt appears and no other text was displayed then the compile was
good.

Running a program

java Test

If problems, type set to view the environment variables such as path and classpath details.
JDK Documentation
Access index.html in directory where you installed the JDK. Will open documentation in browser. Choose
to access either locally (if downloaded and installed the JDK documentation) or on Java Software website.
Scroll down to Java Platform 1.1 Core API Specification.

AppletViewer Utility
e.g. appletviewer testapplet.html
Click on Applet tag top left useful are Tag and Properties (set network and class access to unrestricted to
allow an applet to be tested)
Uses same JVM version as the JDK. A java enabled browser may use a different version of the JVM.
The appletviewer utility processes the applet tag in the HTML only and ignores other tags.
Useful documentation on-line e.g. Package index bookmarked.
Note: Java is very case-sensitive !!!

Java Basics
e.g. Computer.java
Class

A class defines data items and methods for acting on them.


The compiled object will have the name of the defined class with ".class" extension.

Method

Methods are the means of accessing the data items.


Have modifier(s), type of return value, method name, parameter list in parentheses.
Modifier(s) e.g. public, static
Type of return value e.g. void or type of variable/object
Method name e.g. main, setExpirationDate
Parameter list e.g. main (), main (String args[]) square brackets indicate an array, 2 or more
parameters are separated by commas.

Java Language Syntax

Java ignores blank lines and spaces between names, keywords and operators.
A semi-colon indicates the end of a line of executable code.
Usually a block of code is started on an existing line i.e. { on same line.
Java programs typically output their results to a graphical interface. A simple way is to use the
built-in java function System.out.println.

Java Application

The source file and class name should be the same.

Generally a java source file defines one class.

Instance Variables

Defined after the class name and before (or between) any methods.
Format is: data-type variableName;
If same type, can be defined on one line e.g. int cpuSpeed, memory;

Local Variables

Local to a method
Defined by and used in the method
Scope is limited to the method in which it is declared
Values are not available to other methods
Can have the same names as instance variables and will be used (i.e. the instance variable is
hidden). If use the same names, will have to qualify with "this" if want to reference the instance
variable.
Can be defined in a parameter list

Static Variables

The closest thing in Java to a global variable.


Has a larger scope than instance variables.
Can be shared among instances of a class and accessed by all methods in the class and its
instances.
Exists only in the class, not in an instance of the class.
e.g. static int numberOfComputers;

A common use is to keep track of the number of instances of an object that have been created.

Incrementing
numberOfComputers = numberOfComputers + 1; is the same as
numberOfComputers++;
same for -Comments

Single line comments begin with // and continue to the end of the line
Multiple line comments can span multiple lines when enclosed between /* and */

Data Types
Note: String is not a primitive data type. It is a type of object defined in the core APIs. It has a capital "S".

Primitive data types: byte, short, int, long, boolean, char, float, double.

Creating an Instance of a Class with "new"


A class is a template that defines the attributes for an "instance" of an object. Instances are created for
specific objects.
e.g. class Computer has 4 instance variables defined. Then, within the main method, instances can be
created so that there are multiple versions of the variables.
e.g. class Computer { .
public static void main() {
Computer unit = new Computer(); - unit is an instance of the Computer class object
When an instance is created, its method and variable names are typically prefixed with the instance name
and separated with a period e.g. unit.cpuType
Static methods, such as main, and static variables are NOT created as part of an instance of a class.
Assignment and Numeric Literals
The type of value must be known on both sides of the equal sign.
An uppercase or lowercase "L" explicitly sets the type of numeric literal to "long integer". This should be
done when the value is outside 2,147,483,648 to 2,147,483,647
A "F" explicitly sets it to float.
A "D" explicitly sets it to double.
e.g. unit.cpuType = "Pentium";
unit.cpuSpeed = 133;
unit.disk = 5368709120L;

Naming Conventions
No technical restriction on length and can consist of most characters on keyboard. The first character must
be alphabetic, an underscore or a dollar sign.
Length
Class Xxxxx {
}

< 15 chars

Example
One or more words (usually
nouns), no separators, first
letter of each word is
uppercase.

Class TestClass {
}

Method

One or more words (usually


verb followed by noun), no
separators. First word
lowercase, first letter of
subsequent words is
uppercase.

GetCustomerName

Variable

One or more words (usually


nouns), no separators. First
word lowercase, first letter of
subsequent words is
uppercase.

FirstName

Constructors and "this"


E.g. Computer2.java

A Constructor is a special type of method that initialises instance variables when an instance is
created
A return type is not specified since it is implicitly an instance of the object.
Every class has a constructor a default one exists if one is not explicitly coded.
A default constructor initialises primitive data type variables to zero.
The constructor method name is the same as the class name.
The constructor is defined like a method.
The name of the constructor must be the same as the class name.
The constructor can accept incoming parameter values and use them to set the values of the
instance variables.
"this" is a lot like the word "me" in that the person referred to depends on who is saying it.
"this" is a means of referring to a current instance of an object without having to know its name.
The name of the instance is established outside of the constructor. Inside the constructor the
variables are qualified with "this".
When a constructor method is explicitly coded, the default constructor is no longer available.

Constructors are usually the first methods declared in a class.


Use "this" in an instance method to reference the instance variables.

this() Invocation

A special technique for calling the primary constructor from other constructors in the same class.
It must be the first executable line in the constructor and is often the only executable line.

If-Then-Else
if(condition) statement;
if(condition) {
statement1;
statement2;
statement3;
}

No endif

if(condition) statement;
else statement;
if(condition) {
statement1;
statement2;
statement3;
}
else {
statement4;
statement5;
}

Relational Operators
== equal to
!= not equal to
>
>=
<
<=
Logical Operators
&& and
|| or
Multiple Methods with the Same Name

A method name can be used more than once as long as the parameter list is unique.
The data types in a parameter list are what makes one methods signature different from another.
Known as method overloading.
Constructor methods are usually overloaded by at least one version that accepts no parameter
values and thus serves as a default constructor

Packages and Inheritance


e.g. in com\ats\ajv1 - computer.java, installedcomputer.java

A package is a means of managing java projects.

It avoids naming conflicts by organising java classes using a hierarchical file system and Internet
host/domain name conventions.
Typically consists of the top level domain (com, net, org etc) followed by the domain or company
name, followed by naming elements that identify the group of Java classes.

A class is made part of a package by including a package stmt at the top of the java source file
e.g. package com.xyzcorp.admin.hr.utils;
If no package name is specified the compiled class will belong to the "default package".

Examples
Package name com.xyzcorp.admin.hr.utils
Directory structure c:/java/classes/com/xyzcorp/admin/hr/utils/Computer.class
Classpath setting CLASSPATH = c:\java\classes
Java run command java com.xyzcorp.admin.hr.utils.Computer
Or: Com.ats.ajv1
C:\atsajv1\com\ats\ajv1\Computer.class
CLASSPATH = c:\atsajv1
Java com.ats.ajv1.Computer
Cd \atsajv1
Md com
Md com\ats
Md com\ats\ajv1
First, create directory structure then create source within structure with package code.
Access Control Modifiers
public can be accessed by classes in any package
Package this is the default. Can be accessed only by other classes in the same package
protected Can be accessed only by other classes in the same package
and by subclasses referenced from other packages
private Can be accessed only by methods in the same class

Subclasses and Superclasses (Inheritance)

A superclass is a class from which another class inherits methods and variables.
A subclass is a class that inherits methods and variables from another class.
Extends keyword is used in the class declaration. It identifies the superclass and makes the current
class a subclass of it.
e.g. public class SomeSubClass extends SomeClass {
An instance of the subclass inherits the instance methods and variables from the superclass.
In the subclass source, the primary constructor will accept some variable parameters from the
superclass and some from the subclass.
The "super" keyword invokes the constructor for the superclass with its parameters. It must be the
first executable line in the subclass constructor method.
The remaining code of the subclass constructor needs only to set the values of the subclass
instance variables.
An instance method in a subclass will override a method of the same name in the superclass.

Accessor Methods

Methods that get or set a variable.


Should be wider in scope (i.e. more public) than the variables they encapsulate.

Applet Basics
e.g. testapplet
How it works
Web browser requests the webpage.html file
Web server send the file plus the applet class
The applet class is loaded into the browsers JVM only once so if you change the applet you need to exit
the browser and restart it.
Every applet is a subclass of java.applet.Applet.class (which is itself a subclass).
Methods
1.

Init is only called once

2.
3.
4.
5.
6.

Start is called after init and each time the web browser returns to the web page containing the
applet
Paint is called after start and each time the web browser window is uncovered or redisplayed
Stop is called when the web browser leaves the web page but the applet remains in memory
Destroy frees up resources used by the applet and is called when the applet is terminated
immediately after the stop method
Other inherited methods exist

Use the package documentation to view inheritance, methods, constructors etc.

Example HTML:
<applet code="TestApplet.class" width=150 height=30>
The applet tag determines the size of the area in which the applet displays its results. It must be large
enough to accommodate the results or some portions may not appear as intended.
Code this is required and identifies the applet class file. If the applet belongs to a package the fully
qualified name must be specified and the directory structure must be present on the server.
Width/height these are required and specify the size of the applet area in terms of pixels.
Codebase specifies the directory path where the applet class is located. If not used it defaults to the same
path as the HTML file,
Archive contains a collection of support classes (not Java class libraries) needed by the applet
Name if multiple applets are embedded in a single HTML file and need to communicate with each other,
they must be referred to by name
Align/vspace/hspace same as IMG tag. They align the applet area in relation to text and other objects
embedded in the HTML file
Param this passes a single parameter name and value to the applet. Multiple parameters can be used.
Alt specifies a string of alternate text to be displayed if the browser is not Java-enabled but is able to
recognise the applet tag.
Classes and packages can be imported into the applet source to shorten references to objects within them.
Coded after package statement and before class declaration. Can use wildcard *. The java.lang package is
implicitly imported into every class you create.
Every class is a subclass of java.lang.object.
Java must be enabled in your browser.
The Java Console should be enabled for debugging etc change in Internet Settings and restart PC.
Classes in the Abstract Window Tool (AWT) Package

Java.awt.Font
Java.awt.Graphics
Java.awt.Color

Abstract Window Toolkit (AWT) Components


e.g. L07applet, quiz

The abstract modifier is a means of requiring that a class be subclassed or that a method be
overridden

e.g. public abstract class anAbstractClass { this must be subclassed (extended)


e.g. . public abstract void anAbstractMethod(); this must be implemented and overridden in a sub
class.

The final modifier essentially freezes or locks a class, method or variable.

e.g. public final class AfinalClass { this cannot be subclassed


e.g. public final void AfinalMethod() { this cannot be overridden
e.g. public final String AFINALVARIABLE = "CONSTANT"; this cannot be changed so is essentially a
constant. It is common practice to use uppercase characters in the names of final variables.
Common GUI Components
They are subclasses of the java.awt.Component class and inherit many useful methods. Each component
has its own method for setting values, fonts, adding items and other attributes. Some components have only
one constructor while others have several.
They are added to an applet using the applets add() method.
By default they appear in the panel according to the FlowLayout format (left to right, top to bottom).
Label

Label

TextField

Single line input box

Button

Push button

List

Scrollable, 1 or more can be selected

TextArea

Multi line input box

Choice

Drop down list. Only 1 can be selected

Checkbox

Checked or not checked

CheckboxGroup

Radio button group. Only 1 can be selected

Scrollbar

e.g. volume control

Disabling a component makes it unresponsive to user actions and will look grayed-out.
Components added on the fly are unreferenceable and do have names assigned to them
automatically but are difficult to use.
Buttons and checkboxes have their own labels.

Retrieving HTML Parameter Data from the Web Page via getParameter()
Only string data can be passed.
HTML e.g. <applet code="ParameterApplet.class" width=200 height =80>
<param name=parameter1 value="value1">
<param name=paramtere2 value="value2">
JAVA e.g. labelno1.setText(getParameter("parameter1"));
add(labelno1);
String parm2 = getParameter("parameter2"));
add(new Button(parm2));
Boolean primitive data type true or false.
e.g. if (overdue == true) or just if (overdue)

Layouts and Panels


e.g. L08applet, Multipanelapplet, Quiz2
The arrangement of components in a container is dictated by a Layout Manager.

FlowLayout

FlowLayout is the default layout manager. Components appear on the panel in the order in which they are
added and are centered.
Insets

Represent the amount of pixel space between the components and the 4 edges of the panel.
Default is 10 units for top, bottom, left and right.

Hgap and Vgap

The default horizontal and vertical gaps between components is 5 units.

Can change defaults:


e.g. setLayout(new FlowLayout(FlowLayout.LEFT, 10, 1));

this left-adjusts the components an sets the Hgap to 10 and the Vgap to 1

e.g. setLayout(new FlowLayout(FlowLayout.RIGHT));


If code the getInsets() method, it is called automatically. The values returned to the caller become the
empty pixel space between the top, bottom, left and right edges and the components in the panel.
e.g. public Insets getInsets() {
return new Insets(15, 15, 15, 15);
No executable code can appear after the return operator.

GridLayout

Only one component is allowed in a cell.


The add(component) method adds a component to the next empty cell.
The grid is extended as needed to make room for additional components.
Components are stretched to fit the grid cell so can look weird.

SetLayout(new GridLayout(numrows, numcols, hgap, vgap));


(1, 0) all components appear in 1 row and as many columns as necessary
(2, 0) all components appear in 2 rows and as many columns as necessary

(0, 1) all components appear in 1 column and as many rows as necessary


(0, 3) all components appear in 3 columns and as many rows as necessary
Note: If the number of rows is not zero, the number of columns will be treated as zero.

BorderLayout

5 regions "North", "East", "South", "West" and "Center"


Only one component is allowed in a cell (region).
Components are stretched to fit the cell.
The add("Region", component) method adds a component to a specified region.
Adding a new component to a region replaces a component that was previously added.
The add(component) method adds a component to the "Center" region.

Panels within Panels


e.g.

use BorderLayout for the applet panel


add FlowLayout to "North" region
do not use "East" region
leave "South" region as it is
add GridLayout to "West" region

add GridLayout to "Center" region

Component and Container Methods


In addition to its instance name, each component is assigned an "internal name" by the browser as it is
added to a panel. The names may be different each time the browser runs the applet.
setName( ) sets the component name e.g. button.setName("Button");
getName() gets the component name e.g. String somename = button.getName();
getComponent(int) gets the nth component in the container. Components are indexed with the first having
an index of 0.
getComponentCount() gets the number of components in the container.
getComponents() gets all the components in the container and places them in an array. E.g. Component[]
components = getComponents();
Arrays

The [] brackets can appear after the data type or after the variable name:
e.g. int[] intArray; or int intArray[]
Can be declared with initial values:
e.g. String[] months = {"Jan, "Feb", "Mar"}
Can also store objects:
e.g. Component[] components = getComponents();
add(components[1]);
Can be set to a specific size:
e.g. int[] days = new int[12];
Can be multi-dimensional:
e.g. String [] [] twoDimArray = new String [2] [3];
Have a length variable that yields the number of elements they contain:
e.g. for (int i = 0; i < components.length; i++)
For Loop
For (loop counter initialisation,; condition for continuation; loop iteration interval)
The condition is tested at the beginning of the loop.
The iteration is done at the end of the loop.
If you declare the counter in the for loop then its scope is limited to the loop.
The counter can be declare and initialised before the for loop.
The counter can be incremented or decremented by any amount.
Multiple counters and incrementers can be specified but only 1 condition e.g. for (i=0, j=10; i<=j; i+=2, j+
+)
Boolean expression e.g. for (; button.isEnabled();)
Instanceof Operator
The instanceof operator tests whether or not an object is an instance of a particular class.
e.g. if (a instanceof Computer)

Event Handling
e.g. Eventapplet, PriceCalcApplet, Quiz3
Events are initiated by the user, issued by a component, heard by a listener and processed by the listener
interface methods implemented in the applet.
Steps for handling an event:
1.
2.
3.
4.
5.

Identify the component that will issue the event.


Look in the components list of methods for an addXxxListener() method.
Implement the listener interface in the class declaration.
Call the components addXxxListener() method.
Declare each of the interface methods in the class but code only the one(s) relevant to the event.

Similar components that use the same type of listener will call the same interface method. To distinguish
one from another, call the event objectss getSource() method to assign the result to a generic object, then
use "if" blocks to compare this object to the component in question and condition your code. See examples.
Types of Event Listeners:
Component

ComponentListener

Changes to size or location

Container

ContainerListener

Added or removed contents

TextField/TextArea

TextListener

Changes to text

List/Choice

ItemListener

Changes in item selection

Button/List/TextField

ActionListener

Click/release button, doubleclick List item, press Enter in a


TextField

Component

FocusListener

Focus gained or lost

Keystrokes

KeyListener

Keys pressed, released, typed


when component has focus

Scrollbar

AdjustmentListener

Changes in bubble position

Mouse

MouseListener

Component entered, exited,


clicked

Mouse

MouseMotionListener

Dragging and releasing

Interfaces

A java interface provides an interface between two java objects.


An interface declares but does not implement methods.
A class that implements an interface must implement the methods (unless the class is abstract).

The implemented interface methods can be called by another object.


Implementing an interface makes the class an instance of the interface.

Implementing and Declaring Interfaces


Implementing

Use implements keyword in the class declaration statement e.g. public class ClassA extends
Applet implements InterfaceX, InterfaceY {
The methods declared in the interface must also be declared in the class that implements the
interface.
Some interfaces declare several methods. A class that does not need certain interface methods can
code them to do nothing.

Declaring
e.g. public interface InterfaceX {

The interface keyword indicates that the source file will be compiled as an interface rather than a
class.
Access to an interface must be public or package.
Variables are implicitly static and final and must be initialised.
An interface can extend another interface.
A class that implements an extended interface must implement all the methods in the hierarchy.

Deprecation

No longer recommended but still supported for the time being.


The Java compiler will issue warnings when deprecated methods are used.
Replacements for deprecated methods are documented.

Converting String Data to Primitive Data

Each primitive data type is represented by a wrapper class in the java.lang package.
Most of them have a valueOf() method that converts a String into an instance of the wrapper class.
Most of them have methods for converting instances of the wrapper class into a primitive data
type.

i.e. primitive varName = WrapperClass.valueOf(String).primitiveValue();


e.g. int intVariable = Integer.valueOf(txtVariable.getText()).intValue();
Exception Handling

An exception is an object that contains descriptive information about an error condition.


The exception classes are defined in the java.lang package and are listed separately in an
Exceptions index.
To monitor a block of code for an exception, place it in a try block.
To trap and handle generic or specific exceptions, code a catch block for the exception type.
With multiple catch blocks, different types of exceptions can be handled in the same try block in
different ways. The more generic exception types should be handled last.
Try/catch blocks may be nested.
To ensure that some type of housekeeping occurs even if the try/catch blocks branch out or return,
code a finally block. A try block must include a catch block OR a finally block OR both.

AS/400 Toolbox for Java


E.g. AS400CmdTestApplet (in Java for PC based, in ATSAJV1 when deployed on AS/400)
The AS/400 Toolbox for Java

The toolbox contains 100% pure java classes and interfaces for accessing AS/400 objects.
Programs that use toolbox classes will run in any JVM.
It has been modified more than once as enhancements and fixes are added.
Installation on the AS/400 is not required. For development purposes, the jt400.jar (or jt400.zip)
file must be copied to the PC and cited in the CLASSPATH variable change AUTOEXEC or
SETPATH.BAT.
It can be installed on the AS/400 as Licensed Program Product 576xJC1, maintained with PTFs
and distributed to developers and applications.
The latest version can be obtained from www.as400.ibm.com/toolbox. Downloads, evaluation
copy, download evaluation copy, select jt400All.zip link. Uncompress using WinZip select zip
file on PC, choose only jt400.jar and jt400.zip and press Extract Check "selected files" and DO
NOT use folder names.
The toolbox classes provide access to the AS/400 through the several host servers: *SIGNON,
*DATABASE, *DDM, *FILE, *DTAQ, *RMTCMD, *NETPRT, *SVRMAP, *CENTRAL

The AS400 Class

The AS400 class establishes a connection to the AS/400, requests services for accessing data
queues, IFS and database files, running commands and programs, obtaining information about the
AS/400, ending the connection and many other things.

The constructors allow you to build objects that represent AS/400s. Various constructors accept the
system name or IP address, user ID and password.
The connectservice() method establishes a connection to an AS/400 host server.
The disconnectService() method breaks a connection to an AS/400 host server.

The CommandCall Class

The CommandCall class is an object that allows CL commands to be run on the AS/400 and get
messages that indicate their success or failure.

The constructors allow you to build command objects associated with a specific AS/400 system
and/or a specific command string.
The run() method executes the command.

Testing and Deploying Applets

Built-in applet security prevents reading and writing to client files, initiating client programs,
displaying a window without identifying it as an applet or unsigned window and connecting to a
host that is not the originator of the applet.
The Applet Viewer utility allows you to test applets that connect to the AS/400 and are unrestricted
by network and class access (set in properties).
In order to insure that a deployed applet is served from the server rather than the development PC,
it may be necessary to rename the class file on the PC.
The codebase attribute of the applet tag is the directory path to the applet class file. The path is
relative to the html files directory unless it has a leading slash which makes it an absolute path
from the web server root. To point to a peer directory, use the "../" sequence.
If no archive is specified in the applet tag, the packages of classes used in the applet must be
available from the server.
The archive attribute of the applet tag is the path to a jar (Java ARchive) file, a zip file or a cab file
(MS). The path and file is relative to the codebase path unless it has a leading slash.
The entire archive file (jar, zip or cab) will be downloaded to the client.
An archive can be created that contains only the classes needed by the applet which makes it
smaller and quicker when it is downloaded. There are class file dependencies over and above those
actually referenced in the applet. The later toolboxes include a JarMaker utility. Uncompress all of
the classes related to AS400ToolboxInstaller and JarMaker.

Options for large archive files:


1.

Use the jt400.jar file as is and specify archive = "jt400.jar" in the applet tag. It will be downloaded
to the client PC.

2.

3.

Uncompress the jar/zip file in the web server directory structure and omit the archive attribute
from the applet tag. Each class file will be downloaded as needed. There are class file
dependencies over and above those actually referenced in the applet. The web access log will tell
you which ones.
Reduce the size of the archive file by placing in it only the classes used by the applet. Specify
archive = "400cmd.jar" in the applet tag. The JarMaker utility can extract the necessary classes
from jt400.jar and place them in a separate jar file.
e.g. In DOS prompt - C:\Atsajv1>java utilities.JarMaker s jt400.jar d 400cmd.jar rf
com/ibm/as400/access/AS400.class,com/ibm/as400/access/CommandCall.class

To check - C:\Atsajv1>dir *.jar


Copy the 400cmd.jar file to the AS/400 IFS
Note: I could not get the applet to work correctly when deployed on the AS/400. It would not accept a valid
userid and password, eventually disabling the userid after 3 failed attempts.

Accessing DB2/400 Files with JDBC


e.g. CustListApplet, OrderListApplet, ItemListApplet
Access to DB2/400 files through the *DATABASE server requires a *LOCAL entry in the AS/400s
Remote Database Directory. Run WRKRDBDIRE command to see the list of entries. If no entry with a
Remote Location value of *LOCAL appears, add one using Option 1, specifying your AS/400s system
name in the Relation Database field and put *LOCAL as the remote location.
SQL access to a database is accomplished through Java DataBase Connectivity using a driver designed for
a specific RDBMS product. There are 4 types of JDBC drivers:
1.
2.
3.
4.

JDBC-ODBC bridge plus ODBC driver.


Native-API partly-Java driver.
JDBC-Net pure Java driver.
Native-protocol pure Java driver (The AS400JDBCDriver is of this type).

Classes/Interfaces used:

Com.ibm.as400.access.AS400JDBCDriver
Java.sql.DriverManager
Java.sql.Connection
Java.sql.Statement

Java.sql.ResultSet

Overview:

Register the AS/400 JDBC Driver with the SQL Driver Manager
Create a Connection object and establish a connection
Create a (SQL) statement object
Create a ResultSet object by executing the SQL statement
Process the result set

Registering the JDBC driver allows it to be used as a subprotocol when connecting to the database. The
database connection is expressed as a JDBC URL.
A JDBC driver is registered using the java.sql.DriverManagers registerDriver() method.
Once the driver is registered there are 3 types of objects used for SQL actions:
Java.sql.Connection
Java.sql.Statement (for static SQL) or java.sql.PreparedStatement (for dynamic SQL)
Java.sql.ResultSet
The objects are usually created as instance variables to achieve persistence (global scope).
The connection to the DB2/400 database is established when the DriverManagers getConnection() method
is called and the JDBC URL is specified.
A static SQL statement can be created (or allocated) using the Connection objects createStatement()
method.
A static SQL statement can be composed and executed using the Statement objects executeQuery()
method. Its results are placed in a ResultSet object.
A dynamic SQL statement can be composed using the Connection objects prepareStatement() method.
A dynamic (prepared) SQL statements parameter markers can be replaced with real values using the
Statement objects methods for specific data types.
A dynamic (prepared) SQL statement can be executed using the Statement objects executeQuery() method.
Its results are placed in a ResultSet object.
The ResultSet is typically processed by a "while" block that reads each row and extracts data from
columns.
SQL-related errors and warnings are described by the SQLException, SQLWarning and Data Truncation
exception classes in the java.sql package and "thrown" by the JDBC driver. Some SQL errors are caught as
generic Exceptions.
An exception objects getMessage() method returns the descriptive text of an exception. An SQLException
objects getSQLState() and getErrorCode() methods get the SQL state and SQL code respectively.

An exception objects printStackTrace() method sends the backtrace to the standard error stream.
Additional debugging information can be obtained by setting the errors and trace JDBC properties to "full"
and "true" respectively.
Creating the 400jdbc.jar file:
C:\atsajv1>java utilities.JarMaker s jt400.jar d 400jdbc.jar rf
com/ibm/as400/access/AS400JDBCDriver.class
When deploy on AS/400:

Create smaller jar file as above


Copy html, class and jar files to the AS/400 IFS
Edit the html so it includes codebase and archive paths.
Rename the local class file to avoid runtime conflicts.
Access the html file on the AS/400

Database I/O with SQL


An application can be designed as a single class or as a collection of smaller classes which are easier to
design and maintain, objects are easier to reuse and isolated functions are easier to troubleshoot.
Model/View/Controller (MVC)

model represents the data e.g. constructors, getters, setters, rulers


view is the representation of the data to the user e.g. GUI interface, exception reporting, status
reporting
controller handles the interactions between the view and the model e.g. DB connections, SQL
statements, result sets

The "throws" keyword, specified in a method declaration, throws exceptions back to the caller. At least one
type of exception to throw must be specified. Methods that throw exceptions must be called from within a
try/catch block. The need for this capability arises when exceptions occur in non-view classes where they
dont have direct access to the user interface.
The Statement and PreparedStatement classes (java.sql package) have an executeUpdate() method for
executing SQL statements that dont return a result set.

The BigDecimal class (java.math package) is well-suited for handling numbers with a fixed number of
digits and decimal places.
The Vector class (java.util) is similar to an array but the size of vector objects can be changed and its
element can store different types of objects.
The JDKs jar utility allows you to build jar files from scratch e.g. cust400.jar.

Examples of MVC:
Model customer.java and custListData.java
View custMaintApplet.java
Controller customerDataStore.java

You might also like