J2EE

February 18, 2017 | Author: bharaathi | Category: N/A
Share Embed Donate


Short Description

Download J2EE...

Description

J2EE COURSE MATERIALS

CONTENTS SL.NO. 1.

CHAPTER CORE JAVA REVIEW 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8

2.

PAGE NO. 4

Object oriented principle Programming structures Object and classes Inheritance Package and Interface Exception handling Threading Input and Output

INTRODUCTION TO J2EE

29

2.1 Introduction 2.2 J2EE architecture 2.3 Component technologies 2.4 Service technologies 2.5 Communication technologies 2.6 Servers 3.

40

JDBC 3.1 Introduction to JDBC 3.2 Types of drivers 3.3 Steps to connect with database 3.4 ResultSetMetaData 3.5 Scrollable ResultSet 3.6 PreparedStatement 3.7 CallableStaement 3.8 Batch Statement 3.9 Connection pooling

4.

SERVLETS

52

4.1 Introduction to servlets and alternatives 4.2 Directory structure and Web Application Deployment Descriptor 4.3 Life-cycle of Servlet and Servlet APIstructure 4.4 Request and Response 4.5 ServletConfig, ServletContext, Servlet Collaboration 4.6 Session tracking 4.7 Applet-servlet communication

5.

JAVA SERVER PAGES [ JSP ]

80

5.1 Introduction 5.2 Directives 5.3 Scripting elements 5.4 Implicit Objects 2

5.5 Standard Action and Java Bean

6.

REMOTE METHOD INVOCATION [ RMI ]

97

6.1 Introduction. 6.2 Defining the RMI contract 6.3 RMI Client 6.4 RMI Server 6.5 Deploying RMI across a Network

7.

ENTERPRISE JAVA BEAN [ EJB ]

103

7.1 Introduction 7.2 EJB and Java Bean 7.3 Session Bean 7.4 Entity Bean 7.5 Message Driven Bean

8.

STRUTS

127

8.1 Introduction to struts 8.2 A simple application 8.3 Controller 8.4 Views

9.

XML

164 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10 9.11

10.

Introduction to XML XML Syntax XML Elements XML Attributes XML Validation XML with CSS XML with XSL XML Namespace Introduction to DTD DTD – XML Building blocks XML Schema

SUPPORTING TECHNOLOGIES

196

10.1 Introduction to SQL queries 10.2 Intoduction to HTML 10.3 Introduction to CSS 10.4 Introduction to javascript 10.5 UML

3

CHAPTER 1 CORE JAVA REVIEW 1.1 Object oriented principle OBJECT Basic building block for Object-Oriented Programming (OOP). Usually correspond to real-life entities. An object is a unit of software comprising of : a) State / Attribute b) Behavior c) Identity

: Defines the properties of the object & the current values of each of these properties. : Defines the response of an object reacts in terms of its state changes & message passing. : Defines an unique name.

EXAMPLE: Car, Mobile phone, An invoice, John Object : John IDENTITY NAME OF THE PERSON

STATE / ATTRIBUTES AGE ADDRESS PHONE BODY PARTS BEHAVIORS JUMP WALK MOVE ARMS

CLASS    

User-defined data type. Used to represent a template for several similar type of objects. Describes how the objects are structured internally. Objects of the same class have the same definition both for their state & behavior. 4

Example: CLASS : PERSON STATE / ATTRIBUTES AGE ADDRESS PHONE BODY PARTS

BEHAVIORS JUMP WALK MOVE ARMS

INSTANCE     

Creation of an object for a particular class. Attributes & behavior are described by the class. Each instance has a unique identity. Several different instances can be created from the same class. Each instance will have different internal states depending upon the different sequences of operations performed. CLASS : PERSON

Instance of ATTRIBUTES AGE ADDRESS PHONE BODY PARTS

BEHAVIORS JUMP WALK MOVE ARMS

Neh a

Instance of

Instance of Smith

Vivek 5

INHERITANCE A property which allows a class to inherit the properties from another class. Supports the concept of hierarchical classification. The parent class is known as base class and the descendent class is known as derived class. The base class serves as a pattern for the derived class.

