Você está na página 1de 78

Java and J2EE (06IS753)

Java and J2EE


Scheme and Syllabus
Subject Code: 06IS753
Hours / Week: 04
Total Hours: 52

I.A. Marks: 25
Exam Hours: 03
Exam Marks: 100
PART - A

UNIT - 1
INTRODUCTION TO JAVA: Java and Java applications; Java Development Kit (JDK); Java is
interpreted, Byte Code, JVM; Object-oriented programming; Simple Java programs. Data types
and other tokens: Boolean variables, int, long, char, operators, arrays, white spaces, literals,
assigning values; Creating and destroying objects; Access specifiers. Operators and Expressions:
Arithmetic Operators, Bitwise operators, Relational operators, The Assignment Operator, The?
Operator; Operator Precedence; Logical expression; Type casting; Strings Control Statements:
Selection statements, iteration statements, Jump Statements.
6 Hours
UNIT - 2
CLASSES, INHERITANCE, EXCEPTIONS, APPLETS: Classes: Classes in Java; Declaring
a class; Class name; Super classes; Constructors; Creating instances of class; Inner classes.
Inheritance: Simple, multiple, and multilevel inheritance; Overriding, overloading. Exception
handling: Exception handling in Java. The Applet Class: Two types of Applets; Applet basics;
Applet Architecture; An Applet skeleton; Simple Applet display methods; Requesting repainting;
Using the Status Window; The HTML APPLET tag; Passing parameters to Applets;
getDocumentbase() and getCodebase(); ApletContext and showDocument(); The AudioClip
Interface; The AppletStub Interface; Output to the Console.
6 Hours
UNIT - 3
MULTI THREADED PROGRAMMING, EVENT HANDLING: Multi Threaded
Programming: What are threads? How to make the classes threadable; Extending threads;
Implementing runnable; Synchronization; Changing state of the thread; Bounded buffer
problems, read-write problem, producer-consumer problems. Event Handling: Two event
handling mechanisms; The delegation event model; Event classes; Sources of events; Event
listener interfaces; Using the delegation event model; Adapter classes; Inner classes.
7 Hours

UNIT - 4
SWINGS: Swings: The origins of Swing; Two key Swing features; Components and Containers;
The Swing Packages; A simple Swing Application; Create a Swing Applet; Jlabel and
Dept. of ISE , SJBIT

Java and J2EE (06IS753)

ImageIcon; JTextField;The Swing Buttons; JTabbedpane; JScrollPane; JList; JComboBox;


JTable.
7 Hours

PART - B
UNIT - 5
JAVA 2 ENTERPRISE EDITION OVERVIEW, DATABASE ACCESS: Overview of J2EE
and J2SE. The Concept of JDBC; JDBC Driver Types; JDBC Packages; A Brief Overview of the
JDBC process; Database Connection; Associating the JDBC/ODBC Bridge with the Database;
Statement Objects; ResultSet; Transaction Processing; Metadata, Data types; Exceptions.
6 Hours
UNIT - 6
SERVLETS: Background; The Life Cycle of a Servlet; Using Tomcat for Servlet Development;
A simple Servlet; The Servlet API; The Javax.servlet Package; Reading Servlet Parameter; The
Javax.servlet.http package; Handling HTTP Requests and Responses; Using Cookies; Session
Tracking.
7 Hours
UNIT - 7
JSP, RMI: Java Server Pages (JSP): JSP, JSP Tags, Tomcat, Request String, User Sessions,
Cookies, Session Objects. Java Remote Method Invocation: Remote Method Invocation concept;
Server side, Client side.
6 Hours
UNIT - 8
ENTERPRISE JAVA BEANS: Enterprise java Beans; Deployment Descriptors; Session Java
Bean, Entity Java Bean; Message-Driven Bean; The JAR File.
7 Hours
TEXT BOOKS:
1. Java - The Complete Reference Herbert Schildt, 7th Edition, Tata McGraw Hill,
2007.
2. J2EE - The Complete Reference Jim Keogh, Tata McGraw Hill, 2007.
REFERENCE BOOKS:
1. Introduction to JAVA Programming Y. Daniel Liang, 6th Edition, Pearson
Education, 2007.
2. The J2EE Tutorial Stephanie Bodoff et al, 2nd Edition, Pearson Education, 2004.
Dept. of ISE , SJBIT

Java and J2EE (06IS753)

UNIT
No.
1

Table of Contents
INTRODUCTION TO JAVA

Page
No.
1-12

Java and Java applications; Java Development Kit (JDK); Java is interpreted,
Byte Code.

JVM , Object-oriented programming; Simple Java programs

Data types and other tokens: Boolean variables, int, long, char, operators, arrays,
white spaces, literals,

Assigning values ,Creating and destroying objects; Access specifiers.

operators and Expressions: Arithmetic Operators, Bitwise operators, Relational


operators, The Assignment Operator, The ? Operator; Operator Precedence;
Logical expression;

Type casting; Strings , Control Statements: Selection statements, iteration


statements, Jump Statements

CLASSES, INHERITANCE, EXCEPTIONS, APPLETS

13-28

Classes: Classes in Java; Declaring a class; Class name; Super classes;


Constructors; Creating instances of class; Inner classes

13

Inheritance: Simple, multiple, and multilevel inheritance; Overriding,


overloading.

15

Exception handling: Exception handling in Java.

18

The Applet Class: Two types of Applets; Applet basics; Applet Architecture; An
Applet skeleton; Simple Applet display method

20

Requesting repainting; Using the Status Window; The HTML APPLET tag;
Passing parameters to Applets; getDocumentbase() and getCodebase()

22

ApletContext and showDocument(); The AudioClip Interface; The AppletStub


Interface; Output to the Console.

23

MULTI THREADED PROGRAMMING, EVENT HANDLING


Multi Threaded Programming: What are threads? How to make the classes
threadable;

Dept. of ISE , SJBIT

29-41
29

Java and J2EE (06IS753)

Extending threads; Implementing runnable; Synchronization; Changing state of


the thread; Bounded buffer problems

30

Read-write problem, producer-consumer problems

33

Two event handling mechanisms

35

The delegation event model; Event classes; Sources of events

36

Event listener interfaces; Using the delegation event model

37

Adapter classes; Inner classes

39

SWINGS
Swings: The origins of Swing; Two key Swing features

42

Components and Containers

42

The Swing Packages; A simple Swing Application

45

Create a Swing Applet

46

Jlabel and ImageIcon

47

JTextField;The Swing Buttons; JTabbedpane

48

JScrollPane; JList; JComboBox; JTable

49

JAVA 2 ENTERPRISE EDITION OVERVIEW, DATABASE ACCESS:


Overview of J2EE and J2SE.

42-49

50-53
50

The Concept of JDBC; JDBC Driver Types; JDBC Packages

50

A Brief Overview of the JDBC process; Database Connection;

50

Associating the JDBC/ODBC Bridge with the Database;

51

Statement Objects ,ResultSet;

52

Transaction Processing Metadata,. Data types; Exceptions.

53

SERVLETS

54-60

Background

54

The Life Cycle of a Servlet; Using Tomcat for Servlet Development; A simple
Servlet

54

The Servlet API; The Javax.servlet Package

55

Dept. of ISE , SJBIT

Java and J2EE (06IS753)

Reading Servlet Parameter; The Javax.servlet.http package

56

Handling HTTP Requests and Responses

57

Using Cookies

58

Session Tracking.

59

JSP, RMI

61-65

Java Server Pages (JSP): JSP, JSP Tags

61

Tomcat, Request String, User Sessions

62

Cookies, Session Objects

64

Java Remote Method Invocation: Remote Method Invocation concept

64

Server side

65

Client side.

65

KSIMC

65

Dic single windows agency SISI,NSIC,SIDBI,KSFC

65

ENTERPRISE JAVA BEANS

66-68

Enterprise java Beans;

66

Deployment Descriptors

67

Session Java Bean

67

Entity Java Bean;

67

Message-Driven Bean, The JAR File.

68

Dept. of ISE , SJBIT

Java and J2EE (06IS753)

UNIT-1
INTRODUCTION TO JAVA

Java and Java applications; Java Development Kit (JDK); Java is interpreted, Byte Code, JVM;
Objectoriented programming; Simple Java programs.
Data types and other tokens:
Boolean variables, int, long, char, operators,
arrays, white spaces, literals, assigning values; Creating and destroying objects; Access specifiers.
Operators and Expressions: Arithmetic Operators,
Bitwise operators, Relational operators, The Assignment Operator, The? Operator; Operator
Precedence; Logical expression; Type casting; Strings Control Statements: Selection statements,
iteration statements, Jump Statements.

SJBIT, Dept. of ISE

Page 1

Java and J2EE (06IS753)

1.1. Introduction to Java


x Java is an object-oriented programming language developed by Sun Microsystems, a
company best known for its high-end Unix workstations.
x Java is modeled after C++
x Java language was designed to be small, simple, and portable across platforms and
operating systems, both at the source and at the binary level (more about this later).
x Java also provides for portable programming with applets. Applets appear in a Web
page much in the same way as images do, but unlike images, applets are dynamic and
interactive.
x Applets can be used to create animations, figures, or areas that can respond to input
from the reader, games, or other interactive effects on the same Web pages among the
text and graphics.
1.1.2 Java Is Platform-Independent
Platform-independence is a program's capability of moving easily from one computer
system to another.
x Platform independence is one of the most significant advantages that Java has over other
programming languages, particularly for systems that need to work on many different
platforms.
x

Java is platform-independent at both the source and the binary level.

1.1.2 Java Development Kit (JDK)- Byte code


x Bytecodes are a set of instructions that look a lot like machine code, but are not specific to
any one processor
x Platform-independence doesn't stop at the source level, however. Java binary files are also
platform-independent and can run on multiple platforms without the need to recompile the
source. Java binary files are actually in a form called bytecodes.
1.1.3 Object-Oriented Programming
x Many of Java's object-oriented concepts are inherited from C++, the language on which it
is based, but it borrows many concepts from other object-oriented languages as well.

SJBIT, Dept. of ISE

Page 2

Java and J2EE (06IS753)

x Java includes a set of class libraries that provide basic data types, system input and output
capabilities, and other utility functions.
x T h e s e b a s i c c l a s s e s a r e p a r t o f t h e J a v a d e ve l o p m e n t k i t , w h i c h a l s o h a s c l a s s e s t o
s u p p o r t n e t w o r k i n g, c o m m o n I n t e r n e t p r o t o c o l s , a n d u s e r i n t e r f a c e t o o l k i t f u n c t i o n s .
x B e c a u s e t h e s e c l a s s l i b r a r i e s a r e w r i t t e n i n J a va , t h e y a r e p o r t a b l e a c r o s s p l a t f o r m s a s
a ll Ja va a ppl ic a tio ns a re .
1.1.4 Creating a simple Java Program
H e ll o W or ld e xa m ple :
c la s s He l loW o r ld {
p u b l i c s t a t i c vo i d m a i n ( S t r i n g a r gs [ ] ) {
S y s t e m . o u t . p r i n t l n (" H e l l o W o r l d ! " ) ;
}
}
T hi s p ro gra m ha s tw o ma i n pa rts :
x A ll t he pr o gra m i s e nc l ose d i n a c la s s de f in iti on he re , a c la ss c a lle d
H ell o Wor ld.
x T h e b o d y o f t h e p r o g r a m ( h e r e , j u s t t h e o n e l i n e ) i s c o n t a i n e d i n a m e t h o d (f u n c t i o n )
c a l l e d m a i n ( ) . I n J a va a p p l i c a t i o n s , a s i n a C o r C + + p r o g r a m , m a i n ( ) i s t h e f i r s t m e t h o d
( f u nc ti on ) tha t i s ru n whe n the p ro gr a m is e xe c u te d.
1.1.5 Compiling the above program :
x

I n S u n ' s J D K, t h e J a va c o m p i l e r i s c a l l e d j a va c .

javac HelloWorld.java
x W he n the p r o gra m c o mp ile s wit ho ut e rr o rs, a f i le c a l le d He lloW o rld. c la ss is c re a te d,
i n t h e s a m e d i r e c t o r y a s t h e s o u r c e f i l e . T h i s i s t h e J a va b y t e c o d e f i l e .
x T h e n r u n t h a t b y t e c o d e f i l e u s i n g t h e J a va i n t e r p r e t e r . I n t h e J D K, t h e J a v a i n t e r p r e t e r
i s c a l l e d s i m p l y j a va .
j a va H e l l o W o r l d
If the program was typed and compiled correctly, the output will be :
" He llo W o rl d!"
1.2
x

Variables and Data Types


V a r i a b l e s a r e l o c a t i o n s i n m e m o r y i n w h i c h va l u e s c a n b e s t o r e d . T h e y h a ve a n a m e ,

SJBIT, Dept. of ISE

Page 3

Java and J2EE (06IS753)


a t y p e , a n d a va l u e .

x Ja va ha s th re e ki nd s of va ria ble s : in sta nc e va r ia b le s, c la ss va r ia ble s, a n d loc a l


