(Ebook PDF) - Java Programming Language Basics
(Ebook PDF) - Java Programming Language Basics
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/index.html
Training Index
Contents
Lesson 1: Compiling and Running a Simple Program
A Word About the Java Platform
Setting Up Your Computer
Writing a Program
Compiling the Program
Interpreting and Running the Program
Common Compiler and Interpreter Problems
Code Comments
API Documentation
More Information
Lesson 2: Building Applications
Application Structure and Elements
Fields and Methods
Constructors
1 of 3
21-04-2000 17:30
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/index.html
To Summarize
More Information
Lesson 3: Building Applets
Application to Applet
Run the Applet
Applet Structure and Elements
Packages
More Information
Lesson 4: Building a User Interface
Swing APIs
Import Statements
Class Declaration
Global Variables
Constructor
Action Listening
Event Handling
Main Method
Applets Revisited
More Information
Lesson 5: Writing Servlets
About the Example
HTML Form
Servlet Backend
More Information
Lesson 6: File Access and Permissions
File Access by Applications
Exception Handling
File Access by Applets
Granting Applets Permission
Restricting Applications
File Access by Servlets
Appending
More Information
Lesson 7: Database Access and Permissions
Database Setup
Create Database Table
Database Access by Applications
Establishing a Database Connection
Final and Private Variables
Writing and Reading Data
Database Access by Applets
JDBC Driver
JDBC-ODBC Bridge with ODBC Driver
2 of 3
21-04-2000 17:30
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/index.html
Reader Feedback
Tell us what you think of this training book.
Very worth reading
Worth reading
If you have other comments or ideas for future training books, please
type them here:
Submit
Reset
[TOP
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
3 of 3
21-04-2000 17:30
Java(TM) Language Basics, Part 1, Lesson 1: Compiling & Running a Simple Program
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/compile.html
Training Index
The computer age is here to stay. Households and businesses all over
the world use computers in one way or another because computers help
individuals and businesses perform a wide range of tasks with speed,
accuracy, and efficiency. Computers can perform all kinds of tasks
ranging from running an animated 3D graphics application with
background sound to calculating the number of vacation days you have
coming to handling the payroll for a Fortune 500 company.
When you want a computer to perform tasks, you write a program. A
program is a sequence of instructions that define tasks for the computer
to execute. This lesson explains how to write, compile, and run a simple
program written in the Java TM language (Java program) that tells your
computer to print a one-line string of text on the console.
But before you can write and compile programs, you need to understand
what the Java platform is, and set your computer up to run the programs.
A Word About the Java Platform
Setting Up Your Computer
Writing a Program
Compiling the Program
Interpreting and Running the Program
Common Compiler and Interpreter Problems
Code Comments
API Documentation
More Information
1 of 6
21-04-2000 17:30
Java(TM) Language Basics, Part 1, Lesson 1: Compiling & Running a Simple Program
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/compile.html
Note: Make sure you have the Java platform installed and
configured for your system before you try to write and run the
simple program presented next.
Writing a Program
The easiest way to write a simple program is with a text editor. So, using
the text editor of your choice, create a text file with the following text, and
be sure to name the text file ExampleProgram.java. Java programs
are case sensitive, so if you type the code in yourself, pay particular
attention to the capitalization.
//A Very Simple Example
class ExampleProgram {
public static void main(String[] args){
System.out.println("I'm a Simple Program");
}
2 of 6
21-04-2000 17:30
Java(TM) Language Basics, Part 1, Lesson 1: Compiling & Running a Simple Program
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/compile.html
3 of 6
21-04-2000 17:30
Java(TM) Language Basics, Part 1, Lesson 1: Compiling & Running a Simple Program
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/compile.html
Code Comments
Code comments are placed in source files to describe what is happening
in the code to someone who might be reading the file, to comment-out
lines of code to isolate the source of a problem for debugging purposes,
or to generate API documentation. To these ends, the Java language
supports three kinds of comments: double slashes, C-style, and doc
comments.
Double Slashes
Double slashes (//) are used in the C++ programming language, and tell
the compiler to treat everything from the slashes to the end of the line as
text.
//A Very Simple Example
class ExampleProgram {
public static void main(String[] args){
System.out.println("I'm a Simple Program");
}
}
C-Style Comments
Instead of double slashes, you can use C-style comments (/* */) to
enclose one or more lines of code to be treated as text.
/* These are
C-style comments
*/
class ExampleProgram {
public static void main(String[] args){
System.out.println("I'm a Simple Program");
}
}
Doc Comments
To generate documentation for your program, use the doc comments
(/** */) to enclose lines of text for the javadoc tool to find. The
javadoc tool locates the doc comments embedded in source files and
uses those comments to generate API documentation.
4 of 6
21-04-2000 17:30
Java(TM) Language Basics, Part 1, Lesson 1: Compiling & Running a Simple Program
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/compile.html
API Documentation
The Java platform installation includes API Documentation, which
describes the APIs available for you to use in your programs. The files
are stored in a doc directory beneath the directory where you installed
the platform. For example, if the platform is installed in
/usr/local/java/jdk1.2, the API Documentation is in
/usr/local/java/jdk1.2/doc/api.
More Information
See Java 2 SDK Tools for more information on setting the class path and
using the javac, and java commands.
See Common Compiler and Interpreter Problems lesson in The Java
Tutorial for troubleshooting help.
The javadoc Home Page has more information on the javadoc command
and its output.
You can also view the API Documentation for the Java 2 Platform on the
java.sun.com site.
_______
1
As used on this web site, the terms "Java virtual machine" or "JVM"
mean a virtual machine for the Java platform.
[TOP]
5 of 6
21-04-2000 17:30
Java(TM) Language Basics, Part 1, Lesson 1: Compiling & Running a Simple Program
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/compile.html
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
6 of 6
21-04-2000 17:30
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/prog.html
Training Index
All programs written in the Java TM language (Java programs) are built from
classes. Because all classes have the same structure and share common
elements, all Java programs are very similar.
This lesson describes the structure and elements of a simple application
created from one class. The next lesson covers the same material for
applets.
Application Structure and Elements
Fields and Methods
Constructors
More Information
1 of 6
21-04-2000 17:30
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/prog.html
The public static void keywords mean the Java 1 virtual machine
(JVM) interpreter can call the program's main method to start the
program (public) without creating an instance of the class (static), and the
program does not return data to the Java VM interpreter (void) when it
ends.
An instance of a class is an executable copy of
the class While the class describes the data and
behavior, you need a class instance to acquire
and work on data. The diagram at the left
shows three instances of the
ExampleProgram class by the names:
FirstInstance, SecondInstance and
ThirdInstance.
The main method is static to give the Java VM interpreter a way to start
the class without creating an instance of the control class first. Instances
of the control class are created in the main method after the program
starts.
The main method for the simple example does not create an instance of
the ExampleProgram class because none is needed. The
ExampleProgram class has no other methods or fields, so no class
instance is needed to access them from the main method. The Java
platform lets you execute a class without creating an instance of that class
as long as its static methods do not call any non-static methods or fields.
The ExampleProgram class just calls System.out.println. The
java.lang.System class, among other things, provides functionality to
send text to the terminal window where the program was started. It has all
static fields and methods. The static out field in the System class is type
PrintStream, which is a class that provides various forms of print
methods, including the println method.
2 of 6
21-04-2000 17:30
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/prog.html
The static fields and methods of a class can be called by another program
without creating an instance of the class. So, just as the Java VM
interpreter command could call the static main method in the
ExampleProgram class without creating an instance of the
ExampleProgram class, the ExampleProgram class can call the
static println method in the System class, without creating an
instance of the System class.
However, a program must create an instance of a class to access its
non-static fields and methods. Accessing static and non-static fields and
methods is discussed further with several examples in the next section.
Note: The field and method return values are all type String.
class LessonTwoB {
String text = "I'm a Simple Program";
static String text2 = "I'm static text";
String getText(){
return text;
}
String getStaticText(){
return text2;
}
public static void main(String[] args){
3 of 6
21-04-2000 17:30
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/prog.html
The LessonTwoC.java program accesses the static text field with the
static getText method. Static methods and fields are called class
methods and fields. This approach allows the program to call the static
getText method directly without creating an instance of the LessonTwoC
class.
class LessonTwoC {
static String text = "I'm a Simple Program";
//Accessor method
static String getText(){
return text;
}
public static void main(String[] args){
String retrievedText = getText();
System.out.println(retrievedText);
}
}
So, class methods can operate only on class fields, and instance methods
can operate on class and instance fields.
You might wonder what the difference means. In short, there is only one
copy of the data stored or set in a class field but each instance has its own
copy of the data stored or set in an instance field.
The figure above shows three class instances with one static field and one
instance field. At runtime, there is one copy of the value for static Field A
and each instance points to the one copy. When setFieldA(50) is called on
the first instance, the value of the one copy changes from 36 to 50 and all
three instances point to the new value. But, when setFieldB(25) is called
on the first instance, the value for Field B changes from 0 to 25 for the first
instance only because each instance has its own copy of Field B.
See Understanding Instance and Class Members lesson in The Java
tutorial for a thorough discussion of this topic.
4 of 6
21-04-2000 17:30
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/prog.html
Constructors
Classes have a special method called a constructor that is called when a
class instance is created. The class constructor always has the same
name as the class and no return type. The LessonTwoD program converts
the LessonTwoB program to use a constructor to initialize the text string.
Note: If you do not write your own constructor, the compiler adds
an empty constructor, which calls the no-arguments constructor
of its parent class. The empty constructor is called the default
constructor. The default constructor initializes all non-initialized
fields and variables to zero.
class LessonTwoD {
String text;
//Constructor
LessonTwoD(){
text = "I'm a Simple Program";
}
//Accessor method
String getText(){
return text;
}
public static void main(String[] args){
LessonTwoD progInst = new LessonTwoD();
String retrievedText = progInst.getText();
System.out.println(retrievedText);
}
}
To Summarize
A simple program that prints a short text string to the console would
probably do everything in the main method and do away with the
constructor, text field, and getText method. But, this lesson used a
very simple program to show you the structure and elements in a basic
Java program.
More Information
See Understanding Instance and Class Members lesson in The Java
tutorial for a thorough discussion of this topic.
_______
1
As used on this web site, the terms "Java virtual machine" or "JVM"
mean a virtual machine for the Java platform.
[TOP]
5 of 6
21-04-2000 17:30
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/prog.html
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
6 of 6
21-04-2000 17:30
http://developer.java.sun.com/developer...ning/Programming/BasicJava1/applet.html
Training Index
Application to Applet
The following code is the applet equivalent to the LessonTwoB application
from Lesson 2. The figure below shows how the running applet looks. The
structure and elements of the applet code are discussed after the section
on how to run the applet just below.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
public class SimpleApplet extends Applet{
String text = "I'm a simple applet";
public void init() {
text = "I'm a simple applet";
setBackground(Color.cyan);
1 of 5
21-04-2000 17:30
http://developer.java.sun.com/developer...ning/Programming/BasicJava1/applet.html
}
public void start() {
System.out.println("starting...");
}
public void stop() {
System.out.println("stopping...");
}
public void destroy() {
System.out.println("preparing to unload...");
}
public void paint(Graphics g){
System.out.println("Paint");
g.setColor(Color.blue);
g.drawRect(0, 0,
getSize().width -1,
getSize().height -1);
g.setColor(Color.red);
g.drawString(text, 15, 25);
}
}
2 of 5
21-04-2000 17:30
http://developer.java.sun.com/developer...ning/Programming/BasicJava1/applet.html
methods. To create an applet, you extend (or subclass) the Applet class
and implement the appearance and behavior you want.
The applet's appearance is created by drawing onto the Panel or by
attaching other GUI components such as push buttons, scrollbars, or text
areas to the Panel. The applet's behavior is defined by implementing the
methods.
Extending a Class
Most classes of any complexity extend other classes. To
extend another class means to write a new class that can use
the fields and methods defined in the class being extended. The
class being extended is the parent class, and the class doing
the extending is the child class. Another way to say this is the
child class inherits the fields and methods of its parent or chain
of parents. Child classes either call or override inherited
methods. This is called single inheritance.
The SimpleApplet class extends Applet class, which
extends the Panel class, which extends the Container
class. The Container class extends Object, which is the
parent of all Java API classes.
The Applet class provides the init, start, stop, destroy, and
paint methods you saw in the example applet. The SimpleApplet
class overrides these methods to do what the SimpleApplet class
needs them to do. The Applet class provides no functionality for these
methods.
However, the Applet class does provide functionality for the
setBackground method,which is called in the init method. The call to
setBackground is an example of calling a method inherited from a
parent class in contrast to overriding a method inherited from a parent
class.
You might wonder why the Java language provides methods without
implementations. It is to provide conventions for everyone to use for
consistency across Java APIs. If everyone wrote their own method to start
an applet, for example, but gave it a different name such as begin or go,
the applet code would not be interoperable with other programs and
browsers, or portable across multiple platforms. For example, Netscape
and Internet Explorer know how to look for the init and start methods.
Behavior
An applet is controlled by the software that runs it. Usually, the underlying
software is a browser, but it can also be appletviewer as you saw in
the example. The underlying software controls the applet by calling the
methods the applet inherits from the Applet class.
The init Method: The init method is called when the applet is first
3 of 5
21-04-2000 17:30
http://developer.java.sun.com/developer...ning/Programming/BasicJava1/applet.html
4 of 5
21-04-2000 17:30
http://developer.java.sun.com/developer...ning/Programming/BasicJava1/applet.html
Packages
The applet code also has three import statements at the top.
Applications of any size and all applets use import statements to access
ready-made Java API classes in packages. This is true whether the Java
API classes come in the Java platform download, from a third-party, or are
classes you write yourself and store in a directory separate from the
program. At compile time, a program uses import statements to locate
and reference compiled Java API classes stored in packages elsewhere
on the local or networked system. A compiled class in one package can
have the same name as a compiled class in another package. The
package name differentiates the two classes.
The examples in Lessons 1 and 2 did not need a package declaration to
call the System.out.println Java API class because the System
class is in the java.lang package that is included by default. You never
need an import java.lang.* statement to use the compiled classes in
that package.
More Information
You can find more information on applets in the Writing Applets trail in The
Java Tutorial.
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
5 of 5
21-04-2000 17:30
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/front.html
Training Index
In the last lesson you saw how the Applet class provides a Panel
component so you can design the applet's user interface. This lesson
expands the basic application from Lessons 1 and 2 to give it a user
interface using the Java TM Foundation Classes (JFC) Project Swing APIs
that handle user events.
Project Swing APIs
Import Statements
Class Declaration
Instance Variables
Constructor
Action Listening
Event Handling
Main Method
Applets Revisited
More Information
1 of 7
21-04-2000 17:31
When Application
Starts
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/front.html
Import Statements
Here is the SwingUI.java code. At the top, you have four lines of import
statements. The lines indicate exactly which Java TM API classes the
program uses. You could replace four of these lines with this one line:
import java.awt.*;, to import the entire awt package, but doing that
increases compilation overhead than importing exactly the classes you
need and no others.
import
import
import
import
java.awt.Color;
java.awt.BorderLayout;
java.awt.event.*;
javax.swing.*;
Class Declaration
The class declaration comes next and indicates the top-level frame for the
application's user interface is a JFrame that implements the
ActionListener interface.
class SwingUI extends JFrame
implements ActionListener{
The JFrame class extends the Frame class that is part of the Abstract
Window Toolkit (AWT) APIs. Project Swing extends the AWT with a full
set of GUI components and services, pluggable look and feel capabilities,
and assistive technology support. For a more detailed introduction to
Project Swing, see the Swing Connection, and Fundamentals of Swing,
Part 1.
The Java APIs provide classes and interfaces for you to use. An interface
defines a set of methods, but does not implement them. The rest of the
SwingUI class declaration indicates that this class will implement the
ActionListener interface. This means the SwingUI class must
implement all methods defined in the ActionListener interface.
Fortunately, there is only one, actionPerformed, which is discussed
below.
Instance Variables
These next lines declare the Project Swing component classes the
SwingUI class uses. These are instance variables that can be accessed
by any method in the instantiated class. In this example, they are built in
the SwingUI constructor and accessed in the actionPerformed
method implementation. The private boolean instance variable is
2 of 7
21-04-2000 17:31
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/front.html
Constructor
The constructor (shown below) creates the user interface components and
JPanel object, adds the components to the JPanel object, adds the
panel to the frame, and makes the JButton components event listeners.
The JFrame object is created in the main method when the program
starts.
SwingUI(){
text = new JLabel("I'm a Simple Program");
clicked = new JLabel("Button Clicked");
button = new JButton("Click Me");
//Add button as an event listener
button.addActionListener(this);
clickButton = new JButton("Click Again");
//Add button as an event listener
clickButton.addActionListener(this);
//Create panel
panel = new JPanel();
//Specify layout manager and background color
panel.setLayout(new BorderLayout(1,1));
panel.setBackground(Color.white);
//Add label and button to panel
getContentPane().add(panel);
panel.add(BorderLayout.CENTER, text);
panel.add(BorderLayout.SOUTH, button);
}
3 of 7
21-04-2000 17:31
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/front.html
To find out about some of the other available layout managers and how to
use them, see the JDC article Exploring the AWT Layout Managers.
The call to the getContentPane method of the JFrame class is for
adding the Panel to the JFrame. Components are not added directly to a
JFrame, but to its content pane. Because the layout manager controls the
layout of components, it is set on the content pane where the components
reside. A content pane provides functionality that allows different types of
components to work together in Project Swing.
Action Listening
In addition to implementing the ActionListener interface, you have to
add the event listener to the JButton components. An action listener is the
SwingUI object because it implements the ActionListener interface. In this
example, when the end user clicks the button, the underlying Java platform
services pass the action (or event) to the actionPerformed method. In your
code, you implement the actionPerformed method to take the appropriate
action based on which button is clicked..
The component classes have the appropriate add methods to add action
listeners to them. In the code the JButton class has an addActionListener
method. The parameter passed to addActionListener is this, which means
the SwingUI action listener is added to the button so button-generated
actions are passed to the actionPerformed method in the SwingUI object.
button = new JButton("Click Me");
//Add button as an event listener
button.addActionListener(this);
Event Handling
The actionPerformed method is passed an event object that represents the
action event that occurred. Next, it uses an if statement to find out which
component had the event, and takes action according to its findings.
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if (_clickMeMode) {
text.setText("Button Clicked");
button.setText("Click Again");
_clickMeMode = false;
} else {
text.setText("I'm a Simple Program");
button.setText("Click Me");
_clickMeMode = true;
}
}
You can find information on event handling for the different components in
4 of 7
21-04-2000 17:31
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/front.html
Main Method
The main method creates the top-level frame, sets the title, and includes
code that lets the end user close the window using the frame menu.
public static void main(String[] args){
//Create top-level frame
SwingUI frame = new SwingUI();
frame.setTitle("Example");
//This code lets you close the window
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
frame.addWindowListener(l);
//This code lets you see the frame
frame.pack();
frame.setVisible(true);
}
}
The code for closing the window shows an easy way to add event handling
functionality to a program. If the event listener interface you need provides
more functionality than the program actually uses, use an adapter class.
The Java APIs provide adapter classes for all listener interfaces with more
than one method. This way, you can use the adapter class instead of the
listener interface and implement only the methods you need. In the
example, the WindowListener interface has 7 methods and this program
needs only the windowClosing method so it makes sense to use the
WindowAdapter class instead.
This code extends the WindowAdapter class and overrides the
windowClosing method. The new keyword creates an anonymous instance
of the extended inner class. It is anonymous because you are not assigning
a name to the class and you cannot create another instance of the class
without executing the code again. It is an inner class because the extended
class definition is nested within the SwingUI class.
This approach takes only a few lines of code, while implementing the
WindowListener interface would require 6 empty method implementations.
Be sure to add the WindowAdapter object to the frame object so the
frame object will listen for window events.
WindowListener l = new WindowAdapter() {
//The instantiation of object l is extended to
//include this code:
public void windowClosing(WindowEvent e){
System.exit(0);
}
};
frame.addWindowListener(l);
Applets Revisited
5 of 7
21-04-2000 17:31
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/front.html
Using what you learned in Lesson 3: Building Applets and this lesson,
convert the example for this lesson into an applet. Give it a try before
looking at the solution.
In short, the differences between the applet and application versions are
the following:
The applet class is declared public so appletviewer can access
it.
The applet class descends from Applet and the application class
descends from JFrame.
The applet version has no main method.
The application constructor is replaced in the applet by start and
init methods.
GUI components are added directly to the Applet; whereas, in the
case of an application, GUI components are added to the content
pane of its JFrame object.
More Information
For more information on Project Swing, see the Swing Connection, and
Fundamentals of Swing, Part 1.
Also see The JFC Project Swing Tutorial: A Guide to Constructing GUIs.
To find out about some of the other available layout managers and how to
use them, see the JDC article Exploring the AWT Layout Managers.
[TOP]
6 of 7
21-04-2000 17:31
http://developer.java.sun.com/developer...ining/Programming/BasicJava1/front.html
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
7 of 7
21-04-2000 17:31
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/servlet.html
Training Index
HTML Form
1 of 5
21-04-2000 17:31
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/servlet.html
The HTML form is embedded in this HTML file. The diagram shows how
the HTML page looks when it is opened in a browser.
The HTML file and form are similar to
the simple application and applet
examples in Lesson 4 so you can
compare the code and learn how
servlets, applets, and applications
handle end user inputs.
When the user clicks the Click Me
button, the servlet gets the entered text,
and returns an HTML page with the text.
The HTML page returned to the browser by the ExampServlet.java servlet
is shown below. The servlet code to retrieve the user's input and generate
the HTML page follows with a discussion.
Note: To run the example, you have to put the servlet and HTML
files in the correct directories for the Web server you are using.
For example, with Java WebServer 1.1.1, you place the servlet in
the ~/JavaWebServer1.1.1/servlets and the HTML file in
the ~/JavaWebServer1.1.1/public_html directory.
Servlet Backend
ExampServlet.java builds an HTML page to return to the end user. This
means the servlet code does not use any Project Swing or Abstract
Window Toolkit (AWT) components or have event handling code. For this
simple servlet, you only need to import these packages:
java.io for system input and output. The HttpServlet class uses
the IOException class in this package to signal that an input or
output exception of some kind has occurred.
javax.servlet, which contains generic (protocol-independent)
servlet classes. The HttpServlet class uses the
ServletException class in this package to indicate a servlet
problem.
javax.servlet.http, which contains HTTP servlet classes. The
HttpServlet class is in this package.
import java.io.*;
import javax.servlet.*;
2 of 5
21-04-2000 17:31
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/servlet.html
import javax.servlet.http.*;
public class ExampServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>Example</title>" +
"<body bgcolor=FFFFFF>");
out.println("<h2>Button Clicked</h2>");
String DATA = request.getParameter("DATA");
if(DATA != null){
out.println(DATA);
} else {
out.println("No text entered.");
}
out.println("<P>Return to
<A HREF="../simpleHTML.html">Form</A>");
out.close();
}
}
3 of 5
21-04-2000 17:31
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/servlet.html
In short, POST requests are for sending any amount of data directly over
the connection without changing the URL, and GET requests are for getting
limited amounts of information appended to the URL. POST requests
cannot be bookmarked or emailed and do not change the Uniform
Resource Locators (URL) of the response. GET requests can be
bookmarked and emailed and add information to the URL of the response.
The parameter list for the doPost method takes a request and a
response object. The browser sends a request to the servlet and the
servlet sends a response back to the browser.
The doPost method implementation accesses information in the request
object to find out who made the request, what form the request data is in,
and which HTTP headers were sent, and uses the response object to
create an HTML page in response to the browser's request. The doPost
method throws an IOException if there is an input or output problem
when it handles the request, and a ServletException if the request
could not be handled. These exceptions are handled in the HttpServlet
class.
Method Implementation
The first part of the doPost method uses the response object to create
an HTML page. It first sets the response content type to be text/html,
then gets a PrintWriter object for formatted text output.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>Example</title>" +
"<body bgcolor=#FFFFFF>");
out.println("<h2>Button Clicked</h2>");
The next line uses the request object to get the data from the text field
on the form and store it in the DATA variable. The getparameter method
gets the named parameter, returns null if the parameter was not set,
and an empty string if the parameter was sent without a value.
String DATA = request.getParameter("DATA");
The next part of the doPost method gets the data out of the DATA
parameter and passes it to the response object to add to the HTML
response page.
if(DATA != null){
out.println(DATA);
} else {
out.println("No text entered.");
}
The last part of the doPost method creates a link to take the end user
from the HTML response page back to the original form, and closes the
response.
4 of 5
21-04-2000 17:31
http://developer.java.sun.com/developer...ing/Programming/BasicJava1/servlet.html
out.println("<P>Return to
<A HREF="../simpleHTML.html">Form</A>");
out.close();
}
More Information
You can find more information on servlets in the Servlets trail in The Java
Tutorial.
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
5 of 5
21-04-2000 17:31
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
Training Index
So far, you have learned how to retrieve and handle a short text string
entered from the keyboard into a simple graphical user interface (GUI).
But programs also retrieve, handle, and store data in files and databases.
This lesson expands the examples from previous lessons to perform basic
file access using the application programming interfaces (APIs) in the
java.io package. It also shows you how to grant applets permission to
access specific files, and how to restrict an application so it has access to
specific files only.
File Access by Applications
System Properties
File.separatorChar
Exception Handling
File Access by Applets
Granting Applets Permission
Restricting Applications
File Access by Servlets
Appending
More Informattion
1 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
Note: You can learn more about component sizing in The Java
Tutorial sections on Solving Common Layout Problems and
Layout Management.
//Instance variable for text field
JTextField textField;
FileIO(){
text = new JLabel("Text to save to file:");
clicked = new
JLabel("Text retrieved from file:");
button = new JButton("Click Me");
button.addActionListener(this);
2 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
Method Changes
The actionPerformed method uses the FileInputStream and
FileOutputStream classes to read data from and write data to a file.
These classes handle data in byte streams, as opposed to character
streams, which are shown in the applet example. A more detailed
explanation of the changes to the method implementation follows the code.
public void actionPerformed(
ActionEvent event){
Object source = event.getSource();
if(source == button){
//Variable to display text read from file
String s = null;
if(_clickMeMode){
try{
//Code to write to file
String text = textField.getText();
byte b[] = text.getBytes();
String outputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File outputFile = new File(outputFileName);
FileOutputStream out = new
FileOutputStream(outputFile);
out.write(b);
out.close();
//Code to read from file
String inputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File inputFile = new File(inputFileName);
FileInputStream in = new
FileInputStream(inputFile);
byte bt[] = new
byte[(int)inputFile.length()];
3 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
in.read(bt);
s = new String(bt);
in.close();
}catch(java.io.IOException e){
System.out.println("Cannot access text.txt");
}
//Clear text field
textField.setText("");
//Display text read from file
text.setText("Text retrieved from file:");
textField.setText(s);
button.setText("Click Again");
_clickMeMode = false;
} else {
//Save text to file
text.setText("Text to save to file:");
textField.setText("");
button.setText("Click Me");
_clickMeMode = true;
}
}
}
To write the end user text to a file, the text is retrieved from the
textField and converted to a byte array.
String text = textField.getText();
byte b[] = text.getBytes();
Next, a File object is created for the file to be written to and used to
create a FileOutputStream object.
String outputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File outputFile = new File(outputFileName);
FileOutputStream out = new
FileOutputStream(outputFile);
Finally, the FileOutputStream object writes the byte array to the File
object and closes the output stream when the operation completes.
out.write(b);
out.close();
The code to open a file for reading is similar. To read text from a file, a
File object is created and used to create a FileInputStream object.
String inputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File inputFile = new File(inputFileName);
FileInputStream out = new
FileInputStream(inputFile);
4 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
Next, a byte array is created the same size as the file into which the file
contents are read.
byte bt[] = new byte[(int)inputFile.length()];
in.read(bt);
Finally, the byte array is used to construct a String object, which is used
to create the text for the label component. The FileInputStream is
closed when the operation completes.
String s = new String(bt);
label.setText(s);
in.close();
System Properties
The above code used a call to System.getProperty to create the
pathname to the file in the user's home directory. The System class
maintains a set of properties that define attributes of the current working
environment. When the Java platform starts, system properties are
initialized with information about the runtime environment including the
current user, Java platform version, and the character used to separate
components of a file name (File.separatorChar).
The call to System.getProperty uses the keyword user.home to get
the user's home directory and supplies the default value
File.separatorChar + "home" + File.separatorChar +
"monicap") in case no value is found for this key.
File.separatorChar
The above code used the java.io.File.separatorChar variable to
construct the directory pathname. This variable is initialized to contain the
file separator value stored in the file.separator system property and
gives you a way to construct platform-independent pathnames.
For example, the pathname /home/monicap/text.txt for Unix and
\home\monicap\text.txt for Windows are both represented as
File.separatorChar + "home" + File.separatorChar +
"monicap" + File.separatorChar + "text.txt" in a
platform-independent construction.
Exception Handling
An exception is a class that descends from either
java.lang.Exception or java.lang.RuntimeException that
defines mild error conditions your program might encounter. Rather than
letting the program terminate, you can write code to handle exceptions and
continue program execution.
5 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
Note: You can find more information on this topic in The Java
Tutorial trail on Handling Errors with Exceptions.
When you catch exceptions in your code, you should handle them in a way
that is friendly to your end users. The exception and error classes have a
toString method to print system error text and a printStackTrace
method to print a stack trace, which can be very useful for debugging your
application during development. But, it is probably better to deploy the
program with a more user-friendly approach to handling errors.
You can provide your own application-specific error text to print to the
command line, or display a dialog box with application-specific error text.
Using application-specific error text that you provide will also make it much
easier to internationalize the application later on because you will have
access to the text.
6 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
For the example programs in this lesson, the error message for the file
input and output is handled with application-specific error text that prints at
the command line as follows:
//Do this during development
}catch(java.io.IOException e){
System.out.println(e.toString());
System.out.println(e.printStackTrace());
}
//But deploy it like this
}catch(java.io.IOException e){
System.out.println("Cannot access text.txt");
}
If you want to make your code even more user friendly, you could
separate the write and read operations and provide two try and catch
blocks. The error text for the read operation could be Cannot read text.txt,
and the error text for the write operation could be Cannot write text.txt.
As an exercise, change the code to handle the read and write operations
separately. Give it a try before peeking at the solution.
7 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File outputFile = new File(outputFileName);
FileWriter out = new
FileWriter(outputFile);
out.write(text);
out.close();
//Code to read from file
String inputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File inputFile = new File(inputFileName);
FileReader in = new FileReader(inputFile);
char c[] = new
char[(char)inputFile.length()];
in.read(c);
s = new String(c);
in.close();
}catch(java.io.IOException e){
System.out.println("Cannot access text.txt");
}
//Clear text field
textField.setText("");
//Display text read from file
text.setText("Text retrieved from file:");
textField.setText(s);
button.setText("Click Again");
_clickMeMode = false;
} else {
//Save text to file
text.setText("Text to save to file:");
textField.setText("");
button.setText("Click Me");
_clickMeMode = true;
}
}
}
8 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
Java Tutorial trail on Controlling Applets explains how to use Policy Tool in
good detail. Here is the policy file you need to run the applet. You can use
Policy tool to create it or copy the text below into an ASCII file.
grant {
permission java.util.PropertyPermission
"user.home", "read";
permission java.io.FilePermission
"${user.home}/text.txt", "read,write";
};
Restricting Applications
You can use the default security manager and a policy file to restrict the
application's access as follows.
java -Djava.security.manager
-Djava.security.policy=apppolfile
FileIO
Because the application runs within the security manager, which disallows
all access, the policy file needs two additional permissions. One so the
security manager can access the event queue and load the user interface
components, and another so the application does not display the banner
warning that its window was created by another program (the security
manager).
grant {
permission java.awt.AWTPermission
"accessEventQueue";
permission java.awt.AWTPermission
9 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
"showWindowWithoutWarningBanner";
permission java.util.PropertyPermission
"user.home", "read";
permission java.io.FilePermission
"${user.home}/text.txt", "read,write";
};
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileIOServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>Example<title>" +
"<body bgcolor=FFFFFF>");
out.println("<h2>Button Clicked</h2>");
String DATA = request.getParameter("DATA");
if(DATA != null){
out.println("<STRONG>Text from
form:</STRONG>");
out.println(DATA);
} else {
out.println("No text entered.");
10 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
}
try{
//Code to write to file
String outputFileName=
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File outputFile = new File(outputFileName);
FileWriter fout = new FileWriter(outputFile);
fout.write(DATA);
fout.close();
//Code to read from file
String inputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File inputFile = new File(inputFileName);
FileReader fin = new
FileReader(inputFile);
char c[] = new
char[(char)inputFile.length()];
int i;
i = fin.read(c);
String s = new String(c);
out.println("<P>
<STRONG>Text from file:</STRONG>");
out.println(s);
fin.close();
}catch(java.io.IOException e){
System.out.println("Cannot access text.txt");
}
out.println("<P>Return to
<A HREF="../simpleHTML.html">Form</A>");
out.close();
}
}
Appending
So far the examples have shown you how to read in and write out streams
of data in their entirety. But often, you want to append data to an existing
file or read in only certain amounts. Using the RandomAccessFile class,
alter the FileIO.java class to append to the file.
Give it a try before taking a peek at the Solution.
More Information
For more infomation on file input and output, see the Reading and Writing
trail in The Java Tutorial.
You can learn more about component sizing in The Java Tutorial sections
on Solving Common Layout Problems and Layout Management.
11 of 12
21-04-2000 17:32
http://developer.java.sun.com/developer...aining/Programming/BasicJava1/data.html
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
12 of 12
21-04-2000 17:32
Training Index
This lesson converts the application, applet, and servlet examples from
Lesson 6 to write to and read from a database using JDBCTM. JDBC is the
JavaTM database connectivity application programming interface (API)
available in the Java 2 Platform software.
The code for this lesson is very similar to the code you saw in Lesson 6,
but additional steps (beyond converting the file access code to database
access code) include setting up the environment, creating a database
table, and connecting to the database. Creating a database table is a
database administration task that is not part of your program code.
However, establishing a database connection and the resulting database
access are.
As in Lesson 6, the applet needs appropriate permissions to connect to
the database. Which permissions it needs varies with the type of driver
used to make the database connection.
Database Setup
Create Database Table
Database Access by Applications
Establishing a Connection
Final and Private Variables
Writing and Reading Data
Database Access by Applets
JDBC Driver
JDBC-ODBC Bridge with ODBC Driver
Database Access by Servlets
More Information
Database Setup
You need access to a database if you want to run the examples in this
lesson. You can install a database on your machine or perhaps you have
access to a database at work. Either way, you need a database driver
and any relevant environment settings so your program can load the driver
and locate the database. The program will also need database login
information in the form of a user name and password.
A database driver is software that lets a program establish a connection
1 of 11
21-04-2000 17:32
with a database. If you do not have the right driver for the database to
which you want to connect, your program will be unable to establish the
connection.
Drivers either come with the database or are available from the Web. If
you install your own database, consult the documentation for the driver for
information on installation and any other environment settings you need for
your platform. If you are using a database at work, consult your database
administrator for this information.
To show you two ways to do it, the application example uses the jdbc
driver, the applet examples use the jdbc and jdbc.odbc drivers, and the
servlet example uses the jdbc.odbc driver. All examples connect to an
OracleOCI7.3.4 database.
Connections to other databases will involve similar steps and code. Be
sure to consult your documentation or system administrator if you need
help connecting to the database.
2 of 11
21-04-2000 17:32
3 of 11
21-04-2000 17:32
SQL commands are String objects, and therefore, follow the rules of
String construction where the string is enclosed in double quotes (" ")
and variable data is appended with a plus (+). The variable theText is a
text variable. Single quotes are prepended and appended to comply with
SQL syntax.
4 of 11
21-04-2000 17:32
5 of 11
21-04-2000 17:32
Locating the Database Driver: Assuming the driver is not available to the
DriverManager for some reason, the following error generates when
you click the Click Me button.
cannot find driver
This error means the DriverManager looked for the JDBC driver in the
directory where the applet HTML and class files are and could not find it.
To correct this error, copy the driver to the directory where the applet files
are, and if the driver is bundled in a zip file, unzip the zip file so the applet
can access the driver.
Once you have the driver in place, launch the applet again.
appletviewer DbaAppl.html
The first line in the above stack trace tells you access is denied. This
means this stack trace was generated because the applet tried to access
a system resource without the proper permission. The second line means
to correct this condition you need a SocketPermission that gives the
applet access to the machine (developer) where the database is
located.
You can use Policy tool to create the policy file you need, or you can
create it with an ASCII editor. Here is the policy file with the permission
indicated by the stack trace:
6 of 11
21-04-2000 17:32
grant {
permission java.net.SocketPermission "developer",
"resolve";
"accessClassInPackage.sun.jdbc.odbc";
};
Run the applet again, this time with a policy file named DbaApplPol that
has the above permission in it:
appletviewer -J-Djava.security.policy=DbaApplPol
DbaAppl.html
You get a stack trace again, but this time it is a different error condition.
java.security.AccessControlException: access denied
(java.net.SocketPermission
129.144.176.176:1521 connect,resolve)
Run the applet again. If you use the above policy file with the Socket
permissions indicated, it works just fine.
appletviewer -J-Djava.security.policy=DbaApplPol
DbaAppl.html
7 of 11
21-04-2000 17:32
Start the Applet: Here is the DbaOdb.html file for running the
DbaOdbAppl applet:
<HTML>
<BODY>
<APPLET CODE=DbaOdbAppl.class
WIDTH=200
HEIGHT=100>
</APPLET>
</BODY>
</HTML>
The first line in the above stack trace tells you access is denied. This
means this stack trace was generated because the applet tried to access
a system resource without the proper permission. The second line means
you need a RuntimePermission that gives the applet access to the
sun.jdbc.odbc package. This package provides the JDBC-ODBC
bridge functionality to the Java 1 virtual machine (VM).
You can use Policy tool to create the policy file you need, or you can
create it with an ASCII editor. Here is the policy file with the permission
indicated by the stack trace:
grant {
permission java.lang.RuntimePermission
"accessClassInPackage.sun.jdbc.odbc";
};
Run the applet again, this time with a policy file named DbaOdbPol that
has the above permission in it:
appletviewer -J-Djava.security.policy=DbaOdbPol
DbaOdb.html
You get a stack trace again, but this time it is a different error condition.
java.security.AccessControlException:
access denied (java.lang.RuntimePermission
file.encoding read)
The stack trace means the applet needs read permission to the encoded
8 of 11
21-04-2000 17:32
(binary) file. Here is the DbaOdbPol policy file with the permission
indicated by the stack trace added to it:
grant {
permission java.lang.RuntimePermission
"accessClassInPackage.sun.jdbc.odbc";
permission java.util.PropertyPermission
"file.encoding", "read";
};
Run the applet again. If you use the above policy file with the Runtime and
Property permissions indicated, it works just fine.
appletviewer -J-Djava.security.policy=DbaOdbPol
DbaOdb.html
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;
import java.io.*;
public class DbaServlet extends HttpServlet {
private Connection c;
9 of 11
21-04-2000 17:32
10 of 11
21-04-2000 17:32
out.close();
}
}
More Information
You can find more information on variable access settings in the Objects
and Classes trail in The Java Tutorial
_______
1 As used on this web site, the terms "Java virtual machine" or "JVM"
mean a virtual machine for the Java platform.
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
11 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
Training Index
1 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
This lesson converts the File Input and Output application from Lesson 6:
File Access and Permissions to the RMI API.
Program Behavior
The RMIClient1 program presents a simple user interface and prompts for
text input. When you click the Click Me button, the text is sent to the
RMIClient2 program by way of the remote server object. When you click
the Click Me button on the RMIClient2 program, the text sent from
RMIClient1 appears.
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
The first two javac commands compile the RemoteServer and Send
class and interface. The third javac command compiles the RMIClient2
class. The last javac command compiles the RMIClient1 class.
The next line runs the rmic command on the RemoteServer server
3 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
4 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
Java VM, which will create problems when clients try to download the
remote server classes.
The following commands unset the CLASSPATH and start the RMI Registry
on the default 1099 port. You can specify a different port by adding the
port number as follows: rmiregistry 4444 &. If you specify a different
port number, you must specify the same port number in your server-side
code as well.
Unix:
cd /home/zelda/public_html/classes
unsetenv CLASSPATH
rmiregistry &
Win32:
cd \home\zelda\public_html\classes
set CLASSPATH=
start rmiregistry
Note: You might want to set the CLASSPATH back to its original
setting at this point.
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
6 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
The lines beginning at java should be all on one line with spaces where
the lines break. The properties specified with the -D option to the java
interpreter command are program attributes that manage the behavior of
the program for this invocation.
Unix:
cd /home/zelda/classes
java -Djava.rmi.server.codebase=
http://kq6py/~zelda/classes
-Djava.security.policy=java.policy
RMIClient2 kq6py.eng.sun.com
Win32:
cd \home\zelda\classes
java -Djava.rmi.server.codebase=
file:c:\home\zelda\public_html\classes
-Djava.security.policy=java.policy
RMIClient2 kq6py.eng.sun.com
RemoteServer Class
The RemoteServer class extends UnicastRemoteObject and
implements the sendData and getData methods declared in the Send
interface. These are the remotely accessible methods.
UnicastRemoteObject implements a number of java.lang.Object
methods for remote objects and includes constructors and static methods
to make a remote object available to receive method calls from client
programs.
class RemoteServer extends UnicastRemoteObject
implements Send {
String text;
public RemoteServer() throws RemoteException {
super();
}
public void sendData(String gotText){
text = gotText;
}
public String getData(){
7 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
return text;
}
Send Interface
The Send interface declares the methods implemented in the
RemoteServer class. These are the remotely accessible methods.
public interface Send extends Remote {
public void sendData(String text)
throws RemoteException;
8 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
RMIClient1 Class
The RMIClient1 class establishes a connection to the remote server
program and sends data to the remote server object. The code to do
these things is in the actionPerformed and main methods.
actionPerformed Method
The actionPerformed method calls the RemoteServer.sendData
method to send text to the remote server object.
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if(source == button){
//Send data over socket
String text = textField.getText();
try{
send.sendData(text);
} catch (java.rmi.RemoteException e) {
System.out.println("Cannot send data to server");
}
textField.setText(new String(""));
}
}
main Method
The main method installs the RMISecurityManager and creates a
name to use to look up the RemoteServer server object. The client uses
the Naming.lookup method to look up the RemoteServer object in the
RMI Registry running on the server.
The security manager determines whether there is a policy file that lets
downloaded code perform tasks that require permissions.
RMIClient1 frame = new RMIClient1();
if(System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
//args[0] contains name of server where Send runs
String name = "//" + args[0] + "/Send";
send = ((Send) Naming.lookup(name));
} catch (java.rmi.NotBoundException e) {
System.out.println("Cannot look up
remote server object");
} catch(java.rmi.RemoteException e){
System.out.println("Cannot look up
remote server object");
} catch(java.net.MalformedURLException e) {
System.out.println("Cannot look up
9 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
RMIClient2 Class
The RMIClient2 class establishes a connection with the remote server
program and gets the data from the remote server object and displays it.
The code to do this is in the actionPerformed and main methods.
actionPerformed Method
The actionPerformed method calls the RemoteServer.getData
method to retrieve the data sent by the client program. This data is
appended to the TextArea object for display to the end user on the
server side.
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == button){
try{
String text = send.getData();
textArea.append(text);
} catch (java.rmi.RemoteException e) {
System.out.println("Cannot send data
to server");
}
}
}
}
main Method
The main method installs the RMISecurityManager and creates a
name to use to look up the RemoteServer server object. The args[0]
parameter provides the name of the server host. The client uses the
Naming.lookup method to look up the RemoteServer object in the
RMI Registry running on the server.
The security manager determines whether there is a policy file that lets
downloaded code perform tasks that require permissions.
RMIClient2 frame = new RMIClient2();
if(System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
String name = "//" + args[0] + "/Send";
send = ((Send) Naming.lookup(name));
} catch (java.rmi.NotBoundException e) {
System.out.println("Cannot look up remote
server object");
} catch(java.rmi.RemoteException e){
System.out.println("Cannot look up remote
server object");
10 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...raining/Programming/BasicJava1/rmi.html
} catch(java.net.MalformedURLException e) {
System.out.println("Cannot look up remote
server object");
}
More Information
You can find more information on the RMI API in the RMI trail of The Java
Tutorial.
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
11 of 11
21-04-2000 17:32
http://developer.java.sun.com/developer...ining/Programming/BasicJava2/index.html
Contents
Lesson 1: Socket Communications
What are Sockets and Threads?
About the Examples
Example 1: Server-Side Program
Example 1: Client-Side Program
Example 2: Multithreaded Server Example
More Information
Lesson 2: User Interfaces Revisited
About the Example
Fruit Order Client Code
Global Variables
Constructor
Event Handling
Cursor Focus
Converting Strings to Numbers and Back
Server Program Code
View Order Client Code
Program Improvements
More Information
Lesson 3: Cryptography
About the Example
1 of 3
21-04-2000 17:33
http://developer.java.sun.com/developer...ining/Programming/BasicJava2/index.html
2 of 3
21-04-2000 17:33
http://developer.java.sun.com/developer...ining/Programming/BasicJava2/index.html
Reader Feedback
Tell us what you think of this training book and earn two DukeDollars.
Very worth reading
Worth reading
If you have other comments or ideas for future training books, please
type them here:
Submit
Reset
[TOP
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
3 of 3
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/socket.html
1 of 8
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/socket.html
from a client, start a thread for that communication, and continue listening
for requests from other clients.
2 of 8
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/socket.html
java SocketClient
Lastly, the listenSocket method loops on the input stream to read data
as it comes in from the client and writes to the output stream to send the
3 of 8
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/socket.html
data back.
while(true){
try{
line = in.readLine();
//Send data back to client
out.println(line);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
actionPerformed Method
The actionPerformed method is called by the Java platform for action
events such as button clicks. This actionPerformed method uses the
text stored in the line object to initialize the textArea object so the
retrieved text can be displayed to the end user.
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == button){
textArea.setText(line);
}
}
4 of 8
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/socket.html
System.out.println("No I/O");
System.exit(1);
}
}
actionPerformed Method
The actionPerformed method is called by the Java platform for action
events such as button clicks. This actionPerformed method code gets
the text in the Textfield object and passes it to the PrintWriter
object, which then sends it over the socket connection to the server
program.
The actionPerformed method then makes the Textfield object blank
so it is ready for more end user input. Lastly, it receives the text sent back
to it by the server and prints the text out.
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if(source == button){
//Send data over socket
String text = textField.getText();
out.println(text);
textField.setText(new String(""));
out.println(text);
}
//Receive text from server
try{
String line = in.readLine();
System.out.println("Text received: " + line);
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
}
}
5 of 8
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/socket.html
First Client
Second Client
Third Client
The multithreaded server program creates a new thread for every client
request. This way each client has its own connection to the server for
passing data back and forth. When running multiple threads, you have to
be sure that one thread cannot interfere with the data in another thread.
In this example the listenSocket method loops on the
server.accept call waiting for client connections and creates an
instance of the ClientWorker class for each client connection it accepts.
The textArea component that displays the text received from the client
connection is passed to the ClientWorker instance with the accepted
client connection.
public void listenSocket(){
try{
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
ClientWorker w;
try{
//server.accept returns a client connection
w = new ClientWorker(server.accept(), textArea);
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
The important changes in this version of the server program over the
non-threaded server program are the line and client variables are no
longer instance variables of the server class, but are handled inside the
ClientWorker class.
6 of 8
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/socket.html
7 of 8
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/socket.html
More Information
You can find more information on sockets in the All About Sockets section
in The Java Tutorial.
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
8 of 8
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
1 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
2 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
Start RMIClient1:
Unix:
cd /home/zelda/classes
java -Djava.rmi.server.codebase=
http://kq6py/~zelda/classes/
-Djava.security.policy=java.policy RMIClient1
3 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
kq6py.eng.sun.com/~zelda
Win32:
cd \home\zeldzeldaa\classes
java -Djava.rmi.server.codebase=
file:c:\home\zelda\classes\
-Djava.security.policy=java.policy RMIClient1
kq6py.eng.sun.com\home\zelda\public\html
Start RMIClient2:
Unix:
cd /home/zelda/classes
java -Djava.rmi.server.codebase=
http://kq6py/~zelda/classes
-Djava.rmi.server.hostname=kq6py.eng.sun.com
-Djava.security.policy=java.policy RMIClient2
kq6py.eng.sun.com
Win32:
cd \home\zelda\classes
java -Djava.rmi.server.codebase=
file:c:\home\zelda\public_html\classes
-Djava.rmi.server.hostname=kq6py.eng.sun.com
-Djava.security.policy=java.policy RMIClient2
kq6py.eng.sun.com
4 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
by any method in the instantiated class. In this example, they are built in
the SwingUI constructor and accessed in the actionPerformed
method implementation.
JLabel
JLabel
JLabel
JLabel
col1, col2;
totalItems, totalCost;
cardNum, custID;
applechk, pearchk, peachchk;
Constructor
The constructor is fairly long because it creates all the components, sets
the layout to a 2-column grid, and places the components in the grid on a
panel. A panel is a container component that holds other components.
The Reset and Purchase buttons and the appleQnt, pearQnt, and
peachQnt text fields are added as action listeners. This means when the
end user clicks one of the buttons or presses Return in one of the text
fields, an action event occurs that causes the platform to call the
FruitClient.actionPerformed method where the behaviors for
these components are defined.
As explained in Part1, Lesson 4: Building a User Interface, a class
declares the ActionListener interface and implements the
actionPerformed method if it needs to handle action events such as
button clicks and text field Returns. Other user interface components
generate some different action events, and as a result, require you to
implement different interfaces and methods.
//Create left and right column labels
col1 = new JLabel("Select Items");
col2 = new JLabel("Specify Quantity");
//Create labels and text field components
applechk = new JLabel("
Apples");
appleqnt = new JTextField();
appleqnt.addActionListener(this);
pearchk = new JLabel("
Pears");
pearqnt = new JTextField();
pearqnt.addActionListener(this);
peachchk = new JLabel("
Peaches");
peachqnt = new JTextField();
peachqnt.addActionListener(this);
5 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
6 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
panel.add(pearqnt);
panel.add(totalItems);
panel.add(items);
panel.add(totalCost);
panel.add(cost);
panel.add(cardNum);
panel.add(creditCard);
panel.add(custID);
panel.add(customer);
panel.add(reset);
panel.add(purchase);
Event Handling
The actionPerformed method provides behavior for each of the
following possible application events:
The mouse is clicked on the Purchase or Reset button.
The Return key is pressed inside the appleQnt, peachQnt, or
pearQnt field.
Rather than show the entire actionPerformed method here, this section
describes the purchase button and pearQnt text field behaviors only.
The Reset button is similar to the purchase button, and the other text
fields are similar to pearQnt.
Purchase Button: The Purchase button behavior involves retrieving data
from the text fields and text areas, and sending that data to the server
program. The server program is available to the FruitClient program
through its Send interface, which declares the remote server methods for
sending and getting data.
The send variable is an instance of the Send interface. This instance is
created in the FruitClient program's main method. The send variable
is declared static and global in the FruitClient program so the
static main method can instantiate it, and to make it accessible to the
actionPerformed method.
if(source == purchase){
cardnum = creditCard.getText();
custID = customer.getText();
apples = appleqnt.getText();
peaches = peachqnt.getText();
pears = pearqnt.getText();
try{
send.sendCreditCard(cardnum);
send.sendCustID(custID);
send.sendAppleQnt(apples);
send.sendPeachQnt(peaches);
send.sendPearQnt(pears);
7 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
send.sendTotalCost(icost);
send.sendTotalItems(itotal);
} catch (Exception e) {
System.out.println("Cannot send data to server");
}
}
pearQnt Text Field: The pearQnt text field behavior involves retrieving
the number of pears the end user wants to order, adding the number to the
items total, using the number to calculate the cost, and adding the cost for
pears to the total cost. Two interesting things in this code involve managing
the cursor focus and converting strings to numbers for the calculations.
Both topics are covered below.
if(source == pearqnt){
number = pearqnt.getText();
if(number.length() > 0){
pearsNo = Integer.valueOf(number);
itotal += pearsNo.intValue();
pearqnt.setNextFocusableComponent(creditCard);
} else {
itotal += 0;
pearqnt.setNextFocusableComponent(creditCard);
}
}
Cursor Focus
End users can use the Tab key to move the cursor from one component to
another within the user interface. The default Tab key movement steps
through all user interface components including the text areas.
Because the end user does not interact with the text areas, there is no
reason for the cursor to go there. The example program includes a call in
its constructor to pearqnt.setNextFocusableComponent to make
the cursor move from the pearqnt text field to the creditcard text field
bypassing the total cost and total items text areas when the Tab key is
pressed.
applechk = new JLabel("
Apples");
appleqnt = new JTextField();
appleqnt.addActionListener(this);
pearchk = new JLabel("
Pears");
pearqnt = new JTextField();
pearqnt.addActionListener(this);
peachchk = new JLabel("
Peaches");
peachqnt = new JTextField();
peachqnt.addActionListener(this);
cardNum = new JLabel("
Credit Card:");
creditCard = new JTextField();
//Make cursor go to creditCard component
pearqnt.setNextFocusableComponent(creditCard);
customer = new JTextField();
custID = new JLabel("
Customer ID:");
8 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
To display the running item and cost totals in their respective text areas,
the totals have to be converted back to strings. The code at the end of the
actionPerformed method shown below does this.
To display the total items, a java.lang.Integer object is created from
the itotal integer variable. The Integer.toString method is called
to produce the String equivalent of the integer (int). This string is
passed to the call to this.cost.setText(text2) to update the Total
Cost field in the display.
9 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
Until now, all data types used in the examples have been classes. But, the
int and double data types are not classes. They are primitive data
types.
The int data type contains a single whole 32-bit integer value that can be
positive or negative. You can use the standard arithmetic operators (+, -,
*, and /) to perform arithmetic operations on the integer.
The Integer class, not only contains a whole 32-bit integer value that can
be positive or negative, but provides methods for working on the value. For
example, the Integer.intValue method lets you convert an Integer
to an int to perform arithmetic operations.
The double data type contains a 64-bit double-precision floating point
value. The Double class not only contains a 64-bit double-precision
floating point value, but provides methods for working on the value. for
example, the Double.doubleValue method lets you convert a Double
to a double to perform arithmetic operations.
10 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
Program Improvements
The example program as it is currently written has two major design flaws
11 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
in the fruit order client. The first one involves the need to press the Return
key for calculations to happen, and the second involves handling the error
condition if the end user enters a character that is not a number when
ordering apples, peaches, and pears.
Calculations and Pressing Return: If the end user enters a value for
apples, peaches, or pears and moves to the next field without pressing the
Return key, no calculation is made. This means when the end user clicks
the Purchase key, the order is sent, but the item and cost totals will be
incorrect. So, in this particular application relying on the Return key action
event is not good design.
Modify the actionPerformed method so this does not happen. Here is
one possible solution. Give it a try before taking a look.
Non-Number Errors: If the end user enters a non-number value for
apples, peaches, or pears the program will present a stack trace indicating
an illegal number format. A good program will catch and handle the error,
rather than produce a stack trace.
Hint: You need to figure out which part of the code throws the error and
enclose it in a try and catch block. try and catch blocks were first
introduced in Part 1, Lesson 6: File Access and Permissions. The error
you need to catch is java.lang.NumberFormatException.
Give it a try before taking a look at the solution.
More Information
You can find more information on event listening in the Writing Event
Listeners lesson in The Java Tutorial.
The Variables and Data Types trail in The Java Tutorial provides more
information on primitive data types.
See The JFC Swing Tutorial: A Guide to Constructing GUIs for more
information on Project Swing.
*As used on this web site, the terms "Java virtual machine" or "JVM"
mean a virtual machine for the Java platform.
[TOP]
12 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/ui.html
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
13 of 13
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/crypto.html
Many people are protective of their credit card numbers, and for good
reason. A stolen credit card number with other personal information can
give a thief all he or she needs to create serious mayhem in someone's
life. One way to keep credit card and other proprietary information secure
when sending it over the net is to encrypt it.
Encryption is the process of applying a key to plain text that transforms
that plain text into unintelligible (cipher) text. Only programs with the key to
turn the cipher text back to original text can decrypt the protected
information.
This lesson adapts the Part 2, Lesson 2: User Interfaces Revisited
example to encrypt the credit card number before sending it over the net,
and decrypt it on the other side.
1 of 7
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/crypto.html
2 of 7
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/crypto.html
Pseudo Code
A cipher object is used in the encryption and decryption process. The
cipher object is created with a specific cryptographic algorithm depending
on the type of encryption in use. In this example, two types of encryption
3 of 7
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/crypto.html
method
method
method
method
method
to
to
to
to
to
4 of 7
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/crypto.html
Sealing the symmetric key involves creating a sealed object that uses an
asymmetric cipher to seal (encrypt) the session key. The RSA asymmetric
algorithm cannot be used because it has the size restrictions described in
the next section, and the sealing process makes the session key too large
to use with the RSA algorithm.
RMIClient1Sealed.java: The RMIClient1.java code has an encrypt
method to encrypt the credit card number, seal the symmetric key, and
send the encrypted credit card number and sealed key to the server. Here
is the pseudo code to do it:
private void encrypt(credit card number){
Create cipher for symmetric key encryption (DES)
Create a key generator
Create a secret (session) key with key generator
Initialize cipher for encryption with session key
Encrypt credit card number with cipher
Get public key from server
Create cipher for asymmetric encryption
(do not use RSA)
Initialize cipher for encryption with public key
Seal session key using asymmetric Cipher
Send encrypted credit card number and sealed
session key to server
}
5 of 7
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/crypto.html
the class of the session key, the class signature, and any objects
referenced by the session key. The additional information makes the
session key too large to be encrypted with an RSA key, and the result is a
javax.crypto.IllegalBlockSizeException run time error.
RMIClient1.java: The RMIClient1.java code has an encrypt method to
encrypt the credit card number, seal (encrypt) the session key, and send
the encrypted credit card number and sealed session key to the server.
Here is the pseudo code to do it:
private void encrypt(credit card number){
Create cipher for symmetric key encryption (DES)
Create a key generator
Create a secret (session) key with key generator
Initialize cipher for encryption with session key
Encrypt credit card number with cipher
Get public key from server
Create cipher for asymmetric encryption (RSA)
Initialize cipher for encryption with public key
Encrypt session key
Send encrypted credit card number and session
key to server
}
More Information
You can find more information on key encryption on the Security Dynamics
Web site (for RSA encryption), or by using a search engine and searching
on RSA Cryptography, asymmetric key encryption, or symmetric key
encryption.
[TOP]
6 of 7
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/crypto.html
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
7 of 7
21-04-2000 17:33
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/serial.html
One big problem with the example program in its current form is the fact
that sending clients can overwrite each other's data before receiving clients
have a chance to get and process it. This lesson adapts the server code to
ensure all orders are processed (nothing is overwritten), and all orders are
processed in the order they are received by the server.
About the Example
Wrapping the Data
Sending Data
Server Program
Receiving Data
More Information
Sending Data
1 of 5
21-04-2000 17:34
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/serial.html
The total number of items is retrieved from the order.itotal field and
displayed in the user interface.
num = new Integer(order.itotal);
text = num.toString();
this.items.setText(text);
Similarly, the total cost is calculated and displayed in the user interface
using the order.icost field.
order.icost = (order.itotal * 1.25);
cost = new Double(order.icost);
text2 = cost.toString();
this.cost.setText(text2);
try{
send.sendOrder(order);
} catch (Exception e) {
System.out.println("Cannot send data to server");
}
After the totals are calculated, the order object is sent over the net to the
server program.
Server Program
2 of 5
21-04-2000 17:34
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/serial.html
RemoteServer.java
The RemoteServer.sendOrder method accepts a DataOrder
instance as input, and stores each order in a separate file where the file
name is a number. The first order received is stored in a file named 1, the
second order is stored in a file named 2, and so forth.
To keep track of the file names, the value variable is incremented by 1
each time the sendOrder method is called, converted to a String, and
used for the file name in the serialization process.
Objects are serialized by creating a serialized output stream and writing
the object to the output stream. In the code, the first line in the try block
creates a FileOutputStream with the file name to which the serialized
object is to be written.
The next line creates an ObjectOutputFileStream from the file output
stream. This is the serialized output stream to which the order object is
written in the last line of the try block.
RemoteServer.java
public void sendOrder(DataOrder order){
value += 1;
num = new Integer(value);
orders = num.toString();
try{
FileOutputStream fos =
new FileOutputStream(orders);
ObjectOutputStream oos =
new ObjectOutputStream(fos);
oos.writeObject(order);
}catch (java.io.FileNotFoundException e){
System.out.println(e.toString());
}catch (java.io.IOException e){
System.out.println(e.toString());
}
}
3 of 5
21-04-2000 17:34
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/serial.html
Receiving Data
The RMIClient2.actionPerformed method gets an order object and
references its fields to display data in the user interface.
if(source == view){
try{
order = send.getOrder();
creditNo.setText(order.cardnum);
customerNo.setText(order.custID);
applesNo.setText(order.apples);
peachesNo.setText(order.peaches);
pearsNo.setText(order.pears);
cost = order.icost;
price = new Double(cost);
unit = price.toString();
icost.setText(unit);
4 of 5
21-04-2000 17:34
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/serial.html
items = order.itotal;
itms = new Integer(items);
i = itms.toString();
itotal.setText(i);
} catch (Exception e) {
System.out.println("Cannot send data to server");
}
}
More Information
You can find more information on serialization in the Reading and Writing
(but no 'rithmetic) lesson in The JavaTM Tutorial.
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
5 of 5
21-04-2000 17:34
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/collec.html
About Collections
The Collection classes available to use in programs implement Collection
interfaces. Interfaces are abstract data types that let collections be
manipulated independently of their representation details. There are three
primary types of collection interfaces: List, Set, and Map. This lesson
focuses on the List and Set collections.
Set implementations do not permit duplicate elements, but List
implementations do. Duplicate elements have the same data type and
value. For example, two customer IDs of type String containing the value
Zelda are duplicate; whereas, an element of type String containing the
value 1 and an element of type Integer containing the value 1 are not
duplicate.
The API provides two general-purpose Set implementations. HashSet,
which stores its elements in a hash table, and TreeSet, which stores its
elements in a balanced binary tree called a red-black tree. The example
for this lesson uses the HashSet implementation because it currently has
the best performance.
This diagram shows the Collection interfaces on the right and the class
hierarchy for the java.util.HashSet on the left. You can see that the
HashSet class implements the Set interface.
1 of 3
21-04-2000 17:34
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/collec.html
Creating a Set
This example adapts the RMIClient2.java class to collect customer IDs in a
Set and print the list of customer IDs whenever the View button is clicked.
The collection object is a Set so if the same customer enters multiple
orders, there is only one element for that customer in the list of customer
IDs. If the program tries to add an element that is the same as an element
already in the set, the second element is simply not added. No error is
thrown and there is nothing you have to do in your code.
The RMIClient2.actionPerformed method calls the addCustomer method
to add a customer ID to the set when the order processor clicks the View
button.
The addCustomer method shown below adds the customer ID to the set
and prints a notice that the customer ID has been added.
//Create list of customer IDs
public void addCustomer(String custID){
s.add(custID);
System.out.println("Customer ID added");
}
Printing
The print method is called from the RMIClient2.actionPerformed method
when the order processor clicks the View button. The print method
prints the elements currently in the set to the command line.
To traverse the set, an object of type Iterator is returned from the set.
The Iterator object has a hasNext method that lets you test if there is
another element in the set, a next that lets you move over the elements in
the set, and a remove method that lets you remove an element.
2 of 3
21-04-2000 17:34
http://developer.java.sun.com/developer...ning/Programming/BasicJava2/collec.html
The example print method shows two ways to print the set. The first way
uses an iterator and the second way simply calls System.out.println
on the set. In the iterator approach, the element returned by the next
method is printed to the command line until there are no more elements in
the set.
//Print customer IDs
public void print(){
//Iterator approach
if(s.size()!=0){
Iterator it = s.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//Call System.out.println on the set
System.out.println(s);
}else{
System.out.println("No customer IDs available");
}
}
More Information
You can find more information on Collections in the Collections trail in The
JavaTM Tutorial.
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
3 of 3
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
More and more companies, large and small, are doing business around the
world using many different languages. Effective communication is always
good business, so it follows that adapting an application to a local
language adds to profitability through better communication and increased
satisfaction.
The JavaTM 2 platform provides internationalization features that let you
separate culturally dependent data from the application
(internationalization) and adapt it to as many cultures as needed
(localization).
This lesson takes the two client programs from Part 2, Lesson 5:
Collections, internationalizes them and adapts the text to France,
Germany, and the United States.
Identify Culturally Dependent Data
Create Keyword and Value Pair Files
Internationalize Application Text
Internationalize Numbers
Compile and Run the Application
Program Improvements
More Information
1 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
The print method could have been coded to declare the exception in its
throws clause as shown below, but this way you cannot access the error
message text thrown when the method tries to access unavailable data in
the set.
In this case, the system-provided text for this error message is sent to the
command line regardless of the locale in use for the application. The point
here is it is always better to use try and catch blocks wherever possible
if there is any chance the application will be internationalized so you can
localize the error message text.
public void print()
throws java.util.NoSuchElementException{
if(s!=null){
2 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
Iterator it = s.iterator();
while(it.hasNext()){
String customer = (String)it.next();
System.out.println(customer);
}
}else{
System.out.println("No customer IDs available");
}
}
Here is a list of the title, label, button, number, and error text visible to the
user, and therefore, subject to internationalization and localization. This
data was taken from both RMIClient1.java and RMIClient2.java.
Labels: Apples, Peaches, Pears, Total Items, Total Cost, Credit
Card, Customer ID
Titles: Fruit $1.25 Each, Select Items, Specify Quantity
Buttons: Reset, View, Purchase
Number Values: Value for total items, Value for total cost
Errors: Invalid Value, Cannot send data to server, Cannot look up
remote server object, No data available, No customer IDs available,
Cannot access data in server
3 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
language and country codes which you should make part of the file name.
The language and country are both included because the same language
can vary between countries. For example, United States English and
Australian English are a little different, and Swiss German and Austrian
German both differ from each other and from the German spoken in
Germany.
These are the names of the properties files for the German (de_DE),
French (fr_FR), and American English (en_US) translations where de,
fr, and en indicate the German (Deutsche), French, and English
lanuages; and DE, FR, and US indicate Germany (Deutschland), France,
and the United States:
MessagesBundle_de_DE.properties
MessagesBundle_en_US.properties
MessagesBundle_fr_FR.properties
Here is the English language properties file. Keywords appear to the left of
the equals (=) sign, and text values appear to the right.
MessagesBundle_en_US.properties
apples=Apples:
peaches=Peaches:
pears=Pears:
items=Total Items:
cost=Total Cost:
card=Credit Card:
customer=Customer ID:
title=Fruit 1.25 Each
1col=Select Items
2col=Specify Quantity
reset=Reset
view=View
purchase=Purchase
invalid=Invalid Value
send=Cannot send data to server
nolookup=Cannot look up remote server object
nodata=No data available
noID=No customer IDs available
noserver=Cannot access data in server
With this file complete, you can hand it off to your French and German
translators and ask them to provide the French and German equivalents
for the text to the right of th equals (=) sign. Keep a copy for yourself
because you will need the keywords to internationalize your application
text.
The properites file with the German translations produces this user
interface for the fruit order client:
4 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
The properties file with the French translations produces this user interface
for the fruit order client:
main Method
The program is designed so the user specifies the language to use at the
command line. So, the first change to the main method is to add the code
5 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
6 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
7 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
Constructor
The window title is set by calling the getString method on the
ResourceBundle, and passing it the keyword that maps to the title text.
You must pass the keyword exactly as it appears in the translation file, or
you will get a runtime error indicating the resource is unavailable.
RMIClient1(){
//Set window title
setTitle(messages.getString("title"));
The next thing the constructor does is use the args parameter to look up
the remote server object. If there are any errors in this process, the
catch statements get the applicable error text from the
ResourceBundle and print it to the command line. User interface objects
that display text, such as JLabel and JButton, are created in the same
way:
//Create left and right column labels
col1 = new JLabel(messages.getString("1col"));
col2 = new JLabel(messages.getString("2col"));
...
//Create buttons and make action listeners
purchase = new JButton(messages.getString(
"purchase"));
purchase.addActionListener(this);
reset = new JButton(messages.getString("reset"));
reset.addActionListener(this);
actionPerformed Method
In the actionPerformed method, the Invalid Value error is caught
and translated:
if(order.apples.length() > 0){
//Catch invalid number error
try{
applesNo = Integer.valueOf(order.apples);
order.itotal += applesNo.intValue();
}catch(java.lang.NumberFormatException e){
appleqnt.setText(messages.getString("invalid"));
}
} else {
order.itotal += 0;
}
Internationalize Numbers
A NumberFormat object is used to translate numbers to the correct
format for the language currently in use. To do this, a NumberFormat
8 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
9 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
rmic -d . RemoteServer
copy RemoteServer*.class
\home\zelda\public_html\classes
copy Send.class \home\zelda\public_html\classes
copy DataOrder.class \home\zelda\public_html\classes
Win32:
cd \home\zelda\public_html\classes
set CLASSPATH=
start rmiregistry
10 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
Program Improvements
A real-world scenario for an ordering application like this might be that
RMIClient1 is an applet embedded in a web page. When orders are
submitted, order processing staff run RMIClient2 as applications from their
local machines.
So, an interesting exercise is to convert RMIClient1.java to its applet
equivalent. The translation files would be loaded by the applet from the
same directory from which the browser loads the applet class.
One way is to have a separate applet for each language with the language
and country codes hard coded. Your web page can let them choose the
language by clicking a link that launches the appropriate applet. Here are
the source code files for the English, French, and German applets.
Here is the HTML code to load the French applet on a Web page.
<HTML>
<BODY>
<APPLET CODE=RMIFrenchApp.class WIDTH=300 HEIGHT=300>
</APPLET>
</BODY>
</HTML>
11 of 12
21-04-2000 17:34
http://developer.java.sun.com/developer...raining/Programming/BasicJava2/int.html
More Information
You can find more information on Internationalization in the
Internationalization trail in The Java Tutorial.
You can find more informationon applets in the Writing Applets trail in The
Java Tutorial.
_______
1 As used on this web site, the terms "Java virtual machine" or "JVM"
mean a virtual machine for the Java platform
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
12 of 12
21-04-2000 17:34
Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR) http://developer.java.sun.com/developer...raining/Programming/BasicJava2/jar.html
Until now, you have used classes from the Java API library by importing the
package containing the class or classes you need. A package is a convenient
way to organize groups of related classes, and in development, you should
organize your application files into packages too. Packages make it easier to
locate and use the class files and help you control access to class data at run
time.
When your application is fully tested, debugged, and ready for deployment,
use the JavaTM Archive file format to deploy the application. JAR file format is
a compression and file packaging format and tool for bundling executable files
with any other related application files so they can be deployed as one unit.
This lesson shows you how to organize the program files from Part 2, Lesson
6: Internationalization into packages and deploy the executable and other
related files to production using JAR file format. Normally, you would use
packages from the beginning of development.
Setting up Class Packages
Create the Directories
Declare the Packages
Make Classes and Fields Accessible
Change Client Code to Find the Properties File
Compile and Run the Example
Using JAR Files to Deploy
Server Set of Files
Fruit Order Client Set of Files
View Order Client Set of Files
More Information
1 of 9
21-04-2000 17:34
Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR) http://developer.java.sun.com/developer...raining/Programming/BasicJava2/jar.html
deployed separately.
Create the Directories
To organize the internationalization program into three packages, you could
create the following three directories and move the listed source files into
them:
client1
RMIEnglishApp.java
RMIFrenchApp.java
RMIGermanApp.java
MessagesBundle_de_DE.properties
MessagesBundle_en_US.properties
MessagesBundle_fr_FR.properties
index.html
rmiFapp.html
rmiGapp.html
rmiEapp.html
java.policy
client2
RMIClient2.java
MessagesBundle_de_DE.properties
MessagesBundle_en_US.properties
MessagesBundle_fr_FR.properties
java.policy
server
DataOrder.java
RemoteServer.java
Send.java
java.policy
Declare the Packages
Each *.java file needs a package delcaration at the top that reflects the
name of the directory. Also, the fruit order (client1 and view order
(client2) client class files need an import statement for the server package
because they have to access the remote server object at runtime.
As an example, the package declaration and import statements for the
RMIClient2.java class file look like this:
//package declaration
package client2;
import
import
import
import
java.awt.Color;
java.awt.GridLayout;
java.awt.event.*;
javax.swing.*;
import java.io.*;
import java.net.*;
import java.rmi.*;
import java.rmi.server.*;
2 of 9
21-04-2000 17:34
Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR) http://developer.java.sun.com/developer...raining/Programming/BasicJava2/jar.html
import java.util.*;
import java.text.*;
//Import server package
import server.*;
3 of 9
21-04-2000 17:34
Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR) http://developer.java.sun.com/developer...raining/Programming/BasicJava2/jar.html
from compiling and running the example in previous lessons. First, you have to
execute the compiler and interpreter commands from one directory above the
package directories, and second, you have to specify the package directories
to the compiler and interpreter commands.
Compile
These instructions assume development occurs in the zelda home directory.
Unix:
cd /home/zelda/classes
javac server/Send.java
javac server/RemoteServer.java
javac client2/RMIClient2.java
javac client1/RMIFrenchApp.java
javac client1/RMIGermanApp.java
javac client1/RMIEnglishApp.java
rmic -d . server.RemoteServer
cp server/RemoteServer*.class
/home/zelda/public_html/classes
cp server/Send.class
/home/zelda/public_html/classes
cp server/DataOrder.class
/home/zelda/public_html/classes
Win32:
cd \home\zelda\classes
javac server\Send.java
javac server\RemoteServer.java
javac client2\RMIClient2.java
javac client1\RMIFrenchApp.java
javac client1\RMIGermanApp.java
javac client1\RMIEnglishApp.java
rmic -d . server.RemoteServer
copy server\RemoteServer*.class
\home\zelda\public_html\classes
copy server\Send.class
\home\zelda\public_html\classes
copy server\DataOrder.class
\home\zelda\public_html\classes
4 of 9
21-04-2000 17:34
Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR) http://developer.java.sun.com/developer...raining/Programming/BasicJava2/jar.html
cd \home\zelda\public_html\classes
set CLASSPATH=
start rmiregistry
Start RMIGermanApp Here is the HTML code to load the German applet,
Note the directory/package name prefixed to the applet class name
(client1/RMIGermanApp.class).
<HTML>
<BODY>
<APPLET CODE=client1/RMIGermanApp.class WIDTH=300 HEIGHT=300>
</APPLET>
</BODY>
</HTML>
To run the applet with appletviewer, invoke the HTML file from the directory
just above client1 as follows:
cd /home/zelda/classes
appletviewer rmiGapp.html
5 of 9
21-04-2000 17:34
Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR) http://developer.java.sun.com/developer...raining/Programming/BasicJava2/jar.html
-Djava.rmi.server.hostname=kq6py.eng.sun.com
-Djava.security.policy=client2\java.policy
client2\RMIClient2 kq6py.eng.sun.com fr FR
jar is the jar command. If you type jar with no options, you get the
following help screen. You can see from the help screen that the cf options
to the jar command mean create a new JAR file named server.jar and
put the list of files that follows into it. The new JAR file is placed in the current
directory.
kq6py% jar
Usage: jar {ctxu}[vfm0M] [jar-file] [manifest-file]
[-C dir] files ...
Options:
-c create new archive
-t list table of contents for archive
6 of 9
21-04-2000 17:34
Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR) http://developer.java.sun.com/developer...raining/Programming/BasicJava2/jar.html
-x
-u
-v
-f
-m
To deploy the server files, all you have to do is move the server.jar file to
a publicly accessible directory on the server where they are to execute.
Decompress and Unpack Server Files
After moving the JAR file to its final location, the compressed and packed files
need to be decompressed and unpacked so you can start the server. The
following command means extract (x) all files from the server.jar file (f).
jar xf server.jar
7 of 9
21-04-2000 17:34
Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR) http://developer.java.sun.com/developer...raining/Programming/BasicJava2/jar.html
jar cf applet.jar
RMIEnglishApp.class
RMIFrenchApp.class
RMIGermanApp.class
index.html
rmiEapp.html
rmiFapp.html
rmiGapp.html
MessagesBundle_de_DE.properties
MessagesBundle_en_US.properties
MessagesBundle_fr_FR.properties
java.policy
To deploy the fruit order client files, copy the applet.jar file to its final
location.
Decompress and Unpack Files
An applet in a JAR file can be invoked from an HTML file without being
unpacked. All you do is specify the ARCHIVE option to the APPLET tag in
your web page, which tells appletviewer the name of the JAR file containing
the class file. Be sure to include the package directory when you specify the
applet class to the CODE option.
You can leave the translation files and policy file in the JAR file. When using
appletviewer, the applet invoked from the JAR file will find them in the JAR
file.
<HTML>
<BODY>
<APPLET CODE=client1/RMIFrenchApp.class
ARCHIVE="applet.jar"
WIDTH=300
HEIGHT=300>
</APPLET>
</BODY>
</HTML>
However, you do need to unpack the web pages so you can move them to
their final location. The following command does this. Everything goes on one
line.
jar xv applet.jar index.html
rmiEapp.html
rmiFapp.html
rmiGapp.html
Note: To run the HTML files from a browser, you need to unpack
the JAR file, copy the java.policy file to your home directory and
make sure it has the right name (.java.policy for Unix and
java.policy for Windows), and install Java Plug-In.
8 of 9
21-04-2000 17:34
Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR) http://developer.java.sun.com/developer...raining/Programming/BasicJava2/jar.html
The view order set of files (below) consists of the application class file and
the policy file.
RMIClient2.class
java.policy
Compress and Pack Files
jar cf vieworder.jar RMIClient2.class java.policy
To deploy the view order client files, copy the vieworder.jar file to its final
location.
Decompress and Unpack Files
jar xf vieworder.jar
More Information
You can find more information on packages in the Creating and Using
Packages lesson in The Java Tutorial.
You can find more information on these and other JAR file format topics in the
JAR File Format trail in The Java Tutorial.
[TOP
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
9 of 9
21-04-2000 17:34
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/oo.html
Classes
A class is a structure that defines the data and the methods to work on
that data. When you write programs in the Java language, all program
data is wrapped in a class, whether it is a class you write or a class you
1 of 9
21-04-2000 17:35
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/oo.html
Classes in the Java platform API libraries define a set of objects that share
a common structure and behavior. The java.lang.System class used in
the example defines such things as standard input, output, and error
streams, and access to system properties. In contrast, the
java.lang.String class defines character strings.
In the example, you do not see an explicit use of the String class, but in
the Java language, a character string can be used anywhere a method
expects to receive a String object. During execution, the Java platform
creates a String object from the character string passed to the
System.out.println call, but your program cannot call any of the
String class methods because it did not instantiate the String object.
If you want access to the String methods, you can rewrite the example
program to create a String object as follows. This way, you can call a
method such as the String.concat method that adds text to the original
string.
class ExampleProgram {
public static void main(String[] args){
String text = new String("I'm a simple Program ");
System.out.println(text);
String text2 = text.concat(
"that uses classes and objects");
System.out.println(text2);
}
}
Objects
An instance is an executable copy of a class. Another name for instance is
object. There can be any number of objects of a given class in memory at
any one time.
In the last example, four different String objects are created for the
concatenation operation, text object, text2 object, and a String
object created behind the scenes from the " that uses classes and
2 of 9
21-04-2000 17:35
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/oo.html
3 of 9
21-04-2000 17:35
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/oo.html
import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;
class ExampleProgram extends JFrame {
public ExampleProgram(){
String text = new String("I'm a simple Program ");
String text2 = text.concat(
"that uses classes and objects");
JLabel label = new JLabel(text2);
JPanel panel = new JPanel();
panel.setBackground(Color.white);
getContentPane().add(panel);
panel.add(label);
}
public static void main(String[] args){
ExampleProgram frame = new ExampleProgram();
frame.setTitle("Fruit $1.25 Each");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
}
}
Inheritance
One object-oriented concept that helps objects work together is
inheritance. Inheritance defines relationships among classes in an
object-oriented language. In the Java programming language, all classes
descend from java.lang.Object and implement its methods.
4 of 9
21-04-2000 17:35
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/oo.html
Polymorphism
Another way objects work together is to define methods that take other
objects as parameters. You get even more cooperation and efficiency
when the objects are united by a common superclass. All classes in the
Java programming language have an inheritance relationship.
5 of 9
21-04-2000 17:35
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/oo.html
Without the public access level (shown below), its access level is
package by default. You get an error when you try to interpret a class
with an access level of package with the appletviewer tool. The same is
true if the access level is protected or private.
class DbaAppl extends Applet
implements ActionListener {
6 of 9
21-04-2000 17:35
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/oo.html
7 of 9
21-04-2000 17:35
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/oo.html
Getting data, displaying the data, and resetting the display are closely
related and easily form a functional module. But in a larger program with
more data processing, the storing and printing of customer IDs could be
expanded to store and print a wider range of data. In such a case, it would
make sense to have a separate class for storing data, and another class
for printing it in various forms.
You could, for example, have a class that defines how to store customer
IDs, and tracks the number of apples, peaches, and pears sold during the
year. You could also have another class that defines report printing. It
could access the stored data to print reports on apples, peaches, and
pears sold by the month, per customer, or throughout a given season.
Making application code modular by separating out functional units makes
it easier to update and maintain the source code. When you change a
class, as long as you did not change any part of its public interface, you
only have to recompile that one class.
Inheritance
Deciding what classes your program needs means separating functions
into modules, but making your code more efficient and easier to maintain
means looking for common functions where you can use inheritance. If you
need to write a class that has functionality similar to a class in the Java
API libraries, it makes sense to extend that API library class and use its
methods rather than write everything from scratch.
The RMIClient2 class from the Part 2, Lesson 5: Collections lesson
extends JFrame to leverage the ready-made functionality it provides for a
program's top-level window including, frame menu closing behavior,
background color setting, and a customized title.
Likewise, if you want to add customized behavior to an existing class, you
can extend that class and add the functionality you want. For example, you
might want to create your own JButton class with a different look. To do
this, you can write your own class that extends JButton and implement it
to appear the way you want. Then your program can instantiate your
button class instead of the JButton class whenever you need a button
with the new look you created.
Access Levels
You should always keep access levels in mind when you declare classes,
fields, and methods. Consider which objects really need access to the
data, and use packages and access levels to protect your application data
from all other objects executing in the system.
Most object-oriented applications do not allow other objects to access
their fields directly by declaring them private. Then they make their
methods protected, public, or package as needed and allow other objects
to manipulate their private data by calling the methods only. This way, you
can update your class by changing a field definition and the corresponding
method implementation, but other objects that access that data do not
8 of 9
21-04-2000 17:35
http://developer.java.sun.com/developer...Training/Programming/BasicJava2/oo.html
Program Improvements
It is always best to restrict access as much as possible. Going back to
Part 2, Lesson 7: Packages and JAR Files, the server classes had to be
made public and the DataOrder class fields also had to be made
public so the client programs can access them.
At that time, no access level was specified for the other classes and fields
so they are all package by default. All methods have an access level of
public.
A good exercise would be to go back to the client classes and give the
classes, fields, and methods an access level so they are not accessed
inappropriately by other objects.
Here is one possible solution for the RMIClient1.java and RMIClient2.java
client programs. Can you explain why the actionPerformed method
cannot be made private? If not, make it private, run the javac
command to compile, and see what the compiler has to say about it.
More Information
You can find more information on Object-oriented programming concepts
files in the Object-Oriented Programming Concepts trail in The Java
Tutorial.
_______
1
As used on this web site, the terms "Java virtual machine" or "JVM"
mean a virtual machine for the Java platform.
[TOP]
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
9 of 9
21-04-2000 17:35