Advantages Core idea for reuse in the software industry. Useful for easy modification of models. Useful for avoiding redundancy , leading to smaller models that are easier to understand.

Types of Inheritance a) Single Inheritance

:

b) Multiple Inheritance :

If the derived class inherits from a single parent, the inheritance is said to be single inheritance. If the derived class inherits from two or more parents, the inheritance is said to be multiple inheritance.

POLYMORPHISM  Ability to take more than one form  The same operation may exhibit different behavior in different instances.  Behavior depends upon the types of data used in the operation. EXAMPLE Operation to be performed : Addition Input Data Type Result Integer Sum Character Concatenated String

Advantages  Extensively used in implementing inheritance.  Allows objects having different internal structures to share the same external interface.

TYPES OF POLYMORPHISM (a) Compile-time Polymorphism Achieved with static binding. The procedure call is replaced with memory address statically at compile-time. Polymorphism is achieved with function overloading. Function Overloading means that in a program more than one functions can be defined with the same name & return type. The type & number of parameters can vary.

6

(b) Run-time Polymorphism Achieved with dynamic binding. At run-time the procedure call matching the object under current reference will be called. This gives objects the ability to respond to messages from routines when the object’s exact type is not known till the run-time.

DATA ABSTRACTION Refers to the act of representing essential features without including the background details or explanations. Controls the visibility of information. Focuses upon the essential characteristics of some object, relative to the perspective of the viewer.

ENCAPSULATION The method of combining the data member & member functions of an object into a single structure / unit (called class). Isolates the functional details of the object from outside the class. Helps in data hiding.

1.2 PROGRAMMING STRUCTURES       

A Simple Java Program Comments Data Types Variables Assignments and Initializations Operators Arrays

Before we get into the details of the language, a brief overview would be of benefit. This section gives a very quick look at the main features of the language, without going too far into the details or showing us any actual syntax, to give us a feel for the main concepts behind Object-Oriented programming in Java. A Java program is a collection of classes. Some of these we write; some are provided as a part of the java language.

A Simple Java Program Let's look more closely at about the simplest Java program we can have—one that simply prints a message to the console window: public class FirstSample { public static void main(String[] args) { System.out.println("We will not use 'Hello, World!'");

7

}}

Now let's look at this source code line by line. The keyword public is called an access modifier; these modifiers control what other parts of a program can use this code. The keyword class is there to remind us that everything in a Java program lives inside a class. Classes are the uilding blocks with which all Java applications and applets are built. Everything in a Java program must be inside a class. Following the keyword class is the name of the class. The rules for class names in Java are quite generous. Names must begin with a letter, and after that, they can have any combination of letters and digits. The length is essentially unlimited. We cannot use a Java reserved word (such as public or if) for a class name.

COMMENTS Comments in Java, like comments in most programming languages, do not show up in the executable program. Java has three ways of showing comments. The most common method is a //. We use this for a comment that will run from the // to the end of the line. System.out.println("We will not use 'Hello world!'"); // is this too cute? When longer comments are needed, we can mark each line with a //. Or we can use the /* and */ comment delimiters that let we block off a longer comment. /* This is the first sample program in Core Java Chapter 3 Copyright (C) 1996...2000 Cay Horstmann and Gary Cornell */

DATA TYPES Java is a strongly typed language. This means that every variable must have a declared type. There are eight primitive types in Java. Four of them are integer types; two are floating-point number types; one is the character type char, used for characters in the Unicode encoding and one is a boolean type for truth values.

INTEGERS The integer types are for numbers without fractional parts. Negative values are allowed. Java provides the four integer types JAVA INTEGER TYPES Type Int short Long

Storage 4 bytes 2 bytes 8 bytes

Requirement Range (inclusive) 2,147,483,648 to 2,147,483, 647 (just over 2 billion) -32,768 to 32,767 9,223,372,036,854,775,808L to 9,223,372,036,854,775,807L

8

Byte

1 byte

-128 to 127

FLOATING-POINT TYPES The floating-point types denote numbers with fractional parts. There are two floating-point Types

Type Float double

Storage 4 bytes 8 bytes

Requirement Range (inclusive) ±3.40282347E+38F (6–7 significant decimal digits) ±1.79769313486231570E+308 (15 significant decimal digits)

THE CHARACTER TYPE First, single quotes are used to denote char constants. For example, 'H' is a character. It is different from "H", a string containing a single character. Second, the char type denotes characters in the Unicode encoding scheme. Escape \b \t \n \r \” \’ \\

Special characters Sequence Name Unicode Value Backspace \u0008 Tab \u0009 Linefeed \u000a Carriage return \u000d Double quote \u0022 Single quote \u0027 Backslash \u005c

THE BOOLEAN TYPE The boolean type has two values, false and true. It is used for evaluating logical conditions. We cannot convert between integers and boolean values.

VARIABLES In Java, every variable has a type. We declare a variable by placing the type first, followed by the name of the variable. Here are some examples: double salary; int vacationDays; long earthPopulation; char yesChar; boolean done; Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement.

9

OPERATORS An operator takes one or more arguments and produces a new value. The arguments are in a different form than ordinary method calls, but the effect is the same. There are different types of operators are there. They are        

Arithmetic Operators Assignment Operators Unary minus and plus Operators Auto increment and Decrement Operators Relational Operators Logical Operators Bitwise Operators Ternary Operators

Arithmetic Operators The following are the arithmetic operators : addition (+), subtraction (-), division (/), multiplication (*) and modulus (%, which produces the remainder from integer division). Integer division truncates, rather than rounds, the result.

Assignment Operators Assignment is performed with the operator =. It means “take the value of the right-hand side (often called the rvalue) and copy it into the left-hand side (often called the lvalue). An rvalue is any constant, variable or expression that can produce a value, but an lvalue must be a distinct, named variable.

For instance; A = 5; Java also uses a shorthand notation to perform an operation and an assignment at the same time. This is denoted by an operator followed by an equal sign, and is consistent with all the operators in the language Instead of writing x = x + 4; we can write x+=4;

Unary minus and plus Operators The unary minus (-) and unary plus (+) are the same operators as binary minus and plus. The compiler figures out which use is intended by the way we write the expression. For instance, the statement x = -a; has an obvious meaning. The compiler is able to figure out: x = a * -b; but the reader might get confused, so it is clearer to say: 10

AUTO INCREMENT AND DECREMENT OPERATORS The increment and decrement operators are the two of the nicer shortcuts. The decrement operator is -- and means “decrease by one unit.” The increment operator is ++ and means “increase by one unit.” If a is an int, for example, the expression ++a is equivalent to (a = a + 1). Increment and decrement operators produce the value of the variable as a result. There are two versions of each type of operator, often called the prefix and postfix versions. Pre-increment means the ++ operator appears before the variable or expression, and post-increment means the ++ operator appears after the variable or expression. Similarly, predecrement means the -- operator appears before the variable or expression, and post-decrement means the -- operator appears after the variable or expression. For pre-increment and predecrement, (i.e., ++a or --a), the operation is performed and the value is produced. For postincrement and post-decrement (i.e. a++ or a--), the value is produced, then the operation is performed.

Relational Operators Relational operators generate a boolean result. They evaluate the relationship between the values of the operands. A relational expression produces true if the relationship is true, and false if the relationship is untrue. The relational operators are less than (), less than or equal to (=), equivalent (==) and not equivalent (!=). Equivalence and nonequivalence works with all built-in data types, but the other comparisons won’t work with type boolean. The relational operators == and != also work with all objects, but their meaning often confuses the first-time Java programmer.

Logical Operators The logical operators AND (&&), OR (||) and NOT (!) produce a boolean value of true or false based on the logical relationship of its arguments.