va ria ble s.
x I n s t a n c e va r i a b l e s , a r e u s e d t o d e f i n e a t t r i b u t e s o r t h e s t a t e f o r a p a r t i c u l a r o b j e c t.
C l a s s va r i a b l e s a r e s i m i l a r t o i n s t a n c e va r i a b l e s , e x c e p t t h e i r va l u e s a p p l y t o a l l t h a t
c l a s s ' s i n s t a n c e s ( a n d t o t h e c l a s s i t s e l f ) r a t h e r t h a n h a v i n g d i f f e r e n t va l u e s f o r e a c h
o bj ect.
x L o c a l va r i a b l e s a r e d e c l a r e d a n d u s e d i n s i d e m e t h o d d e f i n i t i o n s ,
for example, for index counters in loops, as temporary variables, or to hold values t hat
yo u ne e d on l y in si de the me th od de f i nit io n itse lf
V a ri a b l e d e c l a ra t i o n s c o n s i s t o f a t y p e a n d a v a ri a b l e n a m e :
E xa m ple s :
int myAge;
String
myName;
boolean isTired;
1. 2.1 I nte ger type s.
Type Size Range
b yte 8 bi ts 12 8 to 1 27
s ho r t 16 bi ts 32, 7 68 to 32, 7 67
i nt 3 2 bit s 2, 1 47, 4 83, 6 4 8 to 2, 14 7, 48 3, 64 7
9 22 33 72 03 68 54 77 580 8 to 9 22 33 72 03 68 54 77 5 80 7 lon g 64 b its

1. 2.2 Floating-point
T h i s i s u s e d f o r n u m b e r s w i t h a d e c i m a l p a rt . J a v a f l o a t i n g - p o i n t n u m b e r s a re c o m p l i a n t
w it h IE EE 7 54 (a n in te r na ti ona l sta nda r d f o r de f ini n g f loa t in g-p oi nt num be rs a nd
a rit hme t ic ).
T h e r e a re t w o f l o a t i n g -p o i n t t y p e s : f l o a t (3 2 b i t s , s i n g l e -p re c i s i o n ) a n d d o u b l e ( 6 4 b i t s ,
d o uble - pre c i si on ).
1. 2.3 Char

SJBIT, Dept. of ISE

Page 4

Java and J2EE (06IS753)

T h e c h a r t y p e i s u s e d f o r i n d i v i d u a l c h a ra c t e r s . B e c a u s e J a v a u s e s t h e U n i c o d e c h a ra c t e r
se t, the c ha r t ype ha s 16 bi ts of p re c isi on, un si gne d.
1. 2.4 Boolean

T h e b o o l e a n t y p e c a n h a ve o n e o f t w o v a l u e s , t r u e o r f a l s e . N o t e t h a t u n l i k e i n o t h e r C l i k e l a n g u a g e s , b o o l e a n i s n o t a n u m b e r, n o r c a n i t b e t re a t e d a s o n e . A l l t e s t s o f B o o l e a n
va ria ble s s ho ul d te st f o r t rue o r f a lse .
1. 2.5 Literals
Li t e ra l s a re u s e d t o i n d i c a t e s i m p l e v a l u e s i n y o u r J a v a p ro g r a m s .
N u m b e r Li t e r a l s
x T h e r e a r e s e ve r a l i n t e ge r l i t e r a l s . 4 , f o r e x a m p l e , i s a d e c i m a l i n t e ge r l i t e r a l o f t y p e
i nt
x A d e c i m a l i n t e ge r l i t e r a l l a r ge r t h a n a n i n t i s a u t o m a t i c a l l y o f t y p e l o n g.
x F l oa ti n g- poi nt lite ra ls us ua ll y ha ve t wo pa r ts: the inte ge r pa rt a n d t he de c ima l pa r t
f o r exam ple, 5. 677 77 7.
B o o l e a n Li t e r a l s
B o o l e a n l i t e ra l s c o n s i s t o f t h e k e y w o r d s t r u e a n d f a l s e . T h e s e k e y w o r d s c a n b e u s e d
a n y w h e r e n e e d e d a t e s t o r a s t h e o n l y p o s s i b l e v a l u e s f o r b o o l e a n va r i a b l e s .
1 . 2 . 6 C ha r a c te r L i te r a l s
C h a ra c t e r l i t e ra l s a re e x p r e s s e d b y a s i n g l e c h a ra c t e r s u r r o u n d e d b y s i n g l e q u o t e s : ' a ' , ' # ' ,
' 3 ', a nd s o on. C ha ra c te rs a re sto re d a s 1 6 -bi t Un ic o de c ha ra c te rs.
1. 3 Expressions and Operators
x E x pre ssi on s a re the s im ple st f o rm of sta te me nt i n Ja va tha t a c t ua ll y
a c c o m p l i s h e s s o m e t h i n g . E x p r e s s i o n s a r e s t a t e m e n t s t h a t r e t u r n a va l u e .
x O p e r a t o r s a re spe c ia l s ym bo ls tha t a re c ommo nl y use d in e xp re s si ons.
A r it hme tic a nd te sts f o r e q ua li t y a n d ma gn it ude a re c omm on e xa mple s of
e x p r e s s i o n s . B e c a u s e t h e y r e t u r n a va l u e t h e va l u e c a n b e a s s i g n e d t o a v a r i a b l e o r
t e s t t h a t va l u e i n o t h e r J a va s t a t e m e n t s .
O p e ra t o rs i n J a v a i n c l u d e a ri t h m e t i c , v a ri o u s f o r m s o f a s s i g n m e n t , i n c r e m e n t a n d
de c re me nt, a nd lo gic a l o pe ra ti on s.
1. 3.1 Arithme tic
SJBIT, Dept. of ISE

Page 5

Java and J2EE (06IS753)

J a v a h a s f i ve o p e r a t o r s f o r b a s i c a r i t h m e t i c

Ari thme tic oper ators.


Operator
Ex am
Meaning
ple
+
A d dit io n
3+4

S u bt ra c t io n
5
*
M ul tip licati on 57* 5
/
D i vi s i o n
14 / 7
%

Modul us 20 % 7

Exa m ple progra m :


c l as s Ari t hm et i c Te s t {
publ i c sta t ic voi d ma in (St ri ng a rgs[ ] ) {
short x = 6;
int y = 4;
f l oa t a = 12. 5f ;
f l oa t b = 7f ;
S
Syysstteem
m..oouutt..pprriinnttllnn((""xx +i sy"=+"x+
S ys t e m . o ut. p r i n t ln (" x - y = " +

}}

+
",

y is "

(
x

+ y));

- y));
(
x / y));
S ys t e m . o ut. p r i n t ln (" x / y = " +
S ys t e m . o u t . p r i n t l n (" a is " + a + " , b i s "
(
S ys t e m . o ut. p r i n t ln (" x % y = " +
%
S y s t e m . o u t . p r i n t l n (" a / b = " + ( a /xb ) ) ; y ) ) ;

Assignment operators.

+
y);

+
b;

(
x

Expression Meaning
x += y
x

x=x+y

= y x = x y

x *= y

x=x*y

x = x / y x /= y
Incrementing and Decrementing
x + + i n c r e m e n t s t h e va l u e o f x b y 1 j u s t a s i f yo u h a d u s e d t h e e x p r e s s i o n x = x + 1 .
Si m i l a rl y x -- d e c re m e n t s t h e va l u e o f x b y 1 .

SJBIT, Dept. of ISE

Page 6

Java and J2EE (06IS753)

Ex e rc i se : wri t e t h e d if fe re nce b e t we e n :
y = x++;
y

= ++x;

Comparison operators.
Operator Meaning

Example

==

x == 3

Equal

!=
<
>
<=

N o t equal
x
Le ss t ha n
!x=<
3
G re a te r t ha n
x>
3
3
Le ss tha n or e q ua l x
to
<=
>= Grea ter tha n o r e qua l t o x3 >= 3 Logical
Operators
x E x p r e s s i o n s t h a t r e s u l t i n b o o l e a n va l u e s ( f o r e x a m p l e , t h e c o m p a r i s o n o p e r a t o r s ) c a n
be c o mbi ne d b y usi n g lo gic a l o pe ra to rs t ha t re p re se nt t he lo gic a l c omb ina t io ns
x A N D, OR, X OR, a nd logi c a l N OT.
x F o r A ND c o mb ina ti o ns, use e it he r t he & o r &&. T he e xp re s sio n w ill be t rue onl y if
b ot h e xp re s si ons a re a lso t r ue
x F o r O R e x p r e s s i o n s , u s e e i t h e r | o r | |. O R e x p r e s s i o n s r e s u l t i n t r u e i f e i t h e r o r b o t h o f
t he ope ra n ds is a l so t rue
x I n a d dit io n, the re is the X OR o pe ra t o r ^, w hic h re tu r ns t rue o nl y if i ts o pe ra nd s a re
d i f f e re n t ( o n e t r u e a n d o n e f a l s e , o r v i c e v e rs a ) a n d f a l s e o t h e r wi s e ( e v e n i f b o t h a re
t r ue ).
x I n ge n e r a l , o n l y t h e & & a n d | | a r e c o m m o n l y u s e d a s a c t u a l l o g i c a l c o m b i n a t i o n s . & , |,
a n d ^ a re mo re c omm onl y use d f or b it wise lo gic a l o pe ra t io ns.
x F o r N O T , u s e t h e ! o p e r a t o r w i t h a s i n gl e e x p r e s s i o n a r g u m e n t . T h e va l u e o f t h e N O T
e x p r e s s i o n i s t h e n e ga t i o n o f t h e e x p r e s s i o n ; i f x i s t r u e , ! x i s f a l s e .
Bitwise Operators

These are used to perform operations on individual bits in integers.


Operator Meaning
&

Bi t wise A N D

Bi t wise O R

Bi t wise X OR

SJBIT, Dept. of ISE

Page 7

Java and J2EE (06IS753)


<<

Le f t shif t

>>

Ri gh t shif t

>>>

Ze r o f ill r i ght sh if t

Bi t wise c om ple me nt

<<=

Le f t shif t a s si gnme nt ( x = x < < y)

>>=

R i gh t shif t a ssi gnme nt (x = x > > y)

> > > = Ze r o f i l l r i gh t s h i f t a s s i gn m e n t ( x = x > > > y ) x & = y


A N D a ss i gnme n t (x = x & y)
x |= y

O R a ssi gn me nt (x + x | y)

x^= y

X O R assi gnme nt ( x = x ^ y)

Oper ator Prece de nce


O p e ra t o r p re c e d e n c e d e t e rm i n e s t h e o r d e r i n w h i c h e x p r e s s i o n s a re e v a l u a t e d . T h i s , i n
s ome c a se s, c a n de te rm ine the o ve ra ll va lue o f the e xp re s si on. F or e xa mp le , ta ke the
f o llo wi n g e x p re ss io n:
y=6+4/2
D e p e n d i n g o n w h e t h e r t h e 6 + 4 e x p re s s i o n o r t h e 4 / 2 e x p re s s i o n i s e v a l u a t e d f i r s t , t h e
v a l u e o f y c a n e n d u p b e i n g 5 o r 8 . I n g e n e r a l , i n c r e m e n t a n d d e c r e m e n t a r e e va l u a t e d
b e f o r e a r i t h m e t i c , a r i t h m e t i c e x p r e s s i o n s a r e e va l u a t e d b e f o r e c o m p a r i s o n s , a n d
c o m p a r i s o n s a r e e va l u a t e d b e f o r e l o g i c a l e x p r e s s i o n s . A s s i g n m e n t e x p r e s s i o n s a r e
e va l u a t e d l a s t .
1.4 Arrays
A r r a y s i n J a v a a re a c t u a l o b j e c t s t h a t c a n b e p a s s e d a r o u n d a n d t re a t e d j u s t l i k e o t h e r
o bj ects.
A r r a y s a r e a w a y t o s t o r e a l i s t o f i t e m s . E a c h s l o t o f t h e a r r a y h o l d s a n i n d i vi d u a l
e le me nt, a nd yo u c a n pl a c e e le me n ts in t o o r c h a n ge the c o nte nt s o r th o se sl ot s a s yo u
ne e d to.
T h re e ste p s to c re a te a n a r ra y:
1.

D e c l a r e a va r i a b l e t o h o l d t h e a r r a y.

SJBIT, Dept. of ISE

Page 8

Java and J2EE (06IS753)


2.

C r e a t e a n e w a r r a y o b j e c t a n d a s s i g n i t t o t h e a r r a y va r i a b l e .

3.

S t o re thi n gs in tha t a rra y.

E . g.
St ri n g[ ] n a m e s ;
names = new String[10];
n a me s [ 1 ] =
n1 ;
n a m e s [ 2] =
n2;
...
1. 4.1 Multidime nsional Arrays
Java does not support multidimensional arrays. However, you can declare and create an
a r r a y o f a r r a y s ( a n d t h o s e a r r a y s c a n c o n t a i n a r r a ys , a n d s o o n , f o r h o w e v e r m a n y
d i m e n s i o n s yo u n e e d ) , a n d a c c e s s t h e m a s y o u w o u l d C - s t y l e m u l t i d i m e n s i o n a l a r r a y s :
i n t c o o r d s [ ] [ ] = n e w i nt [ 1 2 ] [ 1 2 ] ;
c oord s[ 0] [ 0] = 1; c oords[ 0] [ 1] = 2;
1. 5 Control State ment
1. 5.1 if Conditionals
x T he if c on diti ona l, wh ic h e na b le s you to e xe c u te d if f e re n t bi ts of c ode ba se d o n a
s i m p l e t e s t i n J a v a , i s ne a r l y i d e n t i c a l t o i f s t a t e m e n t s i n C .
x if c o ndi tio na l s c o nta i n t he ke ywo r d if , f oll owe d b y a bo ole a n te s t, f oll o we d b y a
s ta teme n t ( of te n a bloc k s ta te me n t ) to e xe cute if the te s t is tr ue :
x if ( x < y)
S y s t e m . o u t . p r i n t l n ( " x i s s m a l l e r t h a n y" ) ;
A n o p t i o n a l e l s e k e y w o r d p r o vi d e s t h e s t a t e m e n t t o e x e c u t e i f t h e t e s t i s f a l s e :
if ( x < y)
System.out.println(" x is smaller than y" ); el se
S y s t e m . o u t . p r i n t l n (" y i s b i g g e r" ) ;

1. 5.2 T he Condi ti onal O perator


A n a l t e r n a t i v e t o u s i n g t h e i f a n d e l s e k e y w o rd s i n a c o n d i t i o n a l s t a t e m e n t i s t o u s e t h e
c o nd iti ona l o pe ra to r, some t ime s c a lle d the te r na r y o pe ra to r.
SJBIT, Dept. of ISE

Page 9

Java and J2EE (06IS753)

T he c on dit io na l ope r ato r is a te rn ary ope ra tor be c a u se it ha s th re e te rm s.

Synta x : te st ? true re sul t : fa lse re sult


T h e t e s t i s a n e x p re s s i o n t h a t re t u r n s t r u e o r f a l s e , j u s t l i k e t h e t e s t i n t h e i f s t a t e m e n t . If
t h e t e s t i s t r u e , t h e c o n d i t i o n a l o p e r a t o r r e t u r n s t h e va l u e o f t r u e r e s u l t ; i f i t ' s f a l s e , i t
r e t u r n s t h e v a l u e o f f a l s e r e s u l t . Fo r e x a m p l e , t h e f o l l o w i n g c o n d i t i o n a l t e s t s t h e v a l u e s o f
x and y, returns the smaller of t he two, and as sign s t hat val ue to the va ria ble smal ler:
i n t s m a l l e r = x < y ? x : y;
T h e c o n d i t i o n a l o p e r a t o r h a s a ve r y l o w p r e c e d e n c e ; t h a t i s , i t ' s u s u a l l y e v a l u a t e d o n l y
after all its subexpressions are evaluated. The only operators lower in precedence are the
a s si gnme nt o pe ra t o rs. .
1. 5.3 switch Conditionals
T h i s i s t h e s w i t c h o r c a s e s t a t e m e n t ; i n J a va i t ' s s w i t c h a n d b e h a ve s a s i t d o e s i n C :
switch
(test)
va l ue One :

c a se

resultOne;
break;
c a se va l ue Two:
resultTwo;
break;
c a se va l u e T h re e :
resultThree;
break; . . .
de fa ult: def a ult re sult ;
}
In the switch statement, the test (a primitive type of byte, char, short, or int) is compared
w i t h e a c h o f t h e c a s e v a l u e s i n t u rn . If a m a t c h i s f o u n d , t h e s t a t e m e n t , o r s t a t e m e n t s a f t e r
t h e t e s t i s e x e c u t e d . If n o m a t c h i s f o u n d , t h e d e f a u l t s t a t e m e n t i s e x e c u t e d . Th e d e f a u l t i s
o pt io na l, s o if t he re is n' t a ma tc h i n a n y of the c a se s a nd de f a ult d oe sn 't e x ist, the s witc h
s t a t e m e n t c o m p l e t e s w i t h o u t d o i n g a n y t h i n g.

SJBIT, Dept. of ISE

Page 10

Java and J2EE (06IS753)


1. 5.4 for Loops

T he f o r lo op, a s i n C, r e pe a t s a sta te me n t o r b loc k of sta te me nts some nu mbe r of time s


u nt il a c o ndi tio n is ma tc he d. f o r lo op s a re f re q ue n tl y u se d f o r sim ple ite ra ti on in w hic h
y o u r e p e a t a b l o c k o f s t a t e m e n t s a c e rt a i n n u m b e r o f t i m e s a n d t h e n s t o p , b u t y o u c a n u s e
f o r lo op s f or j ust a b ou t a n y ki nd of lo op.
T h e f o r l o o p i n J a va l o o k s r o u g h l y l i k e t h i s :
f o r ( i n i ti a l i z a t i o n ; te s t ; i n c re me n t ) { s t a t e m e n t s ;
}
T he sta rt of the f o r lo op ha s t hre e pa rt s:
x I n i t i a l i z a t i o n i s a n e x p r e s s i o n t h a t i n i t i a l i z e s t h e s t a r t o f t h e l o o p . I f yo u h a ve a l o op
i n d e x , t h i s e x p re s s i o n m i g h t d e c l a re a n d i n i t i a l i ze i t , f o r e x a m p l e , i n t i = 0 . V a ri a b l e s t h a t
y o u d e c l a re i n t h i s p a r t o f t h e f o r l o o p a re l o c a l t o t h e l o o p i t s e l f ; t h e y c e a s e e x i s t i n g a f t e r
t h e l o o p i s f i n i s h e d e x e c u t i n g. T e s t i s t h e t e s t t h a t o c c u r s a f t e r e a c h p a s s o f t h e l o o p .
T h e t e s t m u s t b e a b o o l e a n e x p r e s s i o n o r f u n c t i o n t h a t r e t u r n s a b o o l e a n va l u e , f o r
e x a m p l e , i < 1 0 . If t h e t e s t i s t r u e , t h e l o o p e x e c u t e s . O n c e t h e t e s t i s f a l s e , t h e l o o p
s to ps e xe c u tin g
I n c r e m e n t i s a n y e x p r e s s i o n o r f u n c t i o n c a l l . C o m m o n l y, t h e i n c r e m e n t i s u s e d t o
c ha n ge t he va l ue of t he l o o p in de x to b r i n g t he s t a te of t he lo o p c lo se r t o r e t u r ni n g f a l s e
a n d c o m p l e t i n g.
T he sta te me nt pa rt of the f o r l oo p i s t he sta te me nts tha t a re e xe c ute d e a c h ti me t he l oo p
i te ra te s. Ju st a s wit h if , you c a n i nc l ude e i the r a sin gle sta te me nt he r e o r a bl oc k ; t he
p r e v i o u s e x a m p l e u s e d a b l o c k b e c a u s e t h a t i s m o re c o m m o n . He re ' s a n e x a m p l e o f a f o r
l o o p t h a t i n i t i a l i z e s a l l t h e va l u e s o f a S t r i n g a r r a y t o n u l l s t r i n gs :
String strArray[] = new String[10]; in t
i ; // loo p in dex
for (i = 0; i < strArray. length; i++)
s t r A r r a y[ i ] = " " ;
1. 5.5 while and do Loops
F i n a l l y , t h e re a re w h i l e a n d d o l o o p s . wh i l e a n d d o l o o p s , l i k e f o r l o o p s , e n a b l e a b l o c k o f
Ja va c o de t o be e xe c ute d re pe a te d l y un til a spe c if ic c on dit io n is me t. W he the r you u se a
f o r l o o p , a w h i l e , o r a d o i s m o s t l y a m a t t e r o f y o u r p r o g r a m m i n g s t y l e . w hile a n d d o
l o o p , a re e x a c t l y t h e s a m e a s i n C a n d C + + e x c e p t t h e i r t e s t c o n d i t i o n m u s t b e a b o o l e a n .
1. 5.6 while Loops
SJBIT, Dept. of ISE

Page 11

Java and J2EE (06IS753)

T h e w h i l e l o o p i s u s e d t o r e p e a t a s t a t e m e n t o r b l o c k o f s t a t e m e n t s a s l o n g a s a p a rt i c u l a r
c o nd iti on is t r ue . w hile l oo ps l oo k like th is:

w h i l e (c o n d i t i o n )
b o d yOf Loo p; }

T h e c o n d i t i o n i s a b o o l e a n e x p re s s i o n . If i t re t u r n s t ru e , t h e w h i l e l o o p e x e c u t e s t h e
s t a t e m e n t s i n b o d y O f L o o p a n d t h e n t e s t s t h e c o n d i t i o n a ga i n , r e p e a t i n g u n t i l t h e
c o nd iti on is f alse :
i nt c ou nt = 0;
while ( count < array 1 .length && array 1 [count] !=0) {
a rra y2[ c ou nt ] = (f l oa t ) a rra y1[ c ou nt + +] ;
}
1. 5.7 do...while Loops
The do loop is j ust like a while loop, except that do executes a given statement or block
u nt il the c on di tio n is f a lse . The ma i n dif f e re nc e is t ha t wh ile lo op s te st t he c on diti on
b e f o r e l o o p i n g, m a k i n g i t p o s s i b l e t h a t t h e b o d y o f t h e l o o p w i l l n e v e r e x e c u t e i f t h e
c on d iti o n is f a lse t he f ir s t t ime i t' s te ste d. do lo o p s r u n the bo d y of t he l oo p a t le a st on c e
be f o re te sti n g the c o ndit io n. do loo ps l oo k like t his :
do {
b o d yOf Loo p;
} wh ile ( c o n d i t i o n ) ;
H e re , the b od yOf Lo op pa rt i s the sta te me nt s tha t a re e xe c u te d w ith e a c h
i nt x = 1 ;
do {
System.out.println(" Looping, round " + x); x ++;
} wh ile ( x < = 10 );
H e re 's t he out pu t of the se s ta te me n ts:
L o o p i n g, r o u n d 1 L o o p i n g, r o u n d 2 L o o p i n g, r o u n d 3 L o o p i n g, r o u n d 4 L o o p i n g, r o u n d 5
L o o p i n g, r o u n d 6
L o o p i n g, r o u n d Lo o p i n g, r o u n d Lo o p i n g, r o u n d L o o p i n g , r o u n d
SJBIT, Dept. of ISE

Page 12

Java and J2EE (06IS753)

UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS

Classes:

Classes in Java; Declaring a class; Class name; Super classes; Constructors; Creating instances of
class; Inner classes. Inheritance: Simple, multiple, and multilevel inheritance; Overriding,
overloading.
x

Exception handling: Exception handling in Java.

The Applet Class:

Two types of Applets; Applet


basics; Applet Architecture; An Applet skeleton; Simple Applet display methods; Requesting
repainting; Using the Status Window; The HTML APPLET tag; Passing parameters to Applets;
getDocumentbase() and getCodebase(); ApletContext and showDocument(); The AudioClip
Interface; The AppletStub Interface; Output to the Console.

SJBIT, Dept. of ISE

Page 13

Java and J2EE (06IS753)

2.1. Defining Classes, Class Name


To define a class, use the class keyword and the name of the class:

class MyClassName {
... }
If this class is a subclass of another class, use extends to indicate the superclass of this

class:
class myClassName extends mySuperClassName {
...
}
x If this class implements a specific interface, use implements to refer to that interface: class
MyRunnableClassName implements Runnable {
...
}
Super Classes
x Each class has a superclass (the class above it in the hierarchy), and each class can have one
or more subclasses (classes below that class in the hierarchy). Classes further down in the
hierarchy are said to inherit from classes further up in the hierarchy.
x Subclasses inherit all the methods and variables from their superclassesthat is, in any
particular class, if the superclass defines behavior that your class needs, you don't have to
redefine it or copy that code from some other class. Your class automatically gets that
behavior from its superclass, that superclass gets behavior from its superclass, and so on all
the way up the hierarchy.
x At the top of the Java class hierarchy is the class Object; all classes inherit from this one
superclass. Object is the most general class in the hierarchy; it defines behavior inherited by
all the classes in the Java class hierarchy. Each class farther down in the hierarchy adds more
information and becomes more tailored to a specific purpose.
E.g.
public class HelloAgainApplet extends java.applet.Applet { }

SJBIT, Dept. of ISE

Page 14

Java and J2EE (06IS753)

2.2 Constructors, Creating instances of a class

The following example demonstrates the creation of classes, creating objects and the usage of
constructors
class Motorcycle { }
create some instance variables for this class
String make; String color; boolean engineState;
Add some behavior (methods) to the class.
void startEngine() {
if (engineState == true)
System.out.println("The engine is already on."); else {
engine State = true;
System.out.println("The engine is now on."); }
}
The program looks like this now :
class Motorcycle {
String make;
String color;

engine is already
on.");
engine
on.");

is

now

boolean engineState;
void startEngine() {

if (engineS tate == true)


System.out.println("The
else {

gientehSotdatp
e rints t=he currtreunet ;values of the instance variables in an instance of your
The showAttesnm
rihnatltni(t"lTohoeks}like:
Motorcycle cSlayssste. m
H.eoruet's.pw
void showAt}ts() {
System. out .println ("This motorcycle is a " + color + " " + make);
if (engineState == true)
System.out.println("The engine is on."); else System.out.println("The engine is off.");

SJBIT, Dept. of ISE

Page 15

Java and J2EE (06IS753)

The showAtts method prints two lines to the screen: the make and color of the motorcycle
object, and whether or not the engine is on or off.
2.2.1 Add the main method

public static void main (String args[]) { Motorcycle m = new Motorcycle(); m.make = "Yamaha
RZ350";
m.color = "yellow";
System.out.println("Calling showAtts..."); m.showAtts(); System.out.println("
"); System.out.println("Starting
engine..."); m.startEngine();
System.out.println("");
System.out.println("Calling showAtts..."); m.showAtts(); System.out.println("
"); System.out.println("Starting
engine..."); m.startEngine();
}
With the main() method, the Motorcycle class is now an application, and you can compile it
again and this time it'll run. Here's how the output should look:
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350 The engine is off.
Starting engine... The engine is now on.
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350 The engine is on.
Starting engine...
The engine is already on.
2.3. Inheritance
Inheritance is a powerful mechanism that means when you write a class you only have to
specify how that class is different from some other class; inheritance will give you automatic
access to the information contained in that other class.
With inheritance, all classesthose you write, those from other class libraries that you use, and
those from the standard utility classes as wellare arranged in a strict hierarchy

SJBIT, Dept. of ISE

Page 16

Java and J2EE (06IS753)

2.3.1 Single and Multiple Inheritance

Single inheritance means that each Java class can have only one superclass (although any given
superclass can have multiple subclasses).
In other object-oriented programming languages, such as C++, classes can have more than one
superclass, and they inherit combined variables and methods from all those classes. This is
called multiple inheritance.
Multiple inheritance can provide enormous power in terms of being able to create classes that
factor just about all imaginable behavior, but it can also significantly complicate class
definitions and the code to produce them. Java makes inheritance simpler by being only
singly inherited.
2.3.2 Overriding Methods
x When a method is called on an object, Java looks for that method definition in the class of
that object, and if it doesn't find one, it passes the method call up the class hierarchy until a
method definition is found.
x Method inheritance enables you to define and use methods repeatedly in subclasses without
having to duplicate the code itself.
x However, there may be times when you want an object to respond to the same methods but
have different behavior when that method is called. In this case, you can override that
method. Overriding a method involves defining a method in a subclass that has the same
signature as a method in a superclass. Then, when that method is called, the method in the
subclass is found and executed instead of the one in the superclass.
2.3.3 Creating Methods that Override Existing Methods
To override a method, all you have to do is create a method in your subclass that has the same
signature (name, return type, and parameter list) as a method defined by one of your class's
superclasses. Because Java executes the first method definition it finds that matches the
signature, this effectively "hides" the original method definition. Here's a simple example
The PrintClass class.
class PrintClass {
int x = 0; int y = 1;
void printMe() {
System.out.println("X is " + x + ", Y is " + y);
System.out.println("I am an instance of the class " +
this.getClass().getName());
SJBIT, Dept. of ISE

Page 17

Java and J2EE (06IS753)

Create a class called PrintSubClass that is a subclass of (extends) PrintClass.


class PrintSubClass extends PrintClass { int z = 3;
public static void main(String args[]) { PrintSubClass obj = new PrintSubClass(); obj
.printMe();
}
}
Here's the output from PrintSubClass:
X is 0, Y is 1
I am an instance of the class PrintSubClass
In the main() method of PrintSubClass, you create a PrintSubClass object and call the printMe()
method. Note that PrintSubClass doesn't define this method, so Java looks for it in each of
PrintSubClass's superclassesand finds it, in this case, in PrintClass. because printMe() is still
defined in PrintClass, it doesn't print the z instance variable.
To call the original method from inside a method definition, use the super keyword to pass the
method call up the hierarchy:
void myMethod (String a, String b) { // do stuff here
super.myMethod(a, b);
// maybe do more stuff here }
The super keyword, somewhat like the this keyword, is a placeholder for this class's superclass.
You can use it anywhere you can use this, but to refer to the superclass rather than to the current
class.

2.4 Exception handling


An exception is an event that occurs during the execution of a program that disrupts the normal
flow of instructions.
2.4.1 The Three Kinds of Exceptions
x Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are
checked exceptions, except for those indicated by Error, RuntimeException, and their
subclasses.
x Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions
indicated by Error and its subclasses.
x Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime
exceptions are those indicated by Runtime Except ion and its subclasses.
SJBIT, Dept. of ISE

Page 18

Java and J2EE (06IS753)

Valid Java programming language code must honor the Catch or Specify Requirement. This
means that code that might throw certain exceptions must be enclosed by either of the
following:

A try statement that catches the exception. The try must provide a handler for the exception,
as described in Catching and Handling Exceptions.
A method that specifies that it can throw the exception. The method must provide a throws
clause that lists the exception, as described in Specifying the Exceptions Thrown by a Method.
Code that fails to honor the Catch or Specify Requirement will not compile.
This example describes how to use the three exception handler components the try, cat ch,
and finally blocks
2.4.2 try block
The first step in constructing an exception handler is to enclose the code that might throw an
exception within a try block. In general, a try block looks like the following.
try {
code
}
catch and finally blocks . . .
Example :
private Vector vector;
private static final int SIZE = 10;
PrintWriter out = null;
try {
System.out.println("Entered try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + vector.elementAt(i));
}
}
The catch Blocks

SJBIT, Dept. of ISE

Page 19

Java and J2EE (06IS753)

You associate exception handlers with a try block by providing one or more catch blocks
directly after the try block. No code can be between the end of the try block and the beginning
of the first catch block.
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
Each catch block is an exception handler and handles the type of exception indicated by its
argument
finally block

The runtime system always executes the statements within the finally block regardless of what
happens within the try block. So it's the perfect place to perform cleanup.
The following finally block for the write Li st method cleans up and then closes the PrintWriter.
finally {
if (out != null) {
System.out.println("Closing PrintWriter"); out . close();
} else {
System.out.println("PrintWriter not open"); }
}
2.5 The Applet Class
Applet Basics
x An applet is a special kind of Java program that a browser enabled with Java technology can
download from the internet and run.
x An applet is typically embedded inside a web-page and runs in the context of the browser.
x An applet must be a subclass of the java.applet.Applet class, which provides the standard
interface between the applet and the browser environment.
x Simple example :
public class HelloWorld extends java.applet.Applet {
public void paint(java.awt.Graphics g) {
SJBIT, Dept. of ISE

Page 20

Java and J2EE (06IS753)

g.drawString("Hello World!",50,25); System.out.println("Hello World!");


}
}
An applet can be included in an HTML page, much in the same way an image is included in a
page.
When Java technology enabled Browser is used to view a page that contains an applet, the
applet's code is transferred to your system and executed by the browser's Java Virtual Machine
(JVM)
Two Types of Applets
1 .Local applet - operate in single machine browser which is not connected in network,
2.Remote applet - remote applet operate over internet via network.
Applet Architecture
Event driven :
An applet waits until an event occurs.
The AWT notifies the applet about an event by calling event handler that has been provided by
the applet.
The applet takes appropriate action and then quickly return control to AWT All Swing
components descend from the AWT Container class
User initiates interaction with an Applet (and not the other way around) An Applet Skeleton
import java.awt.*;
import javax.swing.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends JApplet { // Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */

SJBIT, Dept. of ISE

Page 21

Java and J2EE (06IS753)


public void start() {

// start or resume execution


}
// Called when the applet is stopped. public void stop () {
// suspends execution
}
/* Called when applet is terminated. This is the last
method executed. */
public void destroy() {
// perform shutdown activities }
// Called when an applet's window must be restored. public void paint(Graphics g) {
// redisplay contents of window
}
}
5.1 Simple Applet Display Methods
void drawstring(String message, int x, int y) - void setBackground(Color newColor) void
setForeground(Color newColor) Example :
public class SimpleApplet extends Applet { public void paint (Graphics g) {
g.drawString("First Applet", 50, 50 ); }
}
Requesting Repainting
repaint( ) function is called when you have changed something and want your changes to show
up on the screen
repaint( ) is a request--it might not happen
When you call repaint( ), Java schedules a call to update(Graphics g)
Here's what update does:
public void update(Graphics g) {
// Fills applet with background color, then
SJBIT, Dept. of ISE

Page 22

Java and J2EE (06IS753)


paint(g);

Using The Status Window


Syntax : public void showStatus(String status)
Parameters:
status - a string to display in the status window.
Requests that the argument string be displayed in the "status window".
Many browsers and applet viewers provide such a window, where the application can inform
users of its current state.
Example :
import java.applet. *; import java.awt.*;
public class NetExample extends Applet
{
private AppletContext browser = null;
private Button showStatus = new Button("Show Status"); public void init()
{
Panel panel = new Panel();
panel.setLayout(new GridLayout(1 ,2));
panel.add(showStatus);
setLayout(new BorderLayout()); add("South", panel);
browser = getAppletContext(); }
public boolean action(Event e, Object o)
{
if (e.target == showStatus)
browser.showStatus("Here is something for your status line ..."); return true;
}
}
2.5 The HTML Applet Tag

SJBIT, Dept. of ISE

Page 23

Java and J2EE (06IS753)


x

The APPLET tag is used to start an applet from both an HTML document and from an
applet viewer.

An applet viewer will execute each APPLET tag that it finds in a separate window,while
web browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many
applets on a single page.

The syntax for the standard APPLET tag is shown here. Bracketed items are optional.

< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alte rnate Text]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = Attribute Value>] [< PARAM NAME =
AttributeName2 VALUE = Attribute Value>] . . .
[HTML Displayed in the absence of Java]
</APPLET>
x CODEBASE is an optional attribute that specifies the base URL of the applet code, which
is the directory that will be searched for the applets executable class file (specified by the
CODE tag). The HTML documents URL directory is used as the CODEBASE if this
attribute is not specified. The CODEBASE does not have to be on the host from which the
HTML document was read.
x CODE is a required attribute that gives the name of the file containing your applets
compiled .class file. This file is relative to the code base URL of the applet, which is the
directory that the HTML file was in or the directory indicated by CODEBASE if set.
x ALT is an optional attribute used to specify a short text message that should be displayed if
the browser understands the APPLET tag but cant currently run Java applets. This is
distinct from the alternate HTML you provide for browsers that dont support applets.
x WIDTH AND HEIGHT are required attributes that give the size (in pixels) of the applet
display area.

SJBIT, Dept. of ISE

Page 24

Java and J2EE (06IS753)

x ALIGN is an optional attribute that specifies the alignment of the applet. This attribute is
treated the same as the HTML IMG tag with these possible values:
x LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and
ABSBOTTOM.
VSPACE AND HSPACE These attributes are optional. VSPACE specifies the space, in
p i x e l s , a b o ve a n d b e l o w t h e a p p l e t . H S P A C E s p e c i f i e s t h e s p a c e , i n pi x e l s , o n e a c h
s i d e o f t h e a p p l e t . T h e y r e t r e a t e d t h e s a m e a s th e I M G t a g s V S P A C E a n d H S P A C E
att r ib utes.
PARAM NAME AND VALUE The PARAM ta g all o ws you to s pecify ap plet specific
a rgumen ts in an HTM L pa ge. Applet s access thei r att ri bute s wit h the getParameter( )
met ho d.

Passing Parameters to Applets


P a ra m e t e r s a re p a s s e d t o a p p l e t s i n N AM E = V ALU E p a i r s i n < P A R A M > t a g s b e t we e n t h e
o pen in g a nd clo sin g A P P L E T t a gs.
I n s i d e t h e a p p l e t , yo u r e a d t h e va l u e s p a s s e d t h r o u g h t h e P A R A M t a gs w i t h t h e
ge t Pa r a m e t e r ( ) me th od of t he j a va . a p p l e t . A p p l e t c la ss.
T h e a p p l e t p a r a m e t e r " M e s s a ge " i s t h e s t r i n g t o b e d r a w n .
import java.applet. *; im po rt
j a va . a w t . * ;
public class DrawStringApplet extends Applet { p ri va te
S t ri n g de f a ult Me ssa ge = " He llo !" ; pu blic voi d
pa int ( G ra p hic s g) {
S t r i n g i n p u t F r o m P a ge = t h i s . ge t P a r a m e t e r ( " M e s s a g e " ) ;
i f ( i n p u t F r o m P a g e = = n u l l ) i n p u t F r o m P a g e = d e f a u l t M e s s a ge ;
g . d ra w St ri n g ( i n p u t F r o m Pa g e , 5 0 , 2 5 );
}
}
H T M L f i l e t h a t r e f e r e n c e s t h e a b o ve a p p l e t .
< H T M L> <H E AD >
< T I T LE > D ra w S tr in g < / T IT LE >
< / HE A D >
SJBIT, Dept. of ISE

Page 25

Java and J2EE (06IS753)


< B O DY >

T hi s is the ap plet: <P>


< A P P L E T c o d e = " D r a w S t r i n g A p p l e t" w i d t h = " 3 0 0" h e i g h t = " 5 0" >
<PARAM name="Message" value="Howdy, there!"> This page will be very boring if your
browser doesn't understand Java.
</APPLET>
</BODY> </HTML>
getDocumentBase() and getCodeBase()
Syntax : public URL getDocumentBase()
Returns:
the URL of the document that contains this applet.
x

Gets the URL of the document in which this applet is embedded.

For example, suppose an applet is contained within the document:


http://java.sun.com/products/jdk/1.2/index.html

The document base is:


http://java.sun.com/products/jdk/1.2/index.html
Syntax : public URL getCodeBase()
Returns:
the base URL of the directory which contains this applet.

Gets the base URL. This is the URL of the directory which contains this applet.

Example segments:

URL codeBase = getCodeBase();


Image myImage = getImage(codeBase, "images/myimage.gif"); Applet Context and
showDocument()
AppletContext is an interface that provides the means to control the browser environment in
which the applet is running.
The AudioClip Interface
x

The AudioC lip interface is a simple abstraction for playing a sound clip.

Multiple Audi oC lip items can be playing at the same time, and the resulting sound is
mixed together to produce a composite.

SJBIT, Dept. of ISE

Page 26

Java and J2EE (06IS753)


x

It has the following methods :

play
public abstract void play()

loop

Starts playing this audio clip. Each time this method is called, the
clip is restarted from the beginning.

stop

public abstract void loop()

public abstract voSitdarsttsopp(la) ying this audio clip in a loop.


Stops playing this audio clip.
The AppletStub Interface
The AppletStub interface provides a way to get information from the run-time browser
environment.
The Applet class provides methods with similar names that call these methods. Methods
public abstract boolean isActive ()
The isActive() method returns the current state of the applet. While an applet is initializing, it is
not active, and calls to isActive() return false. The system marks the applet active just prior to
calling start(); after this point, calls to isActive() return true.
x public abstract URL getDocumentBase ()
The getDocumentBase() method returns the complete URL of the HTML file that loaded the
applet. This method can be used with the getImage() or getAudioClip() methods to load an
image or audio file relative to the HTML file.
x public abstract URL getCodeBase ()
The getCodeBase() method returns the complete URL of the .class file that contains the applet.
This method can be used with the getImage() method or the getAudioClip() method to load an
image or audio file relative to the .class file.
x public abstract String getParameter (String name)
The getParameter() method allows you to get parameters from <PARAM> tags within the
<APPLET> tag of the HTML file that loaded the applet. The name parameter of getParameter()
must match the name string of the <PARAM> tag; name is case insensitive. The return value of
getParameter() is the value associated with name; it is always a String regardless of the type of
data in the tag. If name is not found within the <PARAM> tags of the <APPLET>,
getParameter() returns null.
x public abstract AppletContext getAppletContext ()
The getAppletContext() method returns the current AppletContext of the applet. This is part of
the stub that is set by the system when setStub() is called.
SJBIT, Dept. of ISE

Page 27

Java and J2EE (06IS753)

x public abstract void appletResize (int width, int height)

The appletResize() method is called by the resize method of the Applet class. The method
changes the size of the applet space to width x height. The browser must support changing the
applet space; if it doesn't, the size remains unchanged
Output To the Console
The drawString method can be used to output strings to the console. The position of the text can
also be specified.
The following prog shows this concept:
public class ConsolePrintApplet1 extends java.applet.Applet
{
public void init () {
// Put code between this line
double x = 5.0; double y = 3.0;
System.out.println( "x * y = "+ (x*y) );
System.out.println( "x / y = "+ (x/y) );
// // and this line.
}
// Paint message in the applet window. Public

SJBIT, Dept. of ISE

Page 28

Java and J2EE (06IS753)

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING

Multi Threaded Programming:


What are threads? How to make the classes threadable; Extending threads; Implementing
runnable; Synchronization; Changing state of the thread; Bounded buffer problems, read-write
problem, producer-consumer problems.
Event Handling:
Two event handling mechanisms; The delegation event model; Event classes; Sources of events;
Event listener interfaces; Using the delegation event model; Adapter classes; Inner classes.

SJBIT, Dept. of ISE

Page 29

Java and J2EE (06IS753)

3.1 What are Threads?

A thread is a single path of execution of code in a program.


x A Multithreaded program contains two or more parts that can run concurrently.
x Each part of such a program is called a Thread.
x Each thread defines a separate path of execution. Multithreading is a specialized form
of Multitasking.
3.1 How to make the classes threadable
A class can be made threadable in one of the following ways
(1) implement the Runnable Interface and apply its run() method.
(2) extend the Thread class itself.
1. Implementing Runnable Interface: The easiest way to create a thread is to create a class
that implements the Runnable interface. To implement Runnable, a class need only
implement a single method called run().
The Format of that function is public void run().
2. Extending Thread: The second way to create a thread is to create a new class that extends
the Thread class and then to create an instance of this class. This class must override the
run() method which is the entry point for the new thread.
1.2 Extending Threads
You can inherit the Thread class as another way to create a thread in your program. When
you declare an instance of your class, youll also have access to members of the Thread
class. Whenever your class inherits the Thread class, you must override the run() method,
which is an entry into the new thread. The following example shows how to inherit the
Thread class and how to override the run() method. This example defines the MyThread
class, which inherits the Thread class. The constructor of the MyThread class calls the
constructor of the Thread class by using the super keyword and passes it the name of the
new thread, which is My thread. It then calls the start() method to activate the new thread.
The start() method calls the run() method of the MyThread class
class MyThread extends Thread {
MyThread() {
super("My thread");
start();
}
SJBIT, Dept. of ISE

Page 30

Java and J2EE (06IS753)

public void run() {

System.out.println("Child thread started");


System.out.println("Child thread terminated");
}}
class Demo {
public static void main (String args[]){ new
MyThread(); System.out.println("Main
thread started");
System.out.println("Main thread terminated");
}}
3.2 Implementing Runnable
The example in the next segment demonstrates the use of Runnable and its implementation.
Synchronization
1. Two or more threads accessing the same data simultaneously may lead to loss of data
integrity. In order to avoid this java uses the concept of monitor. A monitor is an object used as
a mutually exclusive lock.
2. At a time only one thread can access the Monitor. A second thread cannot enter the monitor
until the first comes out. Till such time the other thread is said to be waiting.
3. The keyword Synchronized is use in the code to enable synchronization and it can be used
along with a method.
Changing the state of thread
There might be times when you need to temporarily stop a thread from processing and then
resume processing, such as when you want to let another thread use the current resource. You
can achieve this objective by defining your own suspend and resume methods, as shown in the
following example. This example defines a MyThread class. The MyThread class defines three
methods: the run() method, the suspendThread() method, and the resumeThread() method. In
addition, the MyThread class declares the instance variable suspended, whose value is used to
indicate whether or not the thread is suspended.
class MyThread implements Runnable {
String name;
Thread t;
SJBIT, Dept. of ISE

Page 31

Java and J2EE (06IS753)


boolean suspended;

MyThread() {
t = new Thread(this, "Thread");
suspended = false ; t.start();
}
public void run() {
try {
for (int i = 0; i < 10; i++) { System.out.println("Thread: " + i ); Thread.sleep(200);
synchronized (this) {
while (suspended) {
wait();
}
}
}
} catch (InterruptedException e ) { System.out.println("Thread: interrupted."); }
System.out.println("Thread exiting.");
}
void suspendThread() { suspended = true;
}
synchronized void resumeThread() {
suspended = false;
notify();
}
}
class Demo {
public static void main (String args [] ) { MyThread t1 = new MyThread();
try{
Thread.sleep(1000);
Thread.sleep(1000);
SJBIT, Dept. of ISE

t1.suspendThread();

System.out.println("Thread:

Suspended");

Page 32

Java and J2EE (06IS753)

t1.resumeThread(); System.out.println("Thread: Resume");


} catch ( InterruptedException e) {
}
try {
t1.t.join();
} catch ( InterruptedException e) { System.out.println (
"Main Thread: interrupted"); }
}
}
3.3 Bounded Buffer Problem
Problem Description :
In computer science the producer-consumer problem (also known as the bounded-buffer
problem) is a classical example of a multi-process synchronization problem. The problem
describes two processes, the producer and the consumer, who share a
common, fixed-size buffer.
The producer's job is to generate a piece of data, put it into the buffer and start again. At the
same time the consumer is consuming the data (i.e. removing it from the buffer) one piece at a
time. The problem is to make sure that the producer won't try to add data into the buffer if it's
full and that the consumer won't try to remove data from an empty buffer. This is the code for
solving the above stated:
class BufferItem {
public volatile double value = 0; // multiple threads access public volatile boolean occupied =
false; // so make these `volatile' }
class BoundedBuffer { // designed for a single producer thread and // a single consumer thread
private int numSlots = 0;
private BufferItem[] buffer = null;
private int putIn = 0, takeOut = 0;
// private int count = 0;
public BoundedBuffer(int numSlots) {

SJBIT, Dept. of ISE

Page 33

Java and J2EE (06IS753)

if (numSlots <= 0) throw new IllegalArgumentException("numSlots<=0"); this.numSlots =


numSlots;
buffer = new BufferItem[numSlots];

for (int i = 0; i < numSlots; i++) buffer[i] = new BufferItem();


putIn = (putIn + 1) % numSlots;
// count++; // race condition!!! }
public double fetch() {
double value;
while (!buffer[takeOut].occupied) // busy wait Thread.currentThread().yield();
value = buffer[takeOut].value;

// C

buffer [takeOut] .occupied = false;


//

// D takeOut = (takeOut + 1) % numSlots;

count--; // race condition!!! return value;

}
}
Read-Write problem
x

Read/Write locks provides a synchronization mechanism that allow threads in an application to


more accurately reflect the type of access to a shared resource that they require.

Many threads can acquire the same read/write lock if they acquire a shared read lock on the
read/write lock object.

Only one thread can acquire an exclusive write lock on a read/write lock object.

When an exclusive write lock is held, no other threads are allowed to hold any lock.
public class Read WriteLock{
private int readers = 0;
private int writers = 0; private int writeRequests = 0;
public synchronized void lockRead() throws InterruptedException{ while(writers > 0 ||
writeRequests > 0){
wait();
}
readers++;

SJBIT, Dept. of ISE

Page 34

Java and J2EE (06IS753)


}

public synchronized void unlockRead(){ readers--;


notifyAll();
}
public synchronized void lockWrite() throws InterruptedException{
writeRequests++;
while(readers > 0 || writers > 0){ wait();
}
writeRequests--;
writers++;
}
public synchronized void unlockWrite() throws InterruptedException{ writers--;
notifyAll();
}
}
Producer-Consumer problems
x

In producer/consumer synchronizations, producer processes make items available to


consumer processes.

Examples are a message sender and a message receiver, or two machines working on items
in sequence.

The synchronization here must ensure that the consumer process does not consume more
items than have been produced. If necessary, the consumer process is blocked (must wait)
if no item is available to be consumed.

Producer and consumer processes are coupled by a buffer to allow asynchronous


production and consumption.

The buffer can be bounded (have a capacity limit) or unbounded (be able to store an
unlimited number of items).

3.4 Event Handling


In Java, events represent all activity that goes on between the user and the application.
SJBIT, Dept. of ISE

Page 35

Java and J2EE (06IS753)

Two event handling mechanisms :

Delegation event model : It defines standard and consistent mechanisms to generate and
process events. Here the source generates an event and sends it to on or more listeners. The
listener simply waits until it receives an event. Once it is obtained, It processes this event and
returns. Listeners should register themselves with a source in order to receive an even
notification. Notifications are sent only to listeners that want to receive them.
Events
In the delegation model, an event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a graphical user
interface. Some of the activities that cause events to be generated are : pressing a button,
entering a character via the keyboard, selecting an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a
software or hardware failure occurs, or an operation is completed.
Event Classes
The classes that represent events are at the core of Javas event handling mechanism.
EventObject : It is at the root of the Java event class hierarchy in java.util. It is the superclass
for all events. Its one constructor is shown here: EventObject(Object src) Here, src is the
object that generates this event. EventObject contains two methods: getSource( ) and toString(
). The getSource( ) method returns the source of the event.
EventObject is a superclass of all events.
The ActionEvent Class :
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu
item is selected. The ActionEvent class defines four integer constants that can be used to
identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK,
META_MASK, and SHIFT_MASK.
ActionEvent has these three constructors: ActionEvent(Object src,
int type, String cmd) ActionEvent(Object src, int type,
String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers) Here, src is a reference
to the object that generated this event. The type of the event is specified by type, and its
command string is cmd. The argument modifiers indicates which modifier keys (ALT, CTRL,
META, and/or SHIFT) were pressed when the event was generated. The when parameter
specifies when the event occurred
x The AdjustmentEvent Class An AdjustmentEvent is generated by a scroll bar
SJBIT, Dept. of ISE

Page 36

Java and J2EE (06IS753)

x The ComponentEvent Class A ComponentEvent is generated when the size,


position, or visibility of a component is changed. There are four types of component
events
x The ContainerEvent Class A ContainerEvent is generated when a component is
added to or removed from a container
x The FocusEvent Class : A FocusEvent is generated when a component gains or
loses input focus
x The InputEvent Class : The abstract class InputEvent is a subclass of
ComponentEvent and is the superclass for component input events. Its subclasses
are KeyEvent and MouseEvent.
x The ItemEvent Class : An ItemEvent is generated when a check box or a list item
is clicked or when a checkable menu item is selected or deselected
x The KeyEvent Class A KeyEvent is generated when keyboard input occurs.
x The MouseEvent Class There are eight types of mouse events
x The MouseWheelEvent Class The MouseWheelEvent class encapsulates a mouse
wheel event.
x The TextEvent Class Instances of this class describe text events. These are
generated

by text fields and text areas when characters are entered by a user or program.
x The WindowEvent Class There are ten types of window events. The WindowEvent
class defines integer constants that can be used to identify them.
Sources of Events
Event Source Description :
x Button - Generates action events when the button is pressed.
x Checkbox - Generates item events when the check box is selected or deselected.
x Choice - Generates item events when the choice is changed.
x List - Generates action events when an item is double-clicked; generates item events
x when an item is selected or deselected.
x Menu Item - Generates action events when a menu item is selected; generates item
events when a checkable menu item is selected or deselected.
SJBIT, Dept. of ISE

Page 37

Java and J2EE (06IS753)

x Scrollbar - Generates adjustment events when the scroll bar is manipulated.


x Text components - Generates text events when the user enters a character.
x Window - Generates window events when a window is activated, closed,
deactivated,

deiconified, iconified, opened, or quit.


Event Listener Interfaces
Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package.
When an event occurs, the event source invokes the appropriate method defined by the listener
and provides an event object as its argument.
Interface Description
ActionListener - Defines one method to receive action events.
AdjustmentListener - Defines one method to receive adjustment events. ComponentListener
- Defines four methods to recognize when a component is hidden, moved, resized, or shown.
ContainerListener - Defines two methods to recognize when a component is added to or
removed from a container.
FocusListener - Defines two methods to recognize when a component gains or loses keyboard
focus.
ItemListener - Defines one method to recognize when the state of an item changes.
KeyListener - Defines three methods to recognize when a key is pressed, released, or typed.
MouseListener - Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
MouseMotionListener - Defines two methods to recognize when the mouse is dragged or
moved.
MouseWheelListener - Defines one method to recognize when the mouse wheel is moved.
TextListener - Defines one method to recognize when a text value changes.
WindowFocusListener - Defines two methods to recognize when a window gains or loses
input focus.
WindowListener Defines seven methods to recognize when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit.
Using the Delegation Event Model
SJBIT, Dept. of ISE

Page 38

Java and J2EE (06IS753)

Applet programming using the delegation event model is done following these two steps:
1. Implement the appropriate interface in the listener so that it will receive the type of event
desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the
event notifications.
Adapter Classes
Definition : An adapter class provides an empty implementation of all methods in an event
listener interface.
x

Adapter classes are useful when you want to receive and process only some of the events
that are handled by a particular event listener interface.

New class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.

For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ). The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then
you could simply extend MouseMotionAdapter and implement mouseDragged( ). The
empty implementation of mouseMoved( ) would handle the mouse motion events for you.

The following example demonstrates an adapter.


// Demonstrate an adapter. import java.awt.*;
import java.awt.event.*; import java.applet. *;
/*
<applet code="AdapterDemo" width=300 height=1 00>
</applet>
*/
public class AdapterDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
SJBIT, Dept. of ISE

Page 39

Java and J2EE (06IS753)

public MyMouseAdapter(AdapterDemo adapterDemo) {

this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}}
Inner Classes
Consider the applet shown in the following listing. It does not use an inner class. Its goal is to
display the string
Mouse Pressed in the status bar of the applet viewer or browser when the mouse is pressed.
There are two top-level classes in this program. MousePressedDemo extends Applet, and
MyMouseAdapter extends MouseAdapter. The init( ) method of MousePressedDemo
instantiates MyMouseAdapter and provides this object as an argument to the
addMouseListener( ) method.
Notice that a reference to the applet is supplied as an argument to the MyMouseAdapter
constructor. This reference is stored in an instance variable for later use by the mousePressed(
)
method.
// This applet does NOT use an inner class.
import java.applet. *;
SJBIT, Dept. of ISE

Page 40

Java and J2EE (06IS753)

import java.awt.event.*;

/*
<applet code="MousePressedDemo" width=200 height=100> </applet>
*/
public class MousePressedDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
}}
class MyMouseAdapter extends MouseAdapter { MousePressedDemo mousePressedDemo;
public MyMouseAdapter(MousePressedDemo mousePressedDemo) { this.mousePressedDemo
= mousePressedDemo;
}
public void mousePressed(MouseEvent me) { mousePressedDemo.showStatus("Mouse
Pressed.");

SJBIT, Dept. of ISE

Page 41

Java and J2EE (06IS753)

UNIT-4: SWINGS

SWINGS:
The origins of Swing; Two key Swing features;
Components and Containers; The Swing Packages;
A simple Swing Application; Create a Swing Applet;
Jlabel and ImageIcon;
JTextField;
The Swing Buttons;
JTabbedpane;
JScrollPane;
JList;
JComboBox;
JTable.

SJBIT, Dept. of ISE

Page 42

Java and J2EE (06IS753)

Swing is built on top of AWT and is entirely written in Java, using AWTs lightweight
component support. In particular, unlike AWT, t he architecture of Swing components makes it
easy to customize both their appearance and behavior. Components from AWT and Swing can be
mixed, allowing you to add Swing support to existing AWT-based programs. For example, swing
components such as JSlider, JButton and JCheckbox could be used in the same program with
standard AWT labels, textfields and scrollbars.
4.1 Three parts
Component set (subclasses of JComponent) Support classes, Interfaces
Swing Components and Containers
Swing components are basic building blocks of an application. Swing toolkit has a wide range
of various widgets. Buttons, check boxes,sliders, list boxes etc. Everything a programmer
needs for his job. In this section of the tutorial, we will describe several useful components.
JLabel Component
JLabel is a simple component for displaying text, images or both. It does not react to input
events.
JCheckBox
JCheckBox is a widget that has two states. On and Off. It is a box with a label JSlider
JSlider is a component that lets the user graphically select a value by sliding a knob within a
bounded interval
JComboBox
Combobox is a component that combines a button or editable field and a drop-down list. The
user can select a value from the drop-down list, which appears at the user's request.
JProgressBar
A progress bar is a widget that is used, when we process lengthy tasks. It is animated so that
the user knows, that our task is progressing
JToggleButton

JToggleButton is a button that has two states. Pressed and not pressed. You toggle between
these two states by clicking on it
Containers
Swing contains a number of components that provides for grouping other components together.

SJBIT, Dept. of ISE

Page 43

Java and J2EE (06IS753)

In AWT, such components extended java.awt.Container and included Panel, Window, Frame,
and Dialog.

1.1 A Simple Container


JPanel is Swings version of the AWT class Panel and uses the same default layout,
FlowLayout. JPanel is descended directly from JComponent.
JFrame is Swings version of Frame and is descended directly from that class. The
components added to the frame are referred to as its contents; these are managed by the
contentPane. To add a component to a JFrame, we must use its contentPane instead.
JInternalFrame is confined to a visible area of a container it is placed in. It can be iconified ,
maximized and layered.
JWindow is Swings version of Window and is descended directly from that class. Like
Window, it uses BorderLayout by default.
JDialog is Swings version of Dialog and is descended directly from that class. Like Dialog, it
uses BorderLayout by default. Like JFrame and JWindow,
JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass
panes. All dialogs are modal, which means the current
thread is blocked until user interaction with it has been completed. JDialog class is intended as
the basis for creating custom dialogs; however, some
of the most common dialogs are provided through static methods in the class JOptionPane.
Jlabel and ImageIcon
Syntax :

public class JLabel

extends JComponent
implements SwingConstants, Accessible
x

It is a display area for a short text string or an image, or both.

A label does not react to input events. As a result, it cannot get the keyboard focus.

A label can display a keyboard alternative as a convenience for a nearby component that
has a keyboard alternative but can't display it.

A JLabel object can display either text, an image, or both.

By default, labels are vertically centered in their display area.

Text-only labels are leading edge aligned, by default; image-only labels are
horizontally centered, by default.

SJBIT, Dept. of ISE

Page 44

Java and J2EE (06IS753)

Can use the setIconTextGap method to specify how many pixels should appear between the
text and the image. The default is 4 pixels.
ImageIcon
Syntax :
public ImageIcon(String filename)
{

this(filename, filename);
}
Creates an ImageIcon from the specified file. The image will be preloaded by using
MediaTracker to monitor the loading state of the image.
The specified String can be a file name or a file path. When specifying a path, use the Internetstandard forward-slash ("/") as a separator. (The string is converted to an URL, so the forwardslash works on all systems.)
For example, specify:
new ImageIcon("images/myImage.gif")
The description is initialized to the filename string.
Example of JLabel with ImageIcon :
import java.awt.FlowLayout; import java.awt.HeadlessException;
import javax.swing.Icon;
import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel;
public class Main extends JFrame {
public Main() throws HeadlessException { setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new
FlowLayout(FlowLayout.LEFT));
Icon icon = new ImageIcon("a.png");
JLabel label1 = new JLabel("Full Name :", icon, JLabel.LEFT);
JLabel label2 = new JLabel("Address :", JLabel.LEFT); label2.setIcon(new
ImageIcon("b.png"));
getContentPane().add(label1); getContentPane().add(label2);
}
SJBIT, Dept. of ISE

Page 45

Java and J2EE (06IS753)

public static void main(String[] args) { new Main().setVisible(true);

}
}
JTextField
x

JTextField is a lightweight component that allows the editing of a single line of text.

JTextField is intended to be source-compatible with java.awt.TextField where it is


reasonable to do so. This component has capabilities not found in the
java.awt.TextField class.

JTextField has a method to establish the string used as the command string for the action
event that gets fired.

The java.awt.TextField used the text of the field as the command string for the
ActionEvent.

JTextField will use the command string set with the setActionCommand method if not null,
otherwise it will use the text of the field as a compatibility with java.awt.TextField.

1. Swing Package

Syntax :
public class JButton extends AbstractButton implements Accessible
An implementation of a "push" button. Buttons can be configured, and to some degree
controlled, by Actions. Using an Action with a button has many benefits beyond directly
configuring a button.
package com.ack.gui.swing.simple;
import java.awt.*;
import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import
javax.swing.*;
public class SimpleSwingButtons extends JFrame {
public static void main( String[] argv ) {
SimpleSwingButtons myExample = new SimpleSwingButtons( "Simple Swing Buttons" );
}
SJBIT, Dept. of ISE

Page 46

Java and J2EE (06IS753)

public SimpleSwingButtons( String title ) {


super( title );
setSize( 150, 150 );
add WindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we
) { dispose();
System.exit( 0 );
}
} );
init();
setVisible( true );
}
private void init() {

JPanel my_panel = new JPanel();


my_panel.setLayout( new GridLayout( 3, 3 ) ); for( int i = 1; i < 10; i++ ) {
ImageIcon icon = new ImageIcon( i + ".gif" ); JButton jb = new JButton( icon );
jb.setToolTipText( i + ".gif" );
my_panel.add( jb );
}
getContentPane().add( my_panel );
my_panel.setBorder( BorderFactory.createEtchedBorder() );
}
}
JTabbedpane
Syntax : public class JTabbedPane
extends JComponent
implements Serializable, Accessible, SwingConstants
x

A component that lets the user switch between a group of components by clicking on a tab
with a given title and/or icon.

SJBIT, Dept. of ISE

Page 47

Java and J2EE (06IS753)


x

Tabs/components are added to a TabbedPane object by using the addTab and insertTab
methods.

A tab is represented by an index corresponding to the position it was added in, where the
first tab has an index equal to 0 and the last tab has an index equal to the tab count minus

The TabbedPane uses a Single SelectionModel to represent the set of tab indices and the
currently selected index. If the tab count is greater than 0, then there will always be a
selected index, which by default will be initialized to the first tab. If the tab count is 0, then
the selected index will be -1.

JScrollPane
Syntax : public class JScrollPane
extends JComponent
implements ScrollPaneConstants, Accessible
x

Provides a scrollable view of a lightweight component.

A JScrollPane manages a viewport, optional vertical and horizontal scroll bars, and
optional row and column heading viewports.

The JViewport provides a window, or "viewport" onto a data source -- for example, a text
file. That data source is the "scrollable client" (aka data model) displayed by the JViewport
view.

A JScrollPane basically consists of JScrollBars, a JViewport, and the wiring between them,
as shown in the diagram at right.

JList
Syntax : public class JList
extends JComponent
implements Scrollable, Accessible
A component that allows the user to select one or more objects from a list. A separate model,
ListModel, represents the contents of the list.
// Create a JList that displays the strings in data[]
String[] data = {"one", "two", "three", "four"}; JList dataList = new JList(data);
JComboBox
Syntax : public class JComboBox
extends JComponent
SJBIT, Dept. of ISE

Page 48

Java and J2EE (06IS753)

implements ItemSelectable, ListDataListener, ActionListener, Accessible

A component that combines a button or editable field and a drop-down list.

The user can select a value from the drop-down list, which appears at the user's request.

If you make the combo box editable, then the combo box includes an editable field into
which the user can type a value.

JTable
Syntax : public class JTable
extends JComponent
implements TableModelListener, Scrollable, TableColumnModelListener,
ListSelectionListener, CellEditorListener, Accessible

The JTable is used to display and edit regular two-dimensional tables of cells.

The JTable has many facilities that make it possible to customize its rendering and

editing but provides defaults for these features so that simple tables can be set up
easily.

For example, to set up a table with 10 rows and 10 columns of numbers:

TableModel dataModel = new AbstractTableModel() {


public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
}
JTable table = new JTable(dataModel); JScrollPane scrollpane = new JScrollPane(table);

SJBIT, Dept. of ISE

Page 49

Java and J2EE (06IS753)

UNIT-5: JAVA 2 ENTERPRISE EDITION OVERVIEW, DATABASE ACCESS:

Overview of J2EE and J2SE.


The Concept of JDBC
JDBC Driver Types;
JDBC Packages; A Brief Overview of the JDBC process; Database Connection; Associating the
JDBC/ODBC Bridge with the Database; Statement Objects; ResultSet; Transaction Processing;
Metadata, Data types; Exceptions.

SJBIT, Dept. of ISE

Page 50

Java and J2EE (06IS753)

Overview of J2EE and J2SE


x

Java2 Platform, Enterprise Edition (J2EE) technology provides a componentbased approach to the design, development, assembly, and deployment of
enterprise applications.

The J2EE platform gives you a multitiered distributed application model, the
ability to reuse components, integrated XML-based data interchange, a unified
security model, and flexible transaction control.

Vendors and customers enjoy the freedom to choose the products and components
that best meet their business and technological requirements.

5. 1 The Concept of JDBC


x

The JDBC ( Java Database Connectivity) API defines interfaces and classes for
writing database applications in Java by making database connections.

Using JDBC you can send SQL, PL/SQL statements to almost any relational
database. JDBC is a Java API for executing SQL statements and supports basic SQL
functionality.

It provides RDBMS access by allowing you to embed SQL inside Java code.

Overview of JDBC Process


Before you can create a java jdbc connection to the database, you must first import the java.sql
package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be
imported.
Java application calls the JDBC library. JDBC loads a driver which talks to the database. We
can change database engines without changing database code.
Establishing Database Connection and Associating JDBC/ODBC bridge 1. Loading a
database driver,
x In this step of the jdbc connection process, we load the driver class by calling Class.forName()
with the Driver class name as an argument. Once loaded, the Driver class creates an instance of
itself.
x A client can connect to Database Server through JDBC Driver. Since most of the Database
servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
x The return type of the Class.forName (String ClassName) method is Class. Class is a class in
java.lang package.
SJBIT, Dept. of ISE

Page 51

Java and J2EE (06IS753)

Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Or any other driver


}
catch(Exception x) {
System.out.println( Unable to load the driver class! );
}
5.2 Creating a oracle jdbc Connection
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC
driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class
manages the JDBC drivers that are installed on the system.
x Its getConnection() method is used to establish a connection to a database. It uses
a username, password, and a jdbc url to establish a connection to the database and
returns a connection object.
x A jdbc Connection represents a session/connection with a specific database. Within the
context of a Connection, SQL, PL/SQL statements are executed and results are returned. An
application can have one or more connections with a single database, or it can have many
connections with different databases.
x A Connection object provides metadata i.e. information about the database, tables, and
fields. It also contains methods to deal with transactions.
Each subprotocol has its own syntax for the source. Were using the jdbc odbc subprotocol, so
the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.
try{
Connection dbConnection=DriverManager.getConnection(url,loginName,Pas sword)
}

catch( SQLException x ){
System.out.println( Couldnt get connection! );
}
5.3. Creating a JDBC Statement object
x Once a connection is obtained we can interact with the database.
Connection interface defines methods for interacting with the database via the established
connection.
SJBIT, Dept. of ISE

Page 52

Java and J2EE (06IS753)

x To execute SQL statements, you need to instantiate a Statement object from your connection
object by using the createStatement() method.
x Statement statement = dbConnection.createStatement();
x A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements


x

Statement: Execute simple sql queries without parameters.


Statement createStatement()
Creates an SQL Statement object.

Prepared Statement: Execute precompiled sql queries with or without parameters. Prep
aredS tatement prepare Statement(String sql)
returns a new PreparedStatement object. Prep aredStatement objects are precompiled SQL
statements.

Callable Statement: Execute a call to a database stored procedure. CallableStatement


prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure
call statements.

5.4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
x

Statement interface defines methods that are used to interact with database via the
execution of SQL statements.

The Statement class has three methods for executing statements:


executeQuery(), executeUpdate(), and execute().
For a SELECT statement, the method to use is executeQuery .

x
x

For statements that create or modify tables, the method to use is executeUpdate. Note:
Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.

ResultSet provides access to a table of data generated by executing a Statement. The table rows
are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data.
The next() method is used to successively step through the rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet. It is constructed from the Connection object.
SJBIT, Dept. of ISE

Page 53

Java and J2EE (06IS753)

UNIT -6: SERVLETS

Background; The Life Cycle of a Servlet; Using Tomcat for


Servlet Development;
A simple Servlet; The Servlet API; The Javax.servlet
Package; Reading Servlet Parameter;
The Javax.servlet.http package;
Handling HTTP Requests and Responses; Using Cookies; Session Tracking

SJBIT, Dept. of ISE

Page 54

Java and J2EE (06IS753)


Background

Definition : Servlets are modules of Java code that run in a server application (hence the name
"Servlets", similar to "Applets" on the client side) to answer client requests.
x

Servlets are not tied to a specific client-server protocol but they are most commonly used
with HTTP and the word "Servlet" is often used in the meaning of "HTTP Servlet".

Servlets make use of the Java standard extension classes in the packages
javax. servlet (the basic Servlet framework) and javax. servlet .http

Typical uses for HTTP Servlets include:


o

Processing and/or storing data submitted by an HTML form.

Providing dynamic content, e.g. returning the results of a database query to the client.

Managing state information on top of the stateless HTTP, e.g. for an online shopping
cart system which manages shopping carts for many concurrent customers and maps
every request to the right customer.

6.1 Servlet Life Cycle

The life cycle of a servlet is controlled by the container in which the servlet has been deployed.
When a request is mapped to a servlet, the container performs the following steps:
1. If an instance of the servlet does not exist, the web container:
a. Loads the servlet class
b. Creates an instance of the servlet class
c. Initializes the servlet instance by calling the init method. Initialization is covered in
Initializing a Servlet
2. Invokes the service method, passing a request and response object.
3. If the container needs to remove the servlet, it finalizes the servlet by calling the servlets
destroy method.
6.1.1 A servlet example
SJBIT, Dept. of ISE

Page 55

Java and J2EE (06IS753)

import java.io.*; import javax.servlet.*; import javax.servlet.http. *;

public class HelloClientServlet extends HttpServlet


{
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html"); PrintWriter out = res.getWriter();
out.println("<HTML><HEAD><TITLE>Hello Client !</TITLE>"+
"</HEAD><BODY>Hello Client !</BODY></HTML>");
out.close();
}
public String getServletInfo()
{
return "HelloClientServlet 1.0 by Stefan Zeiger";
}
}
6.1.2. Servlet API
x

Two packages contain the classes and interfaces that are required to build servlets. They are
javax.servlet and javax.servlet.http.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing
servlets. All servlets must implement the Servlet interface, which defines life cycle
methods.

6.1.3 The servlet packages :


x

The javax.servlet package contains a number of classes and interfaces that describe
and define the contracts between a servlet class and the runtime environment provided for an
instance of such a class by a conforming servlet container.

The Servlet interface is the central abstraction of the servlet API.

SJBIT, Dept. of ISE

Page 56

Java and J2EE (06IS753)


x

All servlets implement this interface either directly, or more commonly, by extending a
class that implements the interface.

The two classes in the servlet API that implement the Servlet interface are GeneriISErvlet
and HttpServlet .

For most purposes, developers will extend HttpServlet to implement their servlets while
implementing web applications employing the HTTP protocol.

The basic Servlet interface defines a service method for handling client requests. This
method is called for each request that the servlet container routes to an instance of a servlet.
6.1.4 Handling HTTP requests and responses :
x

Servlets can be used for handling both the GET Requests and the POST Requests.

x The HttpServlet class is used for handling HTTP GET Requests as it has som specialized
methods that can efficiently handle the HTTP requests. These methods are;
doGet()
doPost()
doPut()
doDelete() doOptions() doTrace() doHead()
An individual developing servlet for handling HTTP Requests needs to override one of these
methods in order to process the request and generate a response. The servlet is invoked
dynamically when an end-user submits a form.
Example:
<form name="F1" action=/servlet/ColServlet> Select the color:
<select name = "col" size = "3">
<option value = "blue">Blue</option> <option value = "orange">Orange</option> </select>
<input type = "submit" value = "Submit"> </form>
Heres the code for ColServlet.java that overrides the doGet() method to retrieve data from the
HTTP Request and it then generates a response as well.
// import the java packages that are needed for the servlet to work
import java.io .*;
import javax.servlet. *;
import javax.servlet.http. *;
SJBIT, Dept. of ISE

Page 57

Java and J2EE (06IS753)


// defining a class

public class ColServlet extends HttpServlet {


public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException
// request is an object of type HttpServletRequest and it's used to obtain information
// response is an object of type HttpServletResponse and it's used to generate a response //
throws is used to specify the exceptions than a method can throw
{
String colname = request.getParameter("col");
// getParameter() method is used to retrieve the selection made by the user
response.setContentType("text/html");
PrintWriter info = response.getWriter();
info .println("The color is: ");
info .println(col);
info.close();
}
}
6.2 Cookies
Cookies are small bits of textual information that a Web server sends to a browser and that the
browser returns unchanged when visiting the same Web site or domain later.
By having the server read information it sent the client previously, the site can provide visitors
with a number of conveniences like:
x

Identifying a user during an e-commerce session..

Avoiding username and password.

Customizing a site.

Focusing advertising.

To send cookies to the client, a servlet would create one or more cookies with the appropriate
names and values via new Cookie (name, value)
6.2.1 Placing Cookies in the Response Headers
SJBIT, Dept. of ISE

Page 58

Java and J2EE (06IS753)


x

The cookie is added to the Set-Cookie response header by means of the addCookie method
of HttpServletResponse. For example:

Cookie userCookie = new Cookie("user", "uid 1234"); response.addCookie(userCookie);


x

To send cookies to the client, you created a Cookie then used addCookie to send a SetCookie HTTP response header.

To read the cookies that come back from the client, call getCookies on the
HttpServletRequest. This returns an array of Cookie objects corresponding to the values that
came in on the Cookie HTTP request header

Once this array is obtained, loop down it, calling getName on each Cookie until find one
matching the name you have in mind. You then call getValue on the matching Cookie,
doing some processing specific to the resultant value.
public static String getCookieValue(Cookie[] cookies, String cookieName,
String defaultValue) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
return(defaultValue);
}

Session Tracking

Why id it needed : In many internet applications it is important to keep track of the session
when the user moves from one page to another or when there are different users logging on
to the same website at the same time

There are three typical solutions to this problem.

Cookies.
x

HTTP cookies can be used to store information about a shopping session, and

each subsequent connection can look up the current session and then extract

information about that session from some location on the server machine.

This is an excellent alternative, and is the most widely used approach.

SJBIT, Dept. of ISE

Page 59

Java and J2EE (06IS753)


URL Rewriting.

You can append some extra data on the end of each URL that identifies the session, and the
server can associate that session identifier with data it has stored about that session.

This is also an excellent solution, and even has the advantage that it works with browsers
that don't support cookies or where the user has disabled cookies.

However, it has most of the same problems as cookies, namely that the server-side program
has a lot of straightforward but tedious processing to do. In addition, you have to be very
careful that every URL returned to the user (even via indirect means like

Hidden form fields.

HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN"
NAME="session" VALUE="...">.

This means that, when the form is submitted, the specified name and value are included in
the GET or POST data.

This can be used to store information about the session.


x However, it has the major disadvantage that it only works if every page is dynamically
generated, since the whole point is that each session has a unique identifier.
Servlets solution :
x

The HttpSession API. is a high-level interface built on top of cookies or URLrewriting. In fact, on many servers, they use cookies if the browser supports them, but
automatically revert to URL-rewriting when cookies are unsupported or explicitly
disabled.

The servlet author doesn't need to bother with many of the details, doesn't have to
explicitly manipulate cookies or information appended to the URL, and is automatically
given a convenient place to store data that is associated with each session.

example,
HttpSession session = request.getSession(true); ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems"); if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);
}
SJBIT, Dept. of ISE

Page 60

Java and J2EE (06IS753)

UNIT-7: JSP, RMI

Java Server Pages (JSP):

JSP, JSP Tags, Tomcat, Request String, User Sessions, Cookies, Session Objects.
Java Remote Method Invocation:

Remote Method Invocation concept; Server side, Client side.

SJBIT, Dept. of ISE

Page 61

Java and J2EE (06IS753)


x

JavaServer Pages (JSP) is a Sun Microsystems specification for combining Java with HTML
to provide dynamic content forWeb pages.

When you create dynamic content, JSPs are more convenient to write than HTTP servlets
because they allow to embed Java code directly into HTML pages, in contrast with HTTP
servlets, in which you embed HTML inside Java code.

JSP is part of the Java 2 Enterprise Edition (J2EE).

JSP enables to separate the dynamic content of aWeb page from its presentation.

It caters to two different types of developers: HTML developers, who are responsible for the
graphical design of the page, and Java developers, who handle the development of software to
create the dynamic content.

7.1 JSP Tags


The following table describes the basic tags that you can use in a JSP page. Each shorthand
tag has an XML equivalent.
JSP Tag
Scriptlet

Syntax
<% java_code %>
. . . or use the XML
equivalent:
<jsp:scriptlet>
java_code
</jsp:scriptlet>

Directive

<% @ dir-type dir-attr


%>
. . . or use the XML
equivalent:
<jsp:directive.dir_type
dir_attr />

Directives contain
messages to the
application server.
A directive can also contain
name/value pair attributes
in the form attr=value,
which provides additional
instructions to
the application server.

Declarations

<%! declaration %>


. . . or use XML
equivalent...
<jsp:declaration>
declaration;
</jsp:declaration>
<%= expression %>
. . . or use XML
e<qjsupiv:uasleB
nte..a.n ... >
J<Sj Pspb:oexdpyriesssiniocnlu>ded if
tehxepression
<e/eaxnpirsession>
b
instantiated here
</jsp:useBean>
<jsp:setProperty ... >
<jsp:getProperty ... >
<jsp:include ... >

Declares a variable or
method that
can be referenced by other
declarations, scriptlets, or
expressions in the page

Expression
Actions
Tomcat

SJBIT, Dept. of ISE

Description
Embeds Java source code
Scriptlet in yourHTML
page. The Java code is
executed and its output is
inserted in sequence with
the rest
of the HTML in the page.

Defines a Java
tehxaptriesssion
ePvroalvuidateedacactepssagtoe
aredqvuaenscted
tfiem
ateu,res of JSP, and
coonnlyverted to a String,
aunsed XML
Page 62
ent ax. These actions
sy
ainreline to the output
sturpepaomrted as defined in
o
thfethe

Java and J2EE (06IS753)


x

Apache Tomcat is an implementation of the Java Servlet and JavaServer Pages


technologies.

The Java Servlet and JavaServer Pages specifications are developed under the Java
Community Process.

Apache Tomcat is developed in an open and participatory environment and released under
the Apache Software
Simple example
<% @ page info="a hello world example" %>
<html>
<head><title>Hello, World</title></head>
<body bgcolor="#ffffff" background="background.gif">
<% @ include file="dukebanner.html" %>
<table>
<tr>
<td width=150> &nbsp; </td>
<td width=250 align=right> <h1>Hello, World !</h1> </td> </tr>
</table>
</body></html>
Request string
<%@ page import="hello.NameHandler" %> <jsp:useBean id="mybean" scope="page"
class="hello.NameHandler" />
<jsp :setProperty name="mybean" property="*" />
<html>
<head><title>Hello, User</title></head>
<body bgcolor="#ffffff" background="background.gif">
<% @ include file="dukebanner.html" %>
<table border="0" width="700">
<tr>
<td width="150"> &nbsp; </td>

SJBIT, Dept. of ISE

Page 63

Java and J2EE (06IS753)


<td width="550">

<h1>My name is Duke. What's yours?</h1>


</td> </tr> <tr>
<td width="150" &nbsp; </td>
<td width="550">
<form method="get">
<input type="text" name="username" size="25">
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</td> </tr> </form>
</table>
<%
if ( request.getParameter("username") != null ) {
%>
<% @ include file="response.jsp" %>
<%
}
%> </body> </html>
The data the user enters is stored in the request object, which usually implements
javax.servlet.HttpServletRequest (or if your implementation uses a different protocol, another
interface that is subclassed from javax.servlet.ServletRequest). You can access the request
object directly within a scriptlet.
Sessions and Cookies in JSP
x

In JSP cookie are the object of the class javax.servlet.http.Cookie.

This class is used to creates a cookie, a small amount of information sent by a


servlet to a Web browser, saved by the browser, and later sent back to the server.

A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.

The getCookies() method of the request object returns an array of Cookie objects. Cookies can
be constructed using the following code:
SJBIT, Dept. of ISE

Page 64

Java and J2EE (06IS753)

<% @ page language="java" import="java.util. *"%> <%

String username=request.getParameter("username"); if(username==null) username="";


Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username); cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
%>
<html> <head>
<title>Cookie Saved</title>
</head> <body>
<p><a href="showcookievaue.jsp">Next Page to view the cookie value</a><p>
</body>
Above code sets the cookie and then displays a link to view cookie page
7.2 RMI
x

RMI applications are often comprised of two separate programs: a server and a client.

x A typical server application creates a number of remote objects, makes references to those
remote objects accessible, and waits for clients to invoke methods on those remote objects.
x A typical client application gets a remote reference to one or more remote objects in the
server and then invokes methods on them. RMI provides the mecahnism by which the server
and the client communicate and pass information back and forth. Such an applications is
sometimes referred to as a distributed object application.
The java.rmi.Remote Interface :
In RMI, a remote interface is an interface that declares a set of methods that may be invoked
from a remote Java virtual machine. A remote interface must satisfy the following
requirements:
A remote interface must at least extend, either directly or indirectly, the interface
java.rmi.Remote.
Each method declaration in a remote interface must satisfy the requirements
Server side and Client side
The interface ServerRef represents the server-side handle for a remote object implementation.
package java.rmi.server;
SJBIT, Dept. of ISE

Page 65

Java and J2EE (06IS753)

public interface ServerRef extends RemoteRef {

RemoteStub exportObject(java.rmi.Remote obj, Object data) throws


java.rmi.RemoteException;
String getClientHost() throws ServerNotActiveException; }
x The method exportObject finds or creates a client stub object for the
supplied Remote object implementation obj.
x The parameter data contains information necessary to export the object (such as port
number).
x The method getClientHost returns the host name of the current client.
When called from a thread actively handling a remote method invocation, the host name
of the client invoking the call is returned.
x If a remote method call is not currently being service, then ServerNotActiveException is
called.
There is no special configuration necessary to enable the client to send RMI calls through a
firewall. The client can, however, disable the packaging of RMI calls as HTTP requests by
setting the java.rmi.server.disableHttp property to equal the boolean value true.

SJBIT, Dept. of ISE

Page 66

Java and J2EE (06IS753)

UNIT 8: ENTERPRISE JAVA BEANS

Enterprise java Beans


Deployment Descriptors
Session Java Bean
Entity Java Bean
Message-Driven Bean
The JAR File.

SJBIT, Dept. of ISE

Page 67

Java and J2EE (06IS753)

Definition : Enterprise JavaBeans (EJB) is a managed, server-side component architecture for


modular construction of enterprise applications.

Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular


construction of enterprise applications. The EJB specification is one of several Java APIs in
the Java EE specification. EJB is a server-side model that encapsulates the business logic of an
application. The EJB specification was originally developed in 1997 by IBM and later adopted
by Sun Microsystems (EJB 1.0 and 1.1) in 1999[1] and enhanced under the Java Community
Process as JSR 19 (EJB 2.0), JSR 153(EJB 2.1), JSR 220 (EJB 3.0) and JSR 318 (EJB 3.1).
The EJB specification intends to provide a standard way to implement the back-end 'business'
code typically found in enterprise applications (as opposed to 'front-end' interface code). Such
code addresses the same types of problems, and solutions to these problems are often repeatedly
re-implemented by programmers. Enterprise JavaBeans are intended to handle such common
concerns as persistence, transactional integrity, and security in a standard way, leaving
programmers free to concentrate on the particular problem at hand.
In a typical J2EE application, Enterprise JavaBeans (EJBs) contain the application's
business logic and live business data. Although it is possible to use standard Java objects to
contain your business logic and business data, using EJBs addresses many of the issues you
would find by using simple Java objects, such as scalability, lifecycle management, and
state management.
There are three different types of EJB that are suited to different purposes:
x

Session EJBA Session EJB is useful for mapping business process flow (or equivalent
application concepts). There are two sub-types of Session EJB stateless and stateful
represent "pure" functionality that is created as it is needed.

Entity EJBAn Entity EJB maps a combination of data (or equivalent application
concept) and associated functionality. Entity EJBs are usually based on an underlying
data store and will be created based on that data within it.

Message-driven EJBA Message-driven EJB is very similar in concept to a Session


EJB, but is only activated when an asynchronous message arrives.

1. Deployment Descriptors
Definition : A deployment descriptor is a file that defines the following kinds of information:
EJB structural information, such as the EJB name, class, home and remote interfaces, bean
type (session or entity), environment entries, resource factory references, EJB references,
security role references, as well as additional information based on the bean type. Application
assembly information, such as EJB references, security roles, security role references, method
permissions, and container transaction attributes. Specifying assembly descriptor information is
an optional task that an Application Assembler performs.
1.1 Session Bean
SJBIT, Dept. of ISE

Page 68

Java and J2EE (06IS753)

Session bean is a type of enterprise bean; a type of EJB server-side component.

Session bean components implement the javax.ejb.SessionBean interface and can be


stateless or stateful.

Stateless session beans are components that perform transient services; stateful session
beans are components that are dedicated to one client and act as a server-side extension of
that client.

Session beans can act as agents modeling workflow or provide access to special transient
business services. As an agent, a stateful session bean might represent a customer's session at an
online shopping site.
x

As a transitive service, a stateless session bean might provide access to validate and
process credit card orders.

Session beans do not normally represent persistent business concepts like Employee or Order.
This is the domain of a different component type called an entity bean.

Example : package ejb.demo;


import javax.ejb.*;
import java.rmi.Remote;
import java.rmi.RemoteException; import java.util. *;
/* *
* This interface is extremely simple it declares only * one create method.
*/
public interface DemoHome extends EJBHome {
public Demo create() throws CreateException, RemoteException;
}
Entity Java Bean
x

An entity bean represents a business object in a persistent storage mechanism.

Some examples of business objects are customers, orders, and products.

In the J2EE SDK, the persistent storage mechanism is a relational database.

x
Typically, each entity bean has an underlying table in a relational database, and each
instance of the bean corresponds to a row in that table.
Message-Driven Bean
SJBIT, Dept. of ISE

Page 69

Java and J2EE (06IS753)


x

A message-driven bean is an enterprise bean that allows J2EE applications to process


messages asynchronously.

It acts as a JMS message listener, which is similar to an event listener except that it
receives messages instead of events.

The messages may be sent by any J2EE component--an application client, another
enterprise bean, or a Web component--or by a JMS application or system that does not use
J2EE technology.

Message-driven beans currently process only JMS messages, but in the future they may be used to
process other kinds of messages
The JAR file
The Java Archive (JAR) file format enables you to bundle multiple files into a single archive file.
Typically a JAR file contains the class files and auxiliary resources associated with applets and
applications.
The JAR file format provides many benefits:
x

Security: You can digitally sign the contents of a JAR file. Users who recognize your
signature can then optionally grant your software security privileges it wouldn't otherwise
have.

Decreased download time: If your applet is bundled in a JAR file, the applet's class files
and associated resources can be downloaded to a browser in a single HTTP transaction
without the need for opening a new connection for each file.

Compression: The JAR format allows you to compress your files for efficient storage.

Packaging for extensions: The extensions framework provides a means by which you can
add functionality to the Java core platform, and the JAR file format defines the packaging
for extensions. By using the JAR file format, you can turn your software into extensions as
well.

Package Sealing: Packages stored in JAR files can be optionally sealed so that the package
can enforce version consistency. Sealing a package within a JAR file means that all classes
defined in that package must be found in the same JAR file.

Package Versioning: A JAR file can hold data about the files it contains, such as vendor
and version information.

Portability: The mechanism for handling JAR files is a standard part of the Java platform's
core API.

Execution
SJBIT, Dept. of ISE

Page 70

Java and J2EE (06IS753)

EJBs are deployed in an EJB container, typically but not necessarily, within an application server.
The specification describes how an EJB interacts with its container and how client code interacts
with the container/EJB combination. The EJB classes used by applications are included in
the javax.ejb package. (The javax.ejb.spi package is a service provider interfaceused only by EJB
container implementations.)
Clients of EJB beans do not instantiate those beans directly via Java's new operator, but instead
have to obtain a reference via the EJB container. This reference is then not a reference to the
implementation bean itself, but to a proxy, which either dynamically implements the local or
remote business interface that the client requested or dynamically implements a sub-type of the
actual bean. The proxy can then be directly cast to the interface or bean. A client is said to have a
'view' on the EJB, and the local interface, remote interface and bean type itself respectively
correspond with the local view, remote view and no-interface view.
This proxy is needed in order to give the EJB container the opportunity to transparently provide
cross-cutting (AOP-like) services to a bean like transactions, security, interceptions, injections,
remoting, etc.
E.g. a client invokes a method on a proxy, which will then first start a transaction with the help of
the EJB container and then call the actual bean method. When the actual bean method returns, the
proxy ends the transaction (i.e. by committing it or doing a rollback) and transfers control back to
the client.
Transactions
EJB containers must support both container managed ACID transactions and bean managed
transactions.
Container-managed transactions (CMT) are by default active for calls to session beans. That is, no
explicit configuration is needed. This behavior may be declaratively tuned by the bean via
annotations and if needed such configuration can later be overridden in the deployment descriptor.
Tuning includes switching off transactions for the whole bean or specific methods, or requesting
alternative strategies for transaction propagation and starting or joining a transaction. Such
strategies mainly deal with what should happen if a transaction is or isn't already in progress at the
time the bean is called. The following variations are supported:
Declarative Transactions Management Types
Type

Explanation

MANDATORY

If the client has not started a transaction, an exception is thrown. Otherwise


the client's transaction is used.

REQUIRED

If the client has started a transaction, it is used. Otherwise a new transaction


is started. (this is the default when no explicit type has been specified)

SJBIT, Dept. of ISE

Page 71

Java and J2EE (06IS753)


REQUIRES_NEW

If the client has started a transaction, it is suspended. A new transaction is


always started.

SUPPORTS

If the client has started a transaction, it is used. Otherwise, no transaction is


used.

NOT_SUPPORTED

If the client has started a transaction, it is suspended. No new transaction is


started.

NEVER

If the client has started a transaction, an exception is thrown. No new


transaction is started.

Alternatively, the bean can also declare via an annotation that it wants to handle transactions
programmatically via the JTA API. This mode of operation is called Bean Managed Transactions
(BMT), since the bean itself handles the transaction instead of the container.
Events
JMS (Java Message Service) is used to send messages from beans to clients, to let clients receive
asynchronous messages from these beans. MDBs can be used to receive messages from clients
asynchronously using either a JMS Queue or a Topic.
Naming and directory services
As an alternative to injection, clients of an EJB can obtain a reference to the session bean's proxy
object (the EJB stub) using JNDI. This alternative can be used in cases where injection is not
available, such as non-managed beans or standalone remote Java SE clients, or when it's necessary
to programmatically determine which bean to obtain.
JNDI names for EJB session beans are assigned by the EJB container via the following scheme:
JNDI names
Scope

Name pattern

Global

java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interfacename>]

Application java:app/<module-name>/<bean-name>[!<fully-qualified-interface-name>]
Module

java:module/<bean-name>[!<fully-qualified-interface-name>]

(entries in square brackets denote optional parts)


A single bean can be obtained by any name matching the above patterns, depending on the
'location' of the client. Clients in the same module as the required bean can use the module scope
SJBIT, Dept. of ISE

Page 72

Java and J2EE (06IS753)

and larger scopes, clients in the same application as the required bean can use the app scope and
higher, etc.

SJBIT, Dept. of ISE

Page 73

Você também pode gostar