Basic Java
Basic Java
experience with other languages, and are familiar with things like
displaying text or graphics or performing simple calculations, this
tutorial could be for you. it walks through how to use the java® 2
platform software to create and run three common types of programs
written for the java platform—applications, applets, and servlets.
you will learn how applications, applets, and servlets are similar and
different, how to build a basic user interface that handles simple end
user input, how to read data from and write data to files and
databases, and how to send and receive data over the network. this
tutorial is not comprehensive, but instead takes you on a straight and
uncomplicated path through the more common programming features
available in the java platform.
if you have no programming experience at all, you might still find this
tutorial useful; but you also might want to take an introductory
programming course or read teach yourself java 2 online in web time
before you proceed.
contents
lesson 1: compiling and running a simple program
• a word about the java platform
• writing a program
• code comments
• api documentation
• more information
lesson 2: building applications
• constructors
• to summarize
• more information
• application to applet
• packages
• more information
• swing apis
• import statements
• class declaration
• global variables
• constructor
• action listening
• event handling
• main method
• applets revisited
• more information
• html form
• servlet backend
• more information
• exception handling
• restricting applications
• appending
• more information
• database setup
o jdbc driver
• more information
o program behavior
o file summary
• remotesend class
• send interface
• rmiclient1 class
• rmiclient2 class
• more information
in closing
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.
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.
• writing a program
• code comments
• api documentation
• more information
java apis are libraries of compiled code that you can use in your
programs. they let you add ready-made and customizable functionality
to save you programming time.
the simple program in this lesson uses a java api to print a line of text
to the console. the console printing capability is provided in the api
ready for you to use; you supply the text to be printed.
java programs are run (or interpreted) by another program called the
java vm. if you are familiar with visual basic or another interpreted
language, this concept is probably familiar to you. rather than running
directly on the native operating system, the program is interpreted by
the java vm for the native operating system. this means that any
computer system with the java vm installed can run java programs
regardless of the computer system on which the applications were
originally developed.
for example, a java program developed on a personal computer (pc)
with the windows nt operating system should run equally well without
modification on a sun ultra workstation with the solaris operating
system, and vice versa.
setting up your computer
before you can write and run the simple java program in this lesson,
you need to install the java platform on your computer system.
the java platform is available free of charge from the java.sun.com
web site. you can choose between the java® 2 platform software for
windows 95/98/nt or for solaris. the download page contains the
information you need to install and configure the java platform for
writing and running java programs.
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 {
}
here is the exampleprogram.java source code file if you do not want to
type the program text in yourself.
compiling the program
a program has to be converted to a form the java vm can understand
so any computer with a java vm can interpret and run the program.
compiling a java program means taking the programmer-readable text
in your program file (also called source code) and converting it to
bytecodes, which are platform-independent instructions for the java
vm.
the java compiler is invoked at the command line on unix and dos shell
operating systems as follows:
javac exampleprogram.java
java exampleprogram
at the command line, you should see:
i'm a simple program
here is how the entire sequence looks in a terminal window:
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 {
}
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 {
}
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.
/** this class displays a text string at
* the console.
*/
class exampleprogram {
}
with one simple class, there is no reason to generate api
documentation. api documentation makes sense when you have an
application made up of a number of complex classes that need
documentation. the tool generates html files (web pages) that
describe the class structures and contain the text enclosed by doc
comments. the javadoc home page has more information on the
javadoc command and its output.
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.
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.
all programs written in the java language (java programs) are built
tm
from classes. because all classes have the same structure and share
common elements, all java programs are very similar.
• constructors
• more information
every application needs one class with a main method. this class is the
entry point for the program, and is the class name passed to the java
interpreter command to run the application.
the code in the main method executes first when the program starts,
and is the control point from which the controller class accessor
methods are called to work on the data.
class exampleprogram {
the public static void keywords mean the java1 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.
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
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 println, which is a static method
class lessontwoa {
system.out.println(text);
note: the field and method return values are all type
string.
class lessontwob {
string gettext(){
return text;
string getstatictext(){
return text2;
string retrievedstatictext =
proginstance.getstatictext();
system.out.println(retrievedtext);
system.out.println(retrievedstatictext);
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 {
//accessor method
return text;
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.
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.
class lessontwod {
string text;
//constructor
lessontwod(){
//accessor method
string gettext(){
return text;
}
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.
• application to applet
• packages
• more information
application to applet
import java.applet.applet;
import java.awt.graphics;
import java.awt.color;
setbackground(color.cyan);
system.out.println("starting...");
}
system.out.println("stopping...");
system.out.println("preparing to unload...");
system.out.println("paint");
g.setcolor(color.blue);
g.drawrect(0, 0,
getsize().width -1,
getsize().height -1);
g.setcolor(color.red);
to see the applet in action, you need an html file with the applet tag
as follows:
<html>
<body>
</applet>
</body>
</html>
the easiest way to run the applet is with appletviewer shown below
where simpleapplet.html is a file that contains the above html code:
appletviewer simpleapplet.html
the java api applet class provides what you need to design the
appearance and manage the behavior of an applet. this class provides
a graphical user interface (gui) component called a panel and a
number of methods. to create an applet, you extend (or subclass) the
applet class and implement the appearance and behavior you want.
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.
panel class, which extends the container class. the container class
the applet class provides the init, start, stop, destroy, and paint
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
created and loaded by the underlying software. this method performs
one-time operations the applet needs for its operation such as creating
the user interface or setting the font. in the example, the init method
initializes the text string and sets the background color.
the start method: the start method is called when the applet is
visited such as when the end user goes to a web page with an applet
on it. the example prints a string to the console to tell you the applet
is starting. in a more complex applet, the start method would do
things required at the start of the applet such as begin animation or
play sounds.
after the start method executes, the event thread calls the paint
the stop and destroy methods: the stop method stops the applet
when the applet is no longer on the screen such as when the end user
goes to another web page. the example prints a string to the console
to tell you the applet is stopping. in a more complex applet, this
method should do things like stop animation or sounds.
the destroy method is called when the browser exits. your applet
should implement this method to do final cleanup such as stop live
threads.
appearance
the panel provided in the applet class inherits a paint method from
context for drawing on the panel. the graphics object has methods
for graphical operations such as setting drawing colors, and drawing
graphics, images, and text.
the paint method for the simpleapplet draws the i'm a simple applet
string in red inside a blue rectangle.
system.out.println("paint");
g.setcolor(color.blue);
g.drawrect(0, 0,
getsize().width -1,
getsize().height -1);
g.setcolor(color.red);
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
more information
you can find more information on applets in the writing applets trail in
the java tutorial.
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 foundation classes (jfc) project swing apis
tm
• import statements
• class declaration
• instance variables
• constructor
• action listening
• event handling
• main method
• applets revisited
• more information
import statements
here is the swingui.java code. at the top, you have four lines of import
statements. the lines indicate exactly which java api classes the
tm
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 java.awt.color;
import java.awt.borderlayout;
import java.awt.event.*;
import 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
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
jpanel panel;
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(){
button.addactionlistener(this);
clickbutton.addactionlistener(this);
//create panel
panel.setlayout(new borderlayout(1,1));
panel.setbackground(color.white);
getcontentpane().add(panel);
panel.add(borderlayout.center, text);
panel.add(borderlayout.south,
button);
the code uses the borderlayout layout manager, which arranges user
interface components in the five areas shown at left. to add a
component, specify the area (north, south, east, west, or center).
//create panel
panel.setlayout(new borderlayout(1,1));
panel.setbackground(color.white);
getcontentpane().add(panel);
panel.add(borderlayout.center, text);
panel.add(borderlayout.south, button);
}
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.
adding the panel to the jframe. components are not added directly to
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){
if (_clickmemode) {
text.settext("button clicked");
button.settext("click again");
_clickmemode = false;
} else {
button.settext("click me");
_clickmemode = true;
}
}
you can find information on event handling for the different
components in the java tutorial section on event handling.
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){
frame.settitle("example");
system.exit(0);
};
frame.addwindowlistener(l);
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.
system.exit(0);
};
frame.addwindowlistener(l);
applets revisited
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.
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.
servlets are easy to write. all you need is the java® 2 platform
software, and javaserver web development kit (jwsdk). you can
tm
this lesson shows you how to create a very simple form that invokes a
basic servlet to process end user data entered on the form.
• servlet backend
• more information
html form
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.
~/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:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class exampservlet extends httpservlet {
httpservletresponse response)
response.setcontenttype("text/html");
out.println("<title>example</title>" +
"<body bgcolor=ffffff>");
out.println("<h2>button clicked</h2>");
if(data != null){
out.println(data);
} else {
out.println("<p>return to
<a href="../simplehtml.html">form</a>");
out.close();
httpservletresponse response)
the exampservlet class is declared public so the web server that runs
the servlet, which is not local to the servlet, can access it.
the exampservlet class defines a dopost method with the same name,
the dopost method performs the http post operation, which is the
type of operation specified in the html form used for this example. the
other possibility is the http get operation, in which case you would
in short, post requests are for sending any amount of data directly
over the connection without changing the url, and get requests are for
response object. the browser sends a request to the servlet and the
servlet sends a response back to the browser.
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
method implementation
the first part of the dopost method uses the response object to create
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
out.println(data);
} else {
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.
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.
• system properties
• file.separatorchar
• exception handling
• restricting applications
• appending
• more informattion
constructor
actionperformed
jtextfield
constructor actionperformed
constructor jtextfield
jtextfield center
note:
jtextfield textfield;
fileio(){
clicked = new
button.addactionlistener(this);
clickbutton.addactionlistener(this);
panel.setlayout(new borderlayout());
panel.setbackground(color.white);
getcontentpane().add(panel);
panel.add("north", text);
panel.add("center", textfield);
panel.add("south", button);
}
method changes
actionperformedfileinputstreamfileoutputstream
object source = event.getsource();
if(source == button){
string s = null;
if(_clickmemode){
try{
string outputfilename =
system.getproperty("user.home",
file.separatorchar + "home" +
file.separatorchar + "monicap") +
file.separatorchar + "text.txt";
fileoutputstream(outputfile);
out.write(b);
out.close();
string inputfilename =
system.getproperty("user.home",
file.separatorchar + "home" +
file.separatorchar + "monicap") +
file.separatorchar + "text.txt";
fileinputstream in = new
fileinputstream(inputfile);
byte[(int)inputfile.length()];
in.read(bt);
s = new string(bt);
in.close();
}catch(java.io.ioexception e){
textfield.settext("");
textfield.settext(s);
button.settext("click again");
_clickmemode = false;
} else {
textfield.settext("");
button.settext("click me");
_clickmemode = true;
textfield
filefileoutputstream
string outputfilename =
system.getproperty("user.home",
file.separatorchar + "home" +
file.separatorchar + "monicap") +
file.separatorchar + "text.txt";
fileoutputstream(outputfile);
fileoutputstreamfile
out.write(b);
out.close();
filefileinputstream
string inputfilename =
system.getproperty("user.home",
file.separatorchar + "home" +
file.separatorchar + "monicap") +
file.separatorchar + "text.txt";
fileinputstream(inputfile);
byte
byte bt[] = new byte[(int)inputfile.length()];
in.read(bt);
stringlabelfileinputstream
string s = new string(bt);
label.settext(s);
in.close();
system properties
system.getpropertysystemfile.separatorchar
system.getpropertyuser.homefile.separatorchar + "home" +
file.separatorchar + "monicap")
file.separatorchar
java.io.file.separatorcharfile.separator
/home/monicap/text.tx
t\home\monicap\text.txtfile.separatorchar + "home" +
"text.txt"
exception handling
java.lang.exceptionjava.lang.runtimeexception
actionperformedtrycatchjava.lang.ioexception
java.lang.ioexception
java.lang.throwable
trycatchjava.io.ioexception
actionperformedjava.io.ioexception
public int acomputationmethod(int number1,
int number2)
throws illegalvalueexception{
//body of method
note:
tostringprintstacktrace
}catch(java.io.ioexception e){
system.out.println(e.tostring());
system.out.println(e.printstacktrace());
}catch(java.io.ioexception e){
• writing:textfieldout.write
• reading:
if(source == button){
string s = null;
if(_clickmemode){
try{
string outputfilename =
system.getproperty("user.home",
file.separatorchar + "home" +
file.separatorchar + "monicap") +
file.separatorchar + "text.txt";
filewriter(outputfile);
out.write(text);
out.close();
string inputfilename =
system.getproperty("user.home",
file.separatorchar + "home" +
file.separatorchar + "monicap") +
file.separatorchar + "text.txt";
file inputfile = new file(inputfilename);
char[(char)inputfile.length()];
in.read(c);
s = new string(c);
in.close();
}catch(java.io.ioexception e){
textfield.settext("");
textfield.settext(s);
button.settext("click again");
_clickmemode = false;
} else {
textfield.settext("");
button.settext("click me");
_clickmemode = true;
click me
fileuiappltext.txttext.txt
grant {
permission java.util.propertypermission
"user.home", "read";
permission java.io.filepermission
"${user.home}/text.txt", "read,write";
};
running an applet with a policy file
polfilefileio.htmlfileioappl
appletviewer -j-djava.security.policy=polfile fileio.html
note:
fileio.htmlfileioappl
<html>
<body>
</applet>
</body>
</html>
restricting applications
java -djava.security.manager
-djava.security.policy=apppolfile fileio
grant {
permission java.awt.awtpermission
"accesseventqueue";
permission java.awt.awtpermission
"showwindowwithoutwarningbanner";
permission java.util.propertypermission
"user.home", "read";
permission java.io.filepermission
"${user.home}/text.txt", "read,write";
};
exampservlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
httpservletresponse response)
response.setcontenttype("text/html");
out.println("<title>example<title>" +
"<body bgcolor=ffffff>");
out.println("<h2>button clicked</h2>");
if(data != null){
out.println("<strong>text from
form:</strong>");
out.println(data);
} else {
try{
string outputfilename=
system.getproperty("user.home",
file.separatorchar + "home" +
file.separatorchar + "monicap") +
file.separatorchar + "text.txt";
fout.write(data);
fout.close();
string inputfilename =
system.getproperty("user.home",
file.separatorchar + "home" +
file.separatorchar + "monicap") +
file.separatorchar + "text.txt";
filereader(inputfile);
char[(char)inputfile.length()];
int i;
i = fin.read(c);
out.println("<p>
out.println(s);
fin.close();
}catch(java.io.ioexception e){
}
out.println("<p>return to
<a href="../simplehtml.html">form</a>");
out.close();
appending
more information
o
•
database setup
jdbcjdbcjdbc.odbcjdbc.odbcoracleoci7.3.4
table dba (
text varchar2(100),
click me
click me
establishing a database connection
drivermanagerconnectionstrings_driver_url
_urljdbc:oracle:thinusernamepassword
private connection c;
"oracle.jdbc.driver.oracledriver";
"jdbc:oracle:thin:username/password@(description=(
address_list=(address=(protocol=tcp)
(host=developer)(port=1521)))
(source_route=yes)(connect_data=(sid=jdcsid)))";
actionperforme
class.forname(_driver
)drivermanager.getconnectiontrycatchcatch
class.forname(_driver);java.lang.classnotfoundexceptionc =
drivermanager.getconnection(_url);java.sql.sqlexception
try{
class.forname(_driver);
c = drivermanager.getconnection(_url);
system.exit(1);
system.exit(1);
}
final and private variables
privatefinal
finalfinalfinal
privateprivateprivateprivate
statementconnectionstatementstringexecuteupdatestatement
object source = event.getsource();
if(source == button){
try{
stringstringthetext
resultsetexecutequerystatementresultsetresultsetdisplaytext
while(results.next()){
string s = results.getstring("text");
displaytext.append(s + "\n");
stmt.close();
} catch(java.sql.sqlexception e){
system.out.println(e.tostring());
panel.removeall();
panel.add("north", clicked);
panel.add("center", displaytext);
panel.add("south", clickbutton);
panel.validate();
panel.repaint();
<html>
<body>
<applet code=dbaappl.class
width=200
height=100>
</applet>
</body>
</html>
appletviewer dbaappl.html
appletviewer dbaappl.html
socketpermissiondeveloper
grant {
permission java.net.socketpermission "developer",
"resolve";
"accessclassinpackage.sun.jdbc.odbc";
};
dbaapplpol
appletviewer -j-djava.security.policy=dbaapplpol
dbaappl.html
(java.net.socketpermission
129.144.176.176:1521 connect,resolve)
socketpermissiondeveloper
dbaapplpol
grant {
"resolve";
permission java.net.socketpermission
"129.144.176.176:1521", "connect,resolve";
};
appletviewer -j-djava.security.policy=dbaapplpol
dbaappl.html
jdbc-odbc bridge with odbc driver
drivermanager
start the applet:dbaodb.htmldbaodbappl
<html>
<body>
<applet code=dbaodbappl.class
width=200
height=100>
</applet>
</body>
</html>
appletviewer dbaodb.html
(java.lang.runtimepermission
accessclassinpackage.sun.jdbc.odbc )
runtimepermissionsun.jdbc.odbc
grant {
permission java.lang.runtimepermission
"accessclassinpackage.sun.jdbc.odbc";
};
dbaodbpol
appletviewer -j-djava.security.policy=dbaodbpol
dbaodb.html
java.security.accesscontrolexception:
access denied (java.lang.runtimepermission
file.encoding read)
dbaodbpol
grant {
permission java.lang.runtimepermission
"accessclassinpackage.sun.jdbc.odbc";
permission java.util.propertypermission
"file.encoding", "read";
};
appletviewer -j-djava.security.policy=dbaodbpol
dbaodb.html
fileioservlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;
import java.io.*;
private connection c;
"sun.jdbc.odbc.jdbcodbcdriver";
_url = "jdbc:odbc:jdc";
httpservletresponse response)
response.setcontenttype("text/html");
out.println("<title>example<title>" +
"<body bgcolor=ffffff>");
out.println("<h2>button clicked</h2>");
if(data != null){
out.println("<strong>text from
form:</strong>");
out.println(data);
} else {
try{
class.forname (_driver);
c = drivermanager.getconnection(_url,
_user,
_pass);
} catch (exception e) {
e.printstacktrace();
system.exit(1);
try{
while(results.next()){
string s = results.getstring("text");
out.println("<br>
out.println(s);
stmt.close();
}catch(java.sql.sqlexception e){
system.out.println(e.tostring());
out.println("<p>return to
<a href="../dbahtml.html">form</a>");
out.close();
more information
•
o
program behavior
rmiclient1rmiclient2click mermiclient2click me
file summary
• senddataremoteserver
• getdataremoteserver
• send.javasenddatagetdata
• senddatagetdata
grant {
permission java.net.socketpermission
"*:1024-65535",
"connect,accept,resolve";
permission java.net.socketpermission
"*:80", "connect";
permission java.awt.awtpermission
"accesseventqueue";
permission java.awt.awtpermission
"showwindowwithoutwarningbanner";
};
compile the example
zeldazeldapublic_htmlzelda
unix:
cd /home/zelda/classes
javac send.java
javac remoteserver.java
javac rmiclient2.java
javac rmiclient1.java
rmic -d . remoteserver
cp remoteserver*.class /home/zelda/public_html/classes
cp send.class /home/zelda/public_html/classes
win32:
cd \home\zelda\classes
javac send.java
javac remoteserver.java
javac rmiclient2.java
javac rmiclient1.java
rmic -d . remoteserver
javacremoteserversendjavacrmiclient2javacrmiclient1
rmi
remoteserve
rclassname_stub.classclassname_skel.classremoteserver
remoteserve
rskelstub/home/zelda/public_html/classespublic_html
sendrmiclient1rmiclient2public_html
• rmiclient1
• rmiclient2
rmiregistryclasspathstubskel
cd /home/zelda/public_html/classes
unsetenv classpath
rmiregistry &
win32:
cd \home\zelda\public_html\classes
set classpath=
start rmiregistry
note:classpath
remoteserverrmiclient1rmiclient2
remoteserver/home/zelda/public_html/classes
java-djava
unix:
cd /home/zelda/public_html/classes
java
-djava.rmi.server.codebase=http://kq6py/~zelda/classes
-djava.rmi.server.hostname=kq6py.eng.sun.com
-djava.security.policy=java.policy remoteserver
win32:
cd \home\zelda\public_html\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 remoteserver
• java.rmi.server.codebase
• java.rmi.server.hostname
• java.rmi.security.policy
• remoteserver
rmiclient1/home/zelda/classes
java-djava
unix:
cd /home/zelda/classes
java -djava.rmi.server.codebase=
http://kq6py/~zelda/classes/
-djava.security.policy=java.policy
rmiclient1 kq6py.eng.sun.com
win32:
cd \home\zelda\classes
java -djava.rmi.server.codebase=
file:c:\home\zelda\classes\
-djava.security.policy=java.policy
rmiclient1 kq6py.eng.sun.com
• java.rmi.server.codebase
• java.security.policy
• rmiclient1kq6py
run rmiclient2
rmiclient2/home/zelda/classes
java-djava
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
• java.rmi.server.codebase
• java.rmi.server.hostname
• java.rmi.security.policy
• rmiclient2
remoteserver class
unicastremoteobjectsenddatagetdatasend
unicastremoteobjectjava.lang.object
implements send {
string text;
text = gottext;
return text;
mainrmisecuritymanagermainremoteserverkq6pysend
kq6py:4444
tryremoteservernamenaming.rebind(name, remoteserver);
if(system.getsecuritymanager() == null) {
system.setsecuritymanager(new
rmisecuritymanager());
try {
naming.rebind(name, remoteserver);
system.out.println("remoteserver bound");
} catch (java.rmi.remoteexception e) {
system.out.println("cannot create
} catch (java.net.malformedurlexception e) {
system.out.println("cannot look up
server object");
note:remoteserversendsendremoteserver
send interface
remoteserver
public interface send extends remote {
throws remoteexception;
rmiclient1 class
actionperformedmain
actionperformed method
actionperformedremoteserver.senddata
public void actionperformed(actionevent event){
if(source == button){
try{
send.senddata(text);
} catch (java.rmi.remoteexception e) {
textfield.settext(new string(""));
}
main method
mai
rmisecuritymanagernameremoteservernaming.lookupremoteserver
if(system.getsecuritymanager() == null) {
system.setsecuritymanager(new rmisecuritymanager());
try {
} catch (java.rmi.notboundexception e) {
system.out.println("cannot look up
} catch(java.rmi.remoteexception e){
system.out.println("cannot look up
} catch(java.net.malformedurlexception e) {
system.out.println("cannot look up
rmiclient2 class
actionperformedmain
actionperformed method
actionperformedremoteserver.getdatatextarea
public void actionperformed(actionevent event) {
if(source == button){
try{
textarea.append(text);
} catch (java.rmi.remoteexception e) {
to server");
}
main method
mai
rmisecuritymanage
rnameremoteserverargs[0]naming.lookupremoteserver
rmiclient2 frame = new rmiclient2();
if(system.getsecuritymanager() == null) {
system.setsecuritymanager(new rmisecuritymanager());
try {
} catch (java.rmi.notboundexception e) {
server object");
} catch(java.rmi.remoteexception e){
server object");
} catch(java.net.malformedurlexception e) {
server object");
more information
in closing
monica pawlan is a staff writer on the jdc team. she has a background
in 2d and 3d graphics, security, database products, and loves to
explore emerging technologies.