Bitwise Operators The bitwise operators allow us to manipulate individual bits in an integral primitive data type. Bitwise operators perform boolean algebra on the corresponding bits in the two arguments to produce the result. The bitwise AND operator (&) produces a one in the output bit if both input bits are one; otherwise it produces a zero. The bitwise OR operator (|) produces a one in the output bit if either input bit is a one and produces a zero only if both input bits are zero. The bitwise EXCLUSIVE OR, or XOR (^), produces a one in the output bit if one or the other input bit is a one, but not both. The bitwise NOT (~, also called the ones complement operator) is a unary operator; it takes only one argument. (All other bitwise operators are binary operators.) Bitwise NOT produces the opposite of the input bit—a one if the input bit is zero, a zero if the input bit is one.

11

Ternary operators This operator is unusual because it has three operands. The expression is of the form: booleanexp ? value0 : value1 If boolean-exp evaluates to true, value0 is evaluated and its result becomes the value produced by the operator. If boolean-exp is false, value1 is evaluated and its result becomes the value produced by the operator. The conditional operator can be used for its side effects or for the value it produces, but in general we want the value since that’s what makes the operator distinct from the if-else. Here’s an example: static int ternary(int i) { return i < 10 ? i * 100 : i * 10; }

We can see that this code is more compact than what we’d need to write without the ternary operator: static int alternative(int i) { if (i < 10) return i * 100; else return i * 10; }

Control flow Java, like any programming language, supports both conditional statements and loops to determine control flow. We start with the conditional statements and then move on to loops. We end with the somewhat cumbersome switch statement that we can use when we have to test for many values of a single expression.

CONDITIONAL STATEMENTS The conditional statement in Java has the form

if statement if ( condition ) statement In Java, as in most programming languages, we will often want to execute multiple statements when a single condition is true. For example: if (ourSales >= target) { performance = "Satisfactory"; bonus = 100; }

12

if/else statement if ( condition ) statement 1 else statement 2;

For example: if (ourSales >= target) { performance = "Satisfactory"; bonus = 100 + 0.01 * (ourSales - target); } else { performance = "Unsatisfactory"; bonus = 0; }

if / elseif (multiple branches) statement Repeated if . . . else if . . . alternatives are very common For example: if (ourSales >= 2 * target) { performance = "Excellent"; bonus = 1000; } else if (ourSales >= 1.5 * target) { performance = "Fine"; bonus = 500; } else if (ourSales >= target) { performance = "Satisfactory"; bonus = 100; } else { System.out.println("We're fired"); }

Indeterminate Loops In Java, as in all programming languages, there are control structures that let us repeat statements. There are two forms for repeating loops that are best when we do not know how many times a loop should be processed (these are “indeterminate loops”). First, there is the while loop that only executes the body of the loop while a condition is true . The general form is: while ( condition ) statement

The while loop will never execute if the condition is false at the outset see Figure 3-10). For example: while (balance < goal) { balance += payment; double interest = balance * interestRate / 100; balance += interest; years++; }

A while loop tests at the top. Therefore, the code in the block may never be executed. If we want to make sure a block is executed at least once, we will need to move the test to the bottom. This is done with the do / while loop. Its syntax looks like this:

13

do statement while ( condition ); do { balance += payment; double interest = balance * interestRate / 100; balance += interest; year++; // print current balance . . . // ask if ready to retire and get input . . . } while (input.equals("N"));

DETERMINATE LOOPS The for loop is a very general construct to support iteration that is controlled by a counter or similar variable that is updated after every iteration. The following is the syntax : for ( statement 1; expression 1; expression 2) statement 2;

The following loop prints the numbers from 1 to 10 on the screen. for (int i = 1; i javac math.java c:\>java math 22 6 The given numbers are 22, 6 Addition :28 Subtraction :16 Multiplication :132 Division :3

18

C:\>java math Invalid input, Usage : java math number1

number2

C:\>java math 44 5 7 Invalid input, Usage : java math number1

number2

Objects and Object Variables To work with objects, we first construct them and specify their initial state. Then we apply methods to the objects. In the Java programming language, we use constructors to construct new instances. A Constructor is a special method whose purpose is to construct and initialize objects. Constructor always have the same name as the class name. Thus, the constructor for the Date class is called Date . To construct a Date object, we combine the constructor with the new operator, as follows: new Date() While writing a constructor, keep the following in our mind     

A constructor has the same name as the class. A class can have more than one constructor. A constructor may take zero, one, or more parameters. A constructor has no return value. A constructor is always called with the new operator.

Syntax for creating an object for a class classname objectname = new classname(); For Example: Date Birthday = new Date(); Through an object we can access any method of the particular class, For this we use a special kind of operator called Dot operator ‘.’. int d = Birthday.get(Calendar.DAY_OF_MONTH); int m = Birthday.get(Calendar.MONTH);

1.4 INHERITANCE Inheritance, another fundamental concept of object-oriented programming. The idea behind inheritance is that we can create new classes that are built upon existing classes. When we inherit from an existing class, we reuse (or inherit) methods and fields, and we add new methods and fields to adapt our new class to new situations.

19

Base

Derived

(The arrow in the above UML diagram points from the derived class to the base class. As we will see, there can be more than one derived class.) We have two ways to differentiate our new derived class from the original base class. The first is: We simply add new functions to the derived class. These new functions are not part of the base class interface. The second and more important way to differentiate our new class is to change the behavior of an existing base-class function. This is referred to as overriding that function.

Here is how we define a Derived class that inherits from the Base class. We use the Java keyword extends to denote inheritance. class Derived extends Base { added methods and fields }

1.5 PACKAGE AND INTERFACE PACKAGE:There is a large set of predefined classes, grouped into packages. The full name of one of these predefined classes includes the name of the package as prefix. For example, the library class java.util.Random is in package java.util, and a program may use the class with code like this: java.util.Random r = new java.util.Random();

20

The import statement allows we to omit the package name from one of these classes. A Java program that includes the line import java.util.Random; can abbreviate the use of Random to Random r = new Random(); We can import all the classes in a package at once with a notation like import java.util.*; The package java.lang is special; every program behaves as if it started with import java.lang.*; whether it does or not. We can define our own packages, but defining packages is an advanced topic beyond the scope of what's required for this course. The import statement doesn't really "import" anything. It just introduces a convenient abbreviation for a fully-qualified class name. When a class needs to use another class, all it has to do is use it. The Java compiler will know that it is supposed to be a class by the way it is used, will import the appropriate .class file, and will even compile a .java file if necessary. (That's why it's important for the name of the file to match the name of the class). For example, here is a simple program that uses two classes: public class HelloTest { public static void main(String[] args) { Hello greeter = new Hello(); greeter.speak(); } } public class Hello { void speak() { System.out.println("Hello World!"); } }

Put each class in a separate file (HelloTest.java and Hello.java). Then try this: javac HelloTest.java java HelloTest We should see a cheery greeting. If we type ls we will see that we have both HelloTest.class and Hello.class even though we only asked to compile HelloTest.java. The Java compiler figured out that class HelloTest uses class Hello and automatically compiled it. Try this to learn more about what's going on: rm -f *.class javac -verbose HelloTest.java java HelloTest

INTERFACE The interface keyword takes the abstract concept one step further. We could think of it as a “pure” abstract class. It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies. An interface can also contain fields, but these are implicitly static and final. An interface provides only a form, but no implementation. 21

To create an interface, use the interface keyword instead of the class keyword. Like a class, we can add the public keyword before the interface keyword (but only if that interface is defined in a file of the same name) or leave it off to give “friendly” status so that it is only usable within the same package. To make a class that conforms to a particular interface (or group of interfaces) use the implements keyword. Once we’ve implemented an interface, that implementation becomes an ordinary class that can be extended in the regular way. A simple example is as follows: interface Area{ float pi=3.14f; float compute (float x, float y); } class rect implements Area{ public float compute(float x, float y){ return x*y; } } class

} class

cir implements Area{ public float compute(float x, float y){ return pi*x*y; } intfacetest { public static void main(String arg[]) [ rect r=new rect(); cir c=new cir(); System.out.println(“Rect= “+r.compute(10.20)); System.out.println(“Cir= “+c.compute(10.20));

} }

1.6 EXCEPTION HANDLING EXCEPTIONS A Java program should never "core dump," no matter how buggy it is. If the compiler excepts it and something goes wrong at run time, Java throws an exception. By default, an exception causes the program to terminate with an error message, but we can also catch an exception. try { // ... foo.bar(); // ... a[i] = 17; // ...

} catch (IndexOutOfBoundsException e) {err.println("Oops: " + e); }

22

The try statement says we're interested in catching exceptions. The catch clause (which can only appear after a try) says what to do if an IndexOutOfBoundsException occurs anywhere in the try clause. In this case, we print an error message. The toString() method of an exception generates a string containing information about what went wrong, as well as a call trace. WARNING Never write an empty catch clause. If we do, we will regret it. Maybe not today, but tomorrow and for the rest of our life. Because we caught this exception, it will not terminate the program. If some other kind of exception occurs (such as divide by zero), the exception will be thrown back to the caller of this function and if that function doesn't catch it, it will be thrown to that function's caller, and so on back to the main function, where it will terminate the program if it isn't caught. Similarly, if the function foo.bar throws an IndexOutOfBoundsException and doesn't catch it, we will catch it here. The catch clause actually catches IndexOutOfBoundsException or any of its subclasses, including ArrayIndexOutOfBoundsException , StringIndexOutOfBoundsException , and others. An Exception is just another kind of object, and the same rules for inheritance hold for exceptions as any other king of class. We can define and throw our own exceptions. class SytaxError extends Exception { int lineNumber; SytaxError(String reason, int line) { super(reason); lineNumber = line; } public String toString() { return "Syntax error on line " + lineNumber + ": " + getMessage(); } } class SomeOtherClass { public void parse(String line) throws SyntaxError { // ... if (...) throw new SyntaxError("missing comma", currentLine); //... } public void parseFile(String fname) { //... try { // ... nextLine = in.readLine(); parse(nextLine); // ... } catch (SyntaxError e) { err.println(e); } }}

23

Each function must declare in its header (with the keyword throws) all the exceptions that may be thrown by it or any function it calls. It doesn't have to declare exceptions it catches. Some exceptions, such as IndexOutOfBoundsException, are so common that Java makes an exception for them (sorry about that pun) and doesn't require that they be declared. This rule applies to RuntimeException and its subclasses. We should never define new subclasses of RuntimeException. There can be several catch clauses at the end of a try statement, to catch various kinds of exceptions. The first one that "matches" the exception (i.e., is a super class of it) is executed. We can also add a finally clause, which will always be executed, no matter how the program leaves the try clause (whether by falling through the bottom, executing a return, break, or continue, or throwing an exception).

1.7 THREADING Java lets we do several things at once by using threads. If our computer has more than one CPU, it may actually run two or more threads simultaneously. Otherwise, it will switch back and forth among the threads at times that are unpredictable unless we take special precautions to control it. There are two different ways to create threads. I will only describe one of them here. Thread t = new Thread(command); // t.start(); // t start running command, but we don't wait for it to finish // ... do something else (perhaps start other threads?) // ... later: t.join(); // wait for t to finish running command

The constructor for the built-in class Thread takes one argument, which is any object that has a method called run. This requirement is specified by requiring that command implement the Runnable interface described earlier. (More precisely, command must be an instance of a class that implements Runnable). The way a thread "runs" a command is simply by calling its run() method. It's as simple as that! In project 1, we are supposed to run each command in a separate thread. Thus we might declare something like this: class Command implements Runnable { String commandLine; Command(String commandLine) { this.commandLine = commandLine; } public void run() { // Do what commandLine says to do } }

24

We can parse the command string either in the constructor or at the start of the run() method. The main program loop reads a command line, breaks it up into commands, runs all of the commands concurrently (each in a separate thread), and waits for them to all finish before issuing the next prompt. In outline, it may look like this. for (;;) { out.print("% "); out.flush(); String line = inputStream.readLine(); int numberOfCommands = // count how many commands there are on the

line

}

Thread t[] = new Thread[numberOfCommands]; for (int i=0; i
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF