Sei sulla pagina 1di 99

Part I: - Object oriented Programming using core java

01: Conversion from Fahrenheit to Celsius

AIM : Write a program that reads a Fahrenheit degree in double then converts it to Celsius and
displays the result. The formula for the conversion is as follows: celsius = (5/9) * (fahrenheit - 32)

OBJECTIVE THEORY About Java

: To expose the concepts of java program, various data types and conversion.

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called Oak but was renamed Java in 1995. Object-oriented programming is at the core of Java. In fact, all Java programs are object orientedthis isnt an option the way that it is in C++, for example. OOP is so integral to Java that you must understand its basic principles before you can write even simple Java programs. Therefore, this chapter begins with a discussion of the theoretical aspects of OOP.

2. Data types, Variables:

Summary of Primitive Data Types

1 SDTL SCOE-IT

01: Conversion from Fahrenheit to Celsius

Data Type boolean byte short char int long float double

Width (bits) not applicable 8 16 16 32 64 32 64

Minimum Value, Maximum Value true, false (no ordering implied) -27 to 2 7-1 -215 to 2 15-1 0x0, 0xffff -231 to 2 31-1 -263 to 2 63-1 1.40129846432481707e-45f, 3.402823476638528860e+38f \'b14.94065645841246544e-324, \'b11.79769313486231570e+308

Wrapper Class Boolean Byte Short Character Integer Long Float Double

Variable Declarations:A variable stores a value of a particular type. A variable has a name, a type, and a value associated with it. In Java, variables can only store values of primitive data types and references to objects. Variables that store references to objects are called reference variables.

Declaring and Initializing Variables:Variable declarations are used to specify the type and the name of variables. This implicitly determines their memory allocation and the values that can be stored in them. We show some examples of declaring variables that can store primitive values: char a, b, c; double area; boolean flag; // a, b and c are character variables. // area is a floating-point variable. // flag is a boolean variable.

The first declaration above is equivalent to the following three declarations: char a; char b; char c; A declaration can also include initialization code to specify an appropriate initial value for the variable: int i = 10, // i is an int variable with initial value 10. j = 101; // j is an int variable with initial value 101. long big = 2147483648L; // big is a long variable with specified initial value. 2 SDTL SCOE-IT

01: Conversion from Fahrenheit to Celsius

Object Reference Variables:An object reference is a value that denotes an object in Java. Such reference values can be stored in variables and used to manipulate the object denoted by the reference value. A variable declaration that specifies a reference type (i.e., a class, an array, or an interface name) declares an object reference variable. Analogous to the declaration of variables of primitive data types, the simplest form of reference variable declaration only specifies the name and the reference type. The declaration determines what objects a reference variable can denote. Before we can use a reference variable to manipulate an object, it must be declared and initialized with the reference value of the object. Pizza yummyPizza; Hamburger bigOne, smallOne; // Variable yummyPizza can reference objects of class Pizza. // Variable bigOne can reference objects of class Hamburger, // and so can variable smallOne.

It is important to note that the declarations above do not create any objects of class Pizza or Hamburger. The declarations only create variables that can store references to objects of these classes. A declaration can also include an initialize to create an object whose reference can be assigned to the reference variable: Pizza yummyPizza = new Pizza("Hot&Spicy"); // Declaration with initializer.

Lifetime of Variables:Lifetime of a variable, that is, the time a variable is accessible during execution, is determined by the context in which it is declared. We distinguish between lifetimes of variables in three contexts: Instance variables members of a class and created for each object of the class. In other words, every object of the class will have its own copies of these variables, which are local to the object. The values of these variables at any given time constitute the state of the object. Instance variables exist as long as the object they belong to exists. Static variables also members of a class, but not created for any object of the class and, therefore, belong only to the class. They are created when the class is loaded at runtime, and exist as long as the class exists.

3 SDTL SCOE-IT

01: Conversion from Fahrenheit to Celsius

Local variables (also called method automatic variables) declared in methods and in blocks and created for each execution of the method or block. After the execution of the method or lock completes, local (non-final) variables are no longer accessible.

A First Simple Program:/*This is a simple Java program. Call this file "Example.java".*/

class Example { // Your program begins with a call to main(). public static void main(String args[]) { System.out.println("This is a simple Java program."); } The main() Method The Java interpreter executes a method called main in the class specified on the command line. Any class can have a main() method, but only the main() method of the class specified to the Java interpreter is executed to start a Java application. The main() method must have public accessibility so that the interpreter can call it. It is a static method belonging to the class, so that no object of the class is required to start the execution. It does not return a value, that is, it is declared void. It always has an array of String objects as its only formal parameter. This array contains any arguments passed to the program on the command line. All this adds up to the following definition of the main() method:

public static void main(String[] args) { // ... } The above requirements do not exclude specification of additional modifiers or any throws clause The main() method can also be overloaded like any other method The Java interpreter ensures that the main() method, that complies with the above definition is the starting point of the program execution.

4 SDTL SCOE-IT

01: Conversion from Fahrenheit to Celsius

FAQs 1. What's the difference between J2SDK 1.5 and J2SDK 5.0? 2. What environment variables do I need to set on my machine in order to be able to run Java programs? 3. Do I need to import java.lang package any time? Why? 4. What is the difference between declaring a variable and defining a variable? 5. What is static in java? 6. What if I write static public void instead of public static void? 7. Can a .java file contain more than one java classes? 8. Is String a primitive data type in Java? 9. Is main a keyword in Java? 10. Is next a keyword in Java? 11. Is delete a keyword in Java? 12. Is exit a keyword in Java?

5 SDTL SCOE-IT

02 Prints a Payroll Statements

AIM

: Write a program that reads the following information and prints a Payroll statement:

Employee's name (e.g., Smith) Number of hours worked in a week (e.g., 10) Hourly pay rate (e.g., 6.75) Federal tax withholding rate (e.g., 20%) State tax withholding rate (e.g., 9%)

OBJECTIVE: To expose the concepts Class, Methods, Array

THEORY

Class:A class is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. Classes can (and usually do) get much more complex. The general form of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } } The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are 6 SDTL SCOE-IT

02 Prints a Payroll Statements

called members of the class. In most classes, the instance variables are acted upon and accessed by the methods defined for that class. Thus, it is the methods that determine how a class data can be used. Variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another.

A Simple Class
Here is a class called Box that defines three instance variables: width, height, and depth. Currently, Box does not contain any methods. class Box { double width; double height; double depth; } As stated, a class defines a new type of data. In this case, the new data type is called Box. You will use this name to declare objects of type Box. It is important to remember that a class declaration only creates a template; it does not create an actual object. To actually create a Box object, you will use a statement like the following: Box mybox = new Box(); // create a Box object called mybox After this statement executes, mybox will be an instance of Box. Thus, it will have physical reality. Every Box object will contain its own copies of the instance variables width, height, and depth. To access these variables, you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. For example, to assign the width variable of mybox the value 100, you would use the following statement: mybox.width = 100; This statement tells the compiler to assign the copy of width that is contained within the mybox object the value of 100. In general, you use the dot operator to access both the instance variables and the methods within an object.

/*A program that uses the Box class. Call this file BoxDemo.java */ 7 SDTL SCOE-IT

02 Prints a Payroll Statements

class Box { double width; double height; double depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; // assign values to mybox's instance variables mybox.width = 10; mybox.height = 20; mybox.depth = 15; // compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } }

Introducing Methods:Classes usually consist of two things: instance variables and methods. This is the general form of a method: type name(parameter-list) { // body of method } Here, type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The name of the method is specified by name. This can be any legal identifier other than those already used by other items within the current scope. The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Methods that have a return type other than void return a value to the calling routine using the following form of the return statement: return value; Here, value is the value returned. // This program includes a method inside the box class. class Box { double width; 8 SDTL SCOE-IT

02 Prints a Payroll Statements

double height; double depth; // display volume of a box void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // display volume of first box mybox1.volume(); // display volume of second box mybox2.volume(); } }

Array:

- An array is a group of like-typed variables that are referred to by a common name.

Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information. 9 SDTL SCOE-IT

02 Prints a Payroll Statements

One-Dimensional Arrays:A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must create an array variable of the desired type. The general form of a one dimensional array declaration is type var-name[ ]; Here, type declares the base type of the array. The base type determines the data type of each element that comprises the array. Thus, the base type for the array determines what type of data the array will hold. For example, the following declares an array named month_days with the type array of int: int month_days[];

Multidimensional Arrays: - In Java, multidimensional arrays are actually arrays of arrays.


These, as you might expect, look and act like regular multidimensional arrays. However, as you will see, there are a couple of subtle differences. To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two-dimensional array variable called twoD. int twoD[][] = new int[4][5]; This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int.

Alternative Array Declaration Syntax


There is a second form that may be used to declare an array: type[ ] var-name; Here, the square brackets follow the type specifier, and not the name of the array variable. For example, the following two declarations are equivalent: int al[] = new int[3]; int[] a2 = new int[3]; The following declarations are also equivalent: char twod1[][] = new char[3][4]; char[][] twod2 = new char[3][4]; This alternative declaration form is included as a convenience, and is also useful when specifying an array as a return type for a method. 10 SDTL SCOE-IT

02 Prints a Payroll Statements

FAQS 1. What if I do not provide the String array as the argument to the method? 2. What is the first argument of the String array in main method? 3. If I do not provide any arguments on the command line, then the String array of Main method will be empty or null? 4. Can I have multiple main methods in the same class? 5. What type of parameter passing does Java support? 6. What is the default value of an object reference declared as an instance variable? 7. Primitive data types are passed by reference or pass by value? 8. What wrapper classes and Why do we need? 9. What is the difference between error and an exception? 10. What happens if you dont initialize an instance variable of any of the primitive types in Java? 11. What will be the initial value of an object reference which is defined as an instance variable?

12. What are the different scopes for Java variables? 13. What is the default value of the local variables?

11 SDTL SCOE-IT

03: Design a Bank Account Class and manage account

AIM : Design a bank account class with constructor and methods to deposit, to withdraw from, change the name, charge a fee and print a summary of the account using toString() method. Use Account class to create and manage two bank accounts. OBJECTIVE THEORY Constructor:
: To expose the concepts of constructor, get and set methods.

- The main purpose of constructors is to set the initial state of an object when

the object is created by using the new operator. A constructor has the following general syntax: <accessibility modifier> <class name> (<formal parameter list>) <throws clause> // Constructor header { // Constructor body <local variable declarations> <nested local class declarations> <statements> } Constructor declarations are very much like method declarations. However, the following restrictions on constructors should be noted: 1. Modifiers other than an accessibility modifier are not permitted in the constructor header. 2. Constructors cannot return a value and, hence, cannot specify a return type, not even void, in the constructor header, but they can contain the simple form of the return statement in the constructor body. 3. Constructor name must be the same as the class name. Class names and method names exist in different namespaces.

12 SDTL SCOE-IT

03: Design a Bank Account Class and manage account

Example public class Name { Name() { // (1) System.out.println("Constructor"); } void Name() { // (2) System.out.println("Method"); } public static void main(String[] args) { new Name().Name(); // (3) Constructor call followed by method call. } } Output from the program: Constructor Method

Default Constructor:-A default constructor is a constructor without any parameters. In


other words, it has the following signature: <class name>() If a class does not specify any constructors, then an implicit default constructor is supplied for the class. The implicit default constructor is equivalent to the following implementation: <class name>() { super(); } // No parameters. Calls superclass constructor.

The only action taken by the implicit default constructor is to call the superclass constructor. This ensures that the inherited state of the object is initialized properly. In addition, all instance variables in the object are set to the default value of their type. In the following code, the class Light does not specify any constructors. class Light { // Fields int noOfWatts; boolean indicator; String location; // No constructors} 13 SDTL SCOE-IT // wattage // on or off // placement

03: Design a Bank Account Class and manage account

class Greenhouse { // ... Light oneLight = new Light(); // (1) Call of implicit default constructor. } In the previous code, the following implicit default constructor is employed when a Light object is created. Light () {super ();}

The accessor and mutator methods: - The role of accessors and mutators are to return
and set the values of an object's state.

Accessor Methods: - An accessor method is used to return the value of a private field. It
follows a naming scheme prefixing the word "get" to the start of the method name. For example let's add accessor methods for firstname, middleNames and lastname: //Accessor for firstName public String getFirstName() { return firstName; } //Accessor for middleNames public String getMiddlesNames() { return middleNames; } //Accessor for lastName public String getLastName() { return lastName; }

These methods always return the same data type as their corresponding private field (e.g., String) and then simply return the value of that private field.

14 SDTL SCOE-IT

03: Design a Bank Account Class and manage account

We can now access their values through the methods of a Person object: public class PersonExample { public static void main(String[] args) { Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall"); System.out.println(dave.getFirstName() + " " + dave.getMiddlesNames() + " " + dave.getLastName()); } }

Mutator Methods:-A mutator method is used to set a value of a private field. It follows a
naming scheme prefixing the word "set" to the start of the method name. For example, let's add mutator fields for address and username: //Mutator for address public void setAddress(String address) { this.address = address;} //Mutator for username public void setUsername(String username) { this.username = username;} These methods do not have a return type and accept a parameter that is the same data type as their corresponding private field. The parameter is then used to set the value of that private field. It's now possible to modify the values for the address and username inside the Person object: public class PersonExample { public static void main(String[] args) { Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall"); dave.setAddress("256 Bow Street"); dave.setUsername("DDavidson"); }}

15 SDTL SCOE-IT

03: Design a Bank Account Class and manage account

Why Use Accessors and Mutators?


It's easy to come to the conclusion that we could just change the private fields of the class definition to be public and achieve the same results. It's important to remember that we want to hide the data of the object as much as possible. The extra buffer provided by these methods allows us to:

Change how the data is handled behind the scenes Impose validation on the values that the fields are being set to.

Let's say we decide to modify how we store middle names. Instead of just one String we now use an array of Strings:

Class Member Access

FAQS: 1. What is user-defined exception in java? 2. What is the difference between a constructor and a method? 3. State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. 4. What if the main method is declared as private? 5. Can a public class MyClass be defined in a source file named YourClass.java? 6. Can main method be declared final?

16 SDTL SCOE-IT

04: Inherit Bank Account Class as Saving & Current

AIM : A class derived from Account that holds information about saving and current account also implements overrides method and print summary of saving and current account. OBJECTIVE
: To expose the concepts of inheritance and overriding.

THEORY Inheritance: -Inheritance is one of the cornerstones of object-oriented programming


because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass.

Inheritance Basics: - To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword. To see how, lets begin with a short example. The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.

// A simple example of inheritance. // Create a superclass. class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); }} // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k);} void sum() { System.out.println("i+j+k: " + (i+j+k)); 17 SDTL SCOE-IT

04: Inherit Bank Account Class as Saving & Current

}} class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); /* The subclass has access to all public members of its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); }} The output from this program is shown here: Contents of superOb: i and j: 10 20 Contents of subOb: i and j: 7 8 k: 9 Sum of i, j and k in subOb: i+j+k: 24

18 SDTL SCOE-IT

04: Inherit Bank Account Class as Saving & Current

As you can see, the subclass B includes all of the members of its superclass, A. This is why subOb can access i and j and call showij( ). Also, inside sum( ), i and j can be referred to directly, as if they were part of B. Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being a superclass for a subclass does not mean that the superclass cannot be used by itself. Further, a subclass can be a superclass for another subclass. The general form of a class declaration that inherits a superclass is shown here: class subclass-name extends superclass-name { // body of class } You can only specify one superclass for any subclass that you create. Java does not support the inheritance of multiple superclasses into a single subclass. (This differs from C++, in which you can inherit multiple base classes.) You can, as stated, create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass. However, no class can be a superclass of itself.

Using super:Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super .super has two general forms. The first calls the superclass constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass. Each use is examined here. Using super to Call Superclass Constructors A subclass can call a constructor method defined by its superclass by use of the following form of super: super(parameter-list); A parameter-list specifies any parameters needed by the constructor in the superclass super( ) must always be the first statement executed inside a subclass constructor.
THE JAVA To

see how super( ) is used, consider this example

// BoxWeight now uses super to initialize its Box attributes. class BoxWeight extends Box { 19 SDTL SCOE-IT

04: Inherit Bank Account Class as Saving & Current

double weight; // weight of box // initialize width, height, and depth using super() BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; }} Here, BoxWeight( ) calls super( ) with the parameters w, h, and d. This causes the Box( ) constructor to be called, which initializes width, height, and depth using these values. BoxWeight no longer initializes these values itself. It only needs to initialize the value unique to it: weight. This leaves Box free to make these values private if desired. In the preceding example, super( ) was called with three arguments. Since constructors can be overloaded, super( ) can be called using any form defined by the superclass. The constructor executed will be the one that matches the arguments. For example, here is a complete implementation of BoxWeight that provides constructors for the various ways that a box can be constructed. In each case, super( ) is called using the appropriate arguments. Notice that width, height, and depth have been made private within Box.

Overriding and Hiding Members


Under certain circumstances, a subclass may override non-static methods defined in the superclass that would otherwise be inherited. When the method is invoked on an object of the subclass, it is the new method implementation in the subclass that is executed. The overridden method in the superclass is not inherited by the subclass, and the new method in the subclass must uphold the following rules of method overriding: The new method definition must have the same method signature (i.e., method name and parameters) and the same return type. Whether parameters in the overriding method should be final is at the discretion of the subclass. A method's signature does not encompass the final modifier of parameters, only their types and order. The new method definition cannot narrow the accessibility of the method, but it can widen it. The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the super class. 20 SDTL SCOE-IT

04: Inherit Bank Account Class as Saving & Current

An instance method in a subclass cannot override a static method in the superclass. The compiler will flag this as an error. A static method is class-specific and not part of any object, while overriding methods are invoked on behalf of objects of the subclass. However, a static method in a subclass can hide a static method in the superclass. A final method cannot be overridden because the modifier final prevents method overriding. An attempt to override a final method will result in a compile-time error. However, an abstract method requires the non-abstract subclasses to override the method, in order to provide an implementation. Accessibility modifier private for a method means that the method is not accessible outside the class in which it is defined; therefore, a subclass cannot override it. However, a subclass can give its own definition of such a method, which may have the same signature as the method in its superclass.

Overriding vs. Overloading


Method overriding should not be confused with method overloading. Method overriding requires the same method signature (name and parameters) and the same return type. Only non-final instance methods in the superclass that are directly accessible from the subclass are eligible for overriding. Overloading occurs when the method names are the same, but the parameter lists differ. Therefore, to overload methods, the parameters must differ in type, order, or number. As the return type is not a part of the signature, having different return types is not enough to overload methods. FAQS: 1. Can an inner class declared inside of method access local variables of this method? 2. What's the main difference between a Vector and an ArrayList? 3. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces? 4. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it? 5. When you declare a method as abstract method? 6. Can I call a abstract method from a non abstract method 7. What is the difference between an Abstract class and Interface in Java ? or can you explain when you use Abstract classes ? 8. What is the purpose of garbage collection in Java, and when is it used? 9. What is the purpose of finalization? 10. What is the difference between static and non-static variables? 11. How are this() and super() used with constructors? 12. What are some alternatives to inheritance? 21 SDTL SCOE-IT

05: Implement equals () and hashCode() methods.

AIM OBJECTIVE

: Implementing equals () and hashCode() methods. : To expose the concepts of equals and hashCode method and apply.

THEORY

: The Java super class java.lang.Object has two very important methods defined in it. They are public boolean equals(Object obj) public int hashCode()

The equals () method:- This method checks if some other object passed to it as an
argument is equal to the object on which this method is invoked. The default implementation of this method in Object class simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. This particular comparison is also known as "shallow comparison". However, the classes providing their own implementations of the equals method are supposed to perform a "deep comparison"; by actually comparing the relevant data members. Since Object class has no data members that define its state, it simply performs shallow comparison The equals() method of java.lang.Object acts the same as the == operator; that is, it tests for object identity rather than object equality. The implicit contract of the equals() method, however, is that it tests for equality rather than identity. Thus most classes will override equals() with a version that does field by field comparisons before deciding whether to return true or false. To elaborate, an object created by a clone() method (that is a copy of the object) should pass the equals() test if neither the original nor the clone has changed since the clone was created. However the clone will fail to be == to the original object. For example, here is an equals() method you could use for the Car class. Two cars are equal if and only if their license plates are equal, and that's what this method tests for. public boolean equals(Object o) { if (o instanceof Car) { Car c = (Car) o; if (this.licensePlate.equals(c.licensePlate)) return true;} 22 SDTL SCOE-IT

05: Implement equals () and hashCode() methods.

return false; } This example is particularly interesting because it demonstrates the impossibility of writing a useful generic equals() method that tests equality for any object. It is not sufficient to simply test for equality of all the fields of two objects. It is entirely possible that some of the fields may not be relevant to the test for equality as in this example where changing the speed of a car does not change the actual car that's referred to. Be careful to avoid this common mistake when writing equals() methods: public boolean equals(Car c) { if (o instanceof Car) { Car c = (Car) o; if (this.licensePlate.equals(c.licensePlate)) return true; } return false; } The equals() method must allow tests against any object of any class, not simply against other objects of the same class (Car in this example.) You do not need to test whether o is null. null is never an instance of any class. null instanceof Object returns false. Here is an examples of a Book class that overrides equals() public class Book { ... public boolean equals(Object obj) { if (obj instanceof Book) return ISBN.equals((Book)obj.getISBN()); else return false; }
}

Consider this code that tests two instances of that Book class for equality
Book firstBook = new Book("0201914670"); //Swing Tutorial, 2nd edition

Book secondBook = new Book("0201914670");

23 SDTL SCOE-IT

05: Implement equals () and hashCode() methods.

if (firstBook.equals(secondBook)) { System.out.println("objects are equal"); } else { System.out.println("objects are not equal"); }

This program displays objects are equal even though firstBook and secondBook reference two distinct objects. They are considered equal because the objects compared contain the same ISBN number. You should always override the equals() method if the identity operator is not appropriate for your class

The hashCode() method :Hash code is not an unique number for an object.If two objects are equals(means ob1.equals(ob2))then these two objects return same hash code.so we have to implement hashcode() of a class in such way that if two objects are equals(that is compared by equal() of that class)then those two objects must return same hash code. Anytime you override equals() you should also override hashCode(). The hashCode() method should ideally return the same int for any two objects that compare equal and a different int for any two objects that don't compare equal, where equality is defined by the equals() method. This is used as an index by the java.util.Hashtable class. In the Car example equality is determined exclusively by comparing license plates; therefore only the licensePlate field is used to determine the hash code. Since licensePlate is a
String,

and since the String class has its own hashCode() method, we can sponge off of that.

public int hashCode() { return this.licensePlate.hashCode(); }

Other times you may need to use the bitwise operators to merge hash codes for multiple fields. There are also a variety of useful methods in the type wrapper classes (java.lang.Double,
java.lang.Float,

etc.) that convert primitive data types to integers that share the same bit

string. These can be used to hash primitive data types.

24 SDTL SCOE-IT

05: Implement equals () and hashCode() methods.

The following code exemplifies how all the requirements of equals and hashCode methods should be fulfilled so that the class behaves correctly and consistently with other Java classes. This class implements the equals method in such a way that it only provides equality comparison for the objects of the same class, similar to built-in Java classes like String and other wrapper classes.
public class Test { private int num; private String data; public boolean equals(Object obj) { if(this == obj) return true; if((obj == null) || (obj.getClass() != this.getClass())) return false; // object must be Test at this point Test test = (Test)obj; return num == test.num && (data == test.data || (data != null && data.equals(test.data))); } public int hashCode() { int hash = 7; hash = 31 * hash + num; hash = 31 * hash + (null == data ? 0 : data.hashCode()); return hash; } // other methods }

FAQS: 1. What would you use to compare two String variables - the operator == or the method equals 2. If you're overriding the method equals() of an object, which other method you might also consider? 3. What modifiers are allowed for methods in an Interface? 4. What is the catch or declare rule for method declarations?

25 SDTL SCOE-IT

06: Mini project

AIM . OBJECTIVE

: Mini project based on Object oriented programming Principle.

: To design a mini project using object oriented programming aspects.

INSTRUCTIONS

: 1. Form a group of two students. 2. Select a topic for Mini Project (E.g. Payroll system, student information system, etc.) 3. Use suitable object oriented programming aspects for designing a mini project.

26 SDTL SCOE-IT

Part II: - Client Side Technologies


07: Create a HTML page about Bank Account

AIM

: Study of Hyper Text Markup Language and there different tag and. Create a HTML page to display all information about bank account.

OBJECTIVE

: To expose the concepts of HTML, different tags.

THEORY

Introduction to Client side Programming.

What is Client-Side Programming


Browser is Universal Client Want power and appearance of application Increase functionality Provide more capable Graphic User Interface (GUI) Incorporate new types of information Move functionality from server to client

Advantages

Reduce load on server, network traffic, network delay Use client processing power and resources, scale with number of clients Localize processing where it is needed Can be simpler than using server side processing

Disadvantages

Possible need for client disk space and other resources Increased complexity of client environment Increased complexity of web pages Distribution and installation issues Reduced portability Security

Security Issues

Unauthorized access to machine resources: disk, cpu etc. o (e.g. format disk) Unauthorized access to information o (e.g. upload history, files) Denial of service o (e.g. crash machine

27 SDTL SCOE-IT

07: Create a HTML page about Bank Account

Techniques

Features of HTML 3.2 and extensions Browser-supported scripting languages Java Applets Combined approaches Dynamic HTML Client-side programming involves writing code that is interpreted by a browser

such as Internet Explorer or Mozilla Firefox or by any other Web client such as a cell phone. The most common languages and technologies used in client-side programming are HTML, JavaScript, Cascading Style Sheets (CSS) and Macromedia Flash.

- Introduction to HTML. HTML (Hypertext Markup Language) is used to create document on the World Wide Web. It is simply a collection of certain key words called Tags that are helpful in writing the document to be displayed using a browser on Internet. It is a platform independent language that can be used on any platform such as Windows, Linux, Macintosh, and so on. To display a document in web it is essential to mark-up the different elements (headings, paragraphs, tables, and so on) of the document with the HTML tags. To view a mark-up document, user has to open the document in a browser. A browser understands and interprets the HTML tags, identifies the structure of the document (which part are which) and makes decision about presentation (how the parts look) of the document.HTML also provides tags to make the document look attractive using graphics, font size and colors. User can make a link to the other document or the different section of the same document by creating Hypertext Links also known as Hyperlinks. HyperText Markup Language (HTML) is the language behind most Web pages. The language is made up of elements that describe the structure and format of the content on a Web page.Cascading Style Sheets (CSS) is used in HTML pages to separate formatting and layout from content. Rules defining color, size, positioning and other display aspects of elements are defined in the HTML page or in linked CSS pages.

28 SDTL SCOE-IT

07: Create a HTML page about Bank Account

HTML Skeleton.
An HTML page contains what can be thought of as a skeleton - the main structure of the page. It looks like this:
<html> <head> <title></title> </head> <body> <!--Content that appears on the page--> </body> </html>

.HTML

element.

Elements in HTML Documents


The HTML instructions, along with the text to which the instructions apply, are called HTML elements. The HTML instructions are themselves called tags, and look like <element_name> -that is, they are simply the element name surrounded by left and right angle brackets. Most elements mark blocks of the document for particular purpose or formatting: the above <element_name> tag marks the beginning of such as section. The end of this section is then marked by the ending tag </element_name> -- note the leading slash character "/" that appears in front of the element name in an end tag. End, or stop tags are always indicated by this leading slash character. For example, the heading at the top of this page is an H2 element, (a level 2 heading) which is written as:
<H2> 2.1 Elements in HTML </H2>.

The <head> Element The <head> element contains content that is not displayed on the page itself. Some of the elements commonly found in the <head> are:

29 SDTL SCOE-IT

07: Create a HTML page about Bank Account

Title of the page (<title>). Browsers typically show the title in the "title bar" at the top of the browser window.

Meta tags, which contain descriptive information about the page (<meta />) Script blocks, which contain javascript or vbscript code for adding functionality and interactivity to a page (<script>)

Style blocks, which contain Cascading Style Sheet rules (<style>). References (or links) to external style sheets (<link />).

The <body> Element The <body> element contains all of the content that appears on the page itself. Body tags will be covered thoroughly throughout this manual

Empty Elements
Some elements are empty -- that is, they do not affect a block of the document in some way. These elements do not require an ending tag. An example is the <HR> element, which draws a horizontal line across the page. This element would simply be entered as
<HR>

Upper and Lower Case


Element names are case insensitive. Thus, the the horizontal rule element can be written as any of <hr>, <Hr> or <HR>.

Elements can have Attributes


Many elements can have arguments that pass parameters to the interpreter handling this element. These arguments are called attributes of the element. For example, consider the element A, which marks a region of text as the beginning (or end) of a hypertext link. This element can have several attributes. One of them, HREF, specifies the hypertext document to which the marked piece of text is linked. To specify this in the tag for A you write:
<A HREF="http://www.somewhere.ca/file.html"> marked text </a>.

30 SDTL SCOE-IT

07: Create a HTML page about Bank Account

where the attribute HREF is assigned the indicated value. Note that the A element is not empty, and that it is closed by the tag </a>. Note also that end tags never take attributes -- the attributes to an element are always placed in the start tag.

Various Tags of HTML.


Tag <!--...--> <!DOCTYPE> <a> <abbr> <acronym> <address> <applet> <area /> <b> <base /> <basefont /> <bdo> <big> <blockquote> <body> <br /> <button> <caption> <center> <cite> <code> <col /> <colgroup> <dd> <del> <dfn> <dir> <div> <dl> Description Defines a comment Defines the document type Defines an anchor Defines an abbreviation Defines an acronym Defines contact information for the author/owner of a document Deprecated. Defines an embedded applet Defines an area inside an image-map Defines bold text DTD STF STF STF STF STF STF TF STF STF

Defines a default address or a default target for all links on a page STF Deprecated. Defines a default font, color, or size for the text in a page Defines the text direction Defines big text Defines a long quotation Defines the document's body Defines a single line break Defines a push button Defines a table caption Deprecated. Defines centered text Defines a citation Defines computer code text Defines attribute values for one or more columns in a table Defines a group of columns in a table for formatting Defines a description of a term in a definition list Defines deleted text Defines a definition term Deprecated. Defines a directory list Defines a section in a document Defines a definition list TF STF STF STF STF STF STF STF TF STF STF STF STF STF STF STF TF STF STF

31 SDTL SCOE-IT

<dt> <em> <fieldset> <font> <form> <frame /> <frameset> <h1> to <h6> <head> <hr /> <html> <i> <iframe> <img /> <input /> <ins> <isindex> <kbd> <label> <legend> <li> <link /> <map> <menu> <meta /> <noframes> <noscript> <object> <ol> <optgroup> <option> <p> <param /> <pre> <q> <s> <samp>

Defines a term (an item) in a definition list Defines emphasized text Defines a border around elements in a form Deprecated. Defines font, color, and size for text Defines an HTML form for user input Defines a window (a frame) in a frameset Defines a set of frames Defines HTML headings Defines information about the document Defines a horizontal line Defines an HTML document Defines italic text Defines an inline frame Defines an image Defines an input control Defines inserted text Deprecated. Defines a searchable index related to a document Defines keyboard text Defines a label for an input element Defines a caption for a fieldset element Defines a list item Defines the relationship between a document and an external resource Defines an image-map Deprecated. Defines a menu list Defines metadata about an HTML document Defines an alternate content for users that do not support frames Defines an alternate content for users that do not support clientside scripts Defines an embedded object Defines an ordered list Defines a group of related options in a select list Defines an option in a select list Defines a paragraph Defines a parameter for an object Defines preformatted text Defines a short quotation Deprecated. Defines strikethrough text Defines sample computer code

STF STF STF TF STF F F STF STF STF STF STF TF STF STF STF TF STF STF STF STF STF STF TF STF TF STF STF STF STF STF STF STF STF STF TF STF

32 SDTL SCOE-IT

<script> <select> <small> <span> <strike> <strong> <style> <sub> <sup> <table> <tbody> <td> <textarea> <tfoot> <th> <thead> <title> <tr> <tt> <u> <ul> <var> <xmp>

Defines a client-side script Defines a select list (drop-down list) Defines small text Defines a section in a document Deprecated. Defines strikethrough text Defines strong text Defines style information for a document Defines subscripted text Defines superscripted text Defines a table Groups the body content in a table Defines a cell in a table Defines a multi-line text input control Groups the footer content in a table Defines a header cell in a table Groups the header content in a table Defines the title of a document Defines a row in a table Defines teletype text Deprecated. Defines underlined text Defines an unordered list Defines a variable part of a text Deprecated. Defines preformatted text

STF STF STF STF TF STF STF STF STF STF STF STF STF STF STF STF STF STF STF TF STF STF

INSTRUCTIONS

: Use a various HTML Tags for designing a GUI for billing system.

FAQs: - 1.What is Client side programming? 2. Difference between client side and server side programming 3. What mark up language? 4. What is HTML? 5. What are the different html tags? 6. What is static and dynamic HTML?

33 SDTL SCOE-IT

08 Java Swing to display all information about bank account

AIM

: Implement the above banking system using java Swing to display all information about bank account..

OBJECTIVE

: To expose the concepts of Java Swing and GUI design.

THEORY

: Introduction

to Java Swing.

"Swing" refers to the new library of GUI controls (buttons, sliders, checkboxes, etc.) that replaces the somewhat weak and inflexible AWT controls

Main New Features


Lightweight. Not built on native window-system windows. Much bigger set of built-in controls. Trees, image buttons, tabbed panes, sliders, toolbars, color choosers, tables, text areas to display HTML or RTF, etc.

Much more customizable. Can change border, text alignment, or add image to almost any control. Can customize how minor features are drawn. Can separate internal representation from visual appearance.

"Pluggable" look and feel. Can change look and feel at runtime, or design own look and feel.

Many miscellaneous new features. Double-buffering built in, tool tips, dockable tool bars, keyboard accelerators, custom cursors, etc.

About JFC:

Java Foundation Classes o Enterprise-level Java functionality o Designed to create sophisticated front-end apps o Contained in Java 2 JFC includes these APIs: o AWT o 2D API o Drag & drop o Assistive technology o Swing

34 SDTL SCOE-IT

08 Java Swing to display all information about bank account

About Swing:

A GUI component framework o A set of Java classes and interfaces for creating graphical interfaces o A follow-on to AWT The Swing API provides: o A rich set of predefined components o A basis for creating sophisticated custom components

Importance of Swing

"Lightweight" components o Pure Java (no native counterpart) o Require less overhead A much richer set of components, including: o Database-bound tables o Trees o Toolbars o Progress bars o Buttons, menus and lists that use graphics More flexible than AWT Lets you: o Create non-rectangular components o Combine components o Customize look & feel (L&F) Sophisticated built-in features: o Tooltips o Borders and insets o Double-buffering for cleaner displays o Slow-motion graphics for debugging Additional Swing APIs for: o Sophisticated text editing (e.g. HTML, RTF) o Undo/redo

Swing vs. AWT

Swing is built on AWT o AWT provides interface to native components o JComponent extends java.awt.Container Swing has replacements for most AWT components o E.g. JButton, JLabel replace Button, Label What Swing uses from AWT: o Base classes: Component, Container Top-level containers: o Applet, Window, Frame, Dialog 35 SCOE-IT

SDTL

08 Java Swing to display all information about bank account

Layout managers Event handling

A Simple Swing Applet

Hello World applet o Ordinary Applet o Contains Swing label, textfield & button Illustrates: o Swing replacements for AWT components o Swing components added to an Applet o ToolTips
o

Java Swing class hierarchy


The class JComponent, descended directly from Container, is the root class for most of Swings user interface components.

36 SDTL SCOE-IT

08 Java Swing to display all information about bank account

HelloWorld Applet Code

Out Put of above Applet

FAQ: - 1.What is Swing? 2. What is JFC? 3. What are the different features of java Swing? 4. What is AWT? 5. What is difference between Swing and AWT? 37 SDTL SCOE-IT

09: Java Applet for Bank Account

AIM

: Implement a Java Applet application to display all information about bank account.

OBJECTIVE

: To expose the concepts of Java Applet.

THEORY

: 1.Introduction to Java Applet

Java is a programming language. Developed in the years 1991 to 1994 by Sun Microsystems. Programs written in Java are called applets. The first browser that could show applets was introduced in 1994, as "WebRunner" later known as "The HotJava Browser". An applet is a program written in the Java programming language that can be included in an HTML page. When you use a Java technology-enabled browser 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). Applet Program that runs in appletviewer (test utility for applets) Web browser (IE, Communicator)

Executes when HTML (Hypertext Markup Language) document containing applet is opened and downloaded

Applications run in command windows

38 SDTL SCOE-IT

09: Java Applet for Bank Account

39 SDTL SCOE-IT

09: Java Applet for Bank Account

40 SDTL SCOE-IT

09: Java Applet for Bank Account

FAQs: -

1.What java applet? 2. What is use of java applet? 3. How to execute a applet? 4. Difference between applet and Servlet? 5. Which class should import to execute applet.

41 SDTL SCOE-IT

10: JavaScript program to accept account number and display

AIM

: Implement a JavaScript program to accept account number and display all information of account.

OBJECTIVE

: To expose the concepts of JavaScript.

THEORY

: Introduction

to JavaScript Programming.

JavaScript is most commonly used as a client side scripting language. This means that JavaScript code is written into an HTML page. When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it's up to the browser to do something with it. JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari. Java script is language developed strictly for the web sites to create interactive web page that can handle calculations, controls such as displaying certain information when certain values provided, validate forms, and more without whole lot of programming effort. In short description, java script is easy programming language specifically designed to make web page elements interactive. An interactive element is one that responds to a user's input. It's developed by NetScape and is not connected to Java but has similaries with C and C++. JavaScript is case sensitive. Like the HTML java script uses open and close tags. Use the following syntax to start and end any java script codes. <script language="javascript"> put your java script statement here </script> <script> - Indicates the document is script language. <language> - Defines the script language, (eg: javascript, vbscript, etc). In this case, language is defined as javascript. </script> - Closes the script tag. // - This is a comment line for java script, which means the computer will not interpret this line as a code.

42 SDTL SCOE-IT

10: JavaScript program to accept account number and display

The following is simple java script program displaying a dialog box with the text This is java script dominated page and writes same text on the browser. <html> <head> </head> <body> <script language="javascript"> alert("This is a java script dominated page"); document.write("This is a java script dominated page"); </script> <body> <html> How it works We started this code with the start and close tags: Start <script language="javascript"> Close</script> Then we display a dialog box with this statement: alert("This is a java script dominated page") Alert is a method that displays the string within the brackets. Then we write same message on the browser using this statement: document.write("This is the java script dominated page") Document is an object means this page. Write is a method writes the string in the brackets to the browser. Java script code can be placed in the head or body section of the html document. The head section is best suited for all your functions and the body section is best for immediate execution code like the one above

43 SDTL SCOE-IT

10: JavaScript program to accept account number and display

Basic JavaScript Examples


Write text with JavaScript

<html> <body> <script type="text/javascript"> document.write("hello world "); </script> </body> </html> Output on web browser hello world

FAQs: -

1.What is JavaScript? 2. Use of JavaScript? 3. Which HTML tag is used for JavaScript? 4. Syntax of JavaScript? 5. What is client side scripting?

44 SDTL SCOE-IT

11: Mini project based on Part I and Part II

AIM OBJECTIVE

: Mini project based on Part I and Part II : Design and implement a Mini Project Based on Fundamental of Java Programming and client side programming.

THEORY

: 1. Problem Statement of project. 2. Description of Project. 3. Java concept used in Project.

INSTRUCTIONS

: 1. Form a group of two students. 2. Select a topic for Mini Project (E.g. Payroll system, student information system, etc.) 3. Use suitable Fundamental of Java Programming and client side Programming (e.g HTML, Java Applet, JavaScript) for Designing a mini project.

45 SDTL SCOE-IT

Part III: - Server side Programming


12: Study of Servelets, JSP, JDBC API

AIM OBJECTIVE

: Study of Servelets, JSP, JDBC API and tomcat server. : To expose the concepts of Java Servlets, JSP,JDBC,tomcat server.

THEORY

: 1. Introduction to Server Side Programming. 2. Study of JSP 3. Study of JDBC 4. Tomcat server

INSTRUCTIONS

: 1. Introduction to Server Side Programming.

Server-side scripting is a web server technology in which a user's request is fulfilled by running a script directly on the web server to generate dynamic web pages. It is usually used to provide interactive web sites that interface to databases or other data stores. This is different from client-side scripting where scripts are run by the viewing web browser, usually in JavaScript. The primary advantage to server-side scripting is the ability to highly customize the response based on the user's requirements, access rights, or queries into data stores. .

46 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Advantages of Server Side Programs


The list below highlights some of the important advantages of Server Side programs. i. All programs reside in one machine called the Server. Any number of remote machines (called clients) can access the server programs. ii. New functionalities to existing programs can be added at the server side which the clients can advantage without having to change anything from their side. iii. Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be done at the server side without having to bother about clients hardware or software capabilities. iv. Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by service side applications. v. They are portable and possess the capability to generate dynamic and user-based content (e.g. displaying transaction information of credit card or debit card depending on users choice).

Types of Server Side Programs


Active Server Pages (ASP) Java Servlets Java Server Pages (JSPs) Enterprise Java Beans (EJBs)

Introduction to Java Servlet.


A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

47 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

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. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

Life cycle of servlets.


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. . If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's
destroy

method.

Overview of web containers:


This provides the basic introduction to J2EE web containers (Also called Servlet container or Servlet engine). In J2EE architecture the basic purpose of the container is to provide the runtime environment for the components. components are managed by container, in order to be managed by container components must follow certain contract. J2EE specification defines contract between components and container, and specifies the deployment model for components. Contract specifies how components should be developed and deployed, and how components can access services provided by container. When developing applications with J2EE, we develop components that follow the contract defined in the specification. 48 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

In J2EE this contract is specified in term of various interfaces and classes, developer writes the classes that implements this interfaces or extends the classes and provides appropriate implementation of various methods and rest will be done by container. Container takes the responsibility of instantiating, initializing and invoking the components. Application does not directly instantiate or invokes components. As you will see that application never instantiate an object of servlet or call any of the init(), service() or destroy() life cycle method, all of these is handled by web container. Web container automatically instantiates and initializes the Servlets on application startup or when invoked for the first time. Container calls the service() method when user requests the servlet. The web container is a Java runtime environment which is responsible for managing life cycle of JSP pages and Servlets. A web container is responsible for instantiating, initializing and invoking Servlets and JSP pages. The web container implements Servlet and JSP API and provide infrastructure for deploying and managing web components. The web container is part of web server or application server that provides the network services over which request and response are sent. A Web container is may be built into the web server or it may be installed as an additional component to a web server. As per the specification, all web containers must support HTTP protocol however it may support addition protocols like HTTPS. Web container is also called servlet container or servlet engine. We will use Tomcat throughout all the tutorials. Tomcat is an open source web server, which is the web container reference implementation. You can find more information about tomcat at http://tomcat.apache.org/. If you have not already downloaded and installed Tomcat, read this tutorial Setting up a Servlet development environment which explains how to install tomcat and setup the environment. We will need to setup the development environment to run the various examples and code sameples given throughout the tutorials. Note: Servlets and JSP pages are collectively called web components.

Setting up a Servlet development environment


List of required softwares:

49 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

1. JAVA 1.5 or 1.6 2. Tomcat 5.5.16 3. eclipse 3.3

Note: this tutorial explains how to install required software on your windows based PC only. First of all you need the Java software development kit 1.5 or 1.6 (JAVA SDK) installed. Checking if JAVA is already installed in your system Follow this step to check if Java software development kit (JDK) is already installed in your system.To determine if JAVA SDK is already installed in your system, run the following command from command prompt. > Java version If JAVA platform is already installed, it will display the version of the JAVA SDK. Below screen shows JAVA version 1.6 running on a windows system. If command executes successfully and shows JAVA version 1.6, you can skip the next step.otherwise download and install the Java SDK as explained in next step.

Install JAVA SDK

50 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

First thing you need to install is Java software development kit (Java SDK) . Download the Java development kit 6 (JDK 6) from Sun Java SE Download site. Current latest version is JDK 6 update 6. Set up the JAVA_HOME environment variable Once the JAVA SDK is installed follow this step to set the JAVA_HOME environment variable. If JAVA_HOME variable is already set, you can skip this step. Right click on My Computer icon on your desktop it will open a popup menu, click on properties, it will open the system properties window, then click on advanced tab.

Click on environment variables button, it will open the environment variables window as shown in figure below. Initially there will be no JAVA_HOME environment variable set as shown in figure. 51 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Click on new button to add new system variable JAVA_HOME.

In the variable name filed, enter JAVA_HOME. Specify the path to root directory of JAVA installation in variable value field and click OK button. Now JAVA_HOME will appear under user variables. Next you need to add bin directory under the root directory of JAVA installation in PATH environment variable.Select the PATH variable from System variables and click on Edit button. Add: ;%JAVA_HOME%\bin; at the end of variable value field and click OK button. 52 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Now verify that everything is correct by following the step: Checking if JAVA is already installed in your system. It should show the version of the installed JAVA SDK. Installing Tomcat Tomcat is an opensource web container. it is also web container reference implementation. You will need tomcat 5.5.16 installed on your system to test various servlet and JSP examples given in other tutorials. Download the latest version of tomcat from here . Download the jakarta-tomcat-5.0.28.tar.gz and extract it to the directory of your choice. Note: This directory is referred as TOMCAT_HOME in other tutorials. Thats all, tomcat is installed. Its very easy, isnt it? Starting and shutting down Tomcat To start the tomcat server, open the command prompt, change the directory to TOMCAT HOME/bin and run the startup.bat file. It will start the server. > startup To shut down the tomcat server, run the shutdown.bat file. It will stop the server. > shutdown Verifying Tomcat installation

53 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

To verify that tomcat is installed properly, start the server as explained above, open the web browser and access the following URL. http://localhost:8080/index.jsp It should show the tomcat welcome page, if tomcat is installed properly and server is running. Setting up the CLASSPATH Now you need to create a new environment variable CLASSPATH if it is not already set. We need to add the servlet-api.jar into the CLASSPATH to compile the Servlets. Follow the same steps as you did to create the JAVA_HOME variable. Create a new variable CLASSPATH under system variables. Add TOMCAT_HOME/lib/servlet-api.jar in variable value field. Note: here TOMCAT_HOME refers to the tomcat installation directory. Introduction to Java Servlets Now you have the basic understanding of the HTTP protocol, web containers, and J2EE web application structure. Before you start learning Servlet API, this tutorial provides the basic understanding of the Java Servlets.

What is a servlet?
Servlets are Java classes that process the request dynamically and generate response independent of the protocol. Servlets are defined in Java Servlet API specification. API Servlets are server side Java programs which extends the functionality of web server. Servlet are protocol independent that means it can be used virtually with any protocol to process the request and generate the response. However in practice Servlets are used to process the HTTP requests and generate the HTML response. If you are not in web development already and not aware of server side programming languages, a question which may arise in your mind is: if the Servlets generates the HTML than why do we need the Servlets? We can simply create the HTML pages instead and deploy them in any web server. The answer is in the term dynamic request handling. If you create the HTML pages which 54 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

are directly served by web server, it is not a dynamic web application. A HTML document is not dynamic. It is a simple static content which is served as it is whenever a request is received. Servlets are used to generate the response dynamically based on the user request. The dynamic response generation is achieved by embedding the application logic in HTTP request-response process. The initial goal of the HTTP protocol was to enable the sharing of information over the internet. HTTP defines what makes a valid request and valid response, how clients can request information and how server can send response, but it does not define how the response could be generated. That means HTTP protocol does not define any way to incorporate the application logic in response generation. Here the server-side technologies like PHP, ASP, Java Servlets and Java server pages come into picture. These technologies provide the way to write the application logic which sits in between the request handling and response generation phases and generate the response dynamically based on the information present in the request. Lets see how it is achieved with Servlets: Whenever the web container receives a HTTP request for a resource, based on the URL of the incoming request, web container determines if the request should be handled by a servlet. If the request is to be handled by a servlet, the container checks to see if the instance of the servlet is already available. If an instance is available, the container delegates the request to that instance. If no instance of the servlet is available, container creates a new instance of the class of servlet and delegates the request to that newly created instance.When delegating the request to a servlet for processing, web container creates the objects of class HttpServletRequest and HttpServletResponse which represents the HTTP request and HTTP response and passes these objects to the Servlet instance. The instance of HttpServletRequest provides servlet the access to incoming HTTP request information, like HTTP headers, form parameters, query string etc. The instance of HttpServletResponse provides the way to send the response to the client. It provides the methods to write the HTML to the output stream to the client, add response headers, add cookies etc.

55 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

During the request processing, the code within the servlet reads the request information, executes the application logic, and generates the response. Once the processing has been completed the response is returned to the client by writing it to the HttpServletResponse. A simple HTML form processing servlet example 1. How to write HTML forms 2. How to forward request from a servlet to a JSP 3. How to read form parameters from request object 4. How to process HTML form input elements like text box, password fields, text area, radio button and checkbox 5. How to generate response from servlet. 6. How to define servlet and servlet mapping in web.xml Create HTML Form Copy following code into form.jsp file under /pages directory. <%@ page contentType="text/html; charset=ISO-8859-1"%> <html> <head> <title>A simple form processing Servlet example</title> </head> <body> <h3>User registration example</h3> <form action="formServlet" method="post"> <table> <tr> <td>User Name</td> <td><input type="text" name="username"></td> </tr> <tr> <td>Password</td> <td><input type="password" name="password"></td> </tr> <tr> <td>Bio</td> <td><textarea rows="5" cols="50" name="bio"></textarea> </td> </tr> <tr> <td>Country</td> <td> 56 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

<select name="country"> <option value="ind">India</option> <option value="usa">America</option> <option value="ca">Canada</option> <option value="aus">Australia</option> </select> </td> </tr> <tr> <td>Subscribe for newsletter</td> <td> <label for="newsletter1">Yes</label> <input type="radio" id="newsletter1" name="newsletter" value="Yes" checked="checked"> <label for="newsletter2">No</label> <input type="radio" id="newsletter2"name="newsletter" value="No"> </td> </tr> <tr> <td>Preferences</td> <td> <label for="preference1">Receive members</label> <input type="checkbox" id="preference1" name="receivemail" value="yes" checked="checked"><br/> <label for="preference2">Receive notifications</label> <input type="checkbox" id="preference2" name="receivenotification" value="yes"><br/> </td> </tr> <tr> <td> <input type="submit" value="Submit">&nbsp; <input type="reset"> </td> <td></td> </table> </form> </body> </html>

mail

from

Create a Servlet to process HTML form submission

57 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Copy following code into FormServlet.java, compile the class and put it under WEB-INF/classes directory import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class FormServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { getServletContext().getRequestDispatcher("/WEBINF/pages/form.jsp").forward(req, resp); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("username"); String password = request.getParameter("password"); String bio = request.getParameter("bio"); String country = request.getParameter("country"); String subscribeForNewsletter = request.getParameter("newsletter"); String receiveMail = request.getParameter("receivemail"); String reveiveNotifications = request.getParameter("receivenotification"); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.write("<h2> You have entered following values </h2>"); writer.write("<br/>"); writer.write("<table>"); startTableRow(writer); addTableColumn(writer, "username"); addTableColumn(writer, userName); closeTableRow(writer); startTableRow(writer); addTableColumn(writer, "password"); addTableColumn(writer, password); closeTableRow(writer); startTableRow(writer); 58 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

addTableColumn(writer, "Bio"); addTableColumn(writer, bio); closeTableRow(writer); startTableRow(writer); addTableColumn(writer, "Country"); addTableColumn(writer, country); closeTableRow(writer); startTableRow(writer); addTableColumn(writer, "Subscribe for news letter"); addTableColumn(writer, subscribeForNewsletter); closeTableRow(writer); startTableRow(writer); addTableColumn(writer, "Receive mail from members"); addTableColumn(writer, receiveMail); closeTableRow(writer); startTableRow(writer); addTableColumn(writer, "Receive notification"); addTableColumn(writer, reveiveNotifications); closeTableRow(writer); writer.write("</table>"); writer.close(); } private static void startTableRow(PrintWriter writer) { writer.write("<tr>"); } private static void closeTableRow(PrintWriter writer) { writer.write("</tr>"); } private static void addTableColumn(PrintWriter writer, String value) { writer.write("<td> "+ value + "</td>"); }

} Define servlet in deployment descriptor (web.xml) A servlet must be defined into web.xml deployment descriptor. Copy the following code into web.xml file and save it under WEB-INF directory. <?xml version="1.0" encoding="ISO-8859-1"?> 59 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <servlet> <servlet-name>formServlet</servlet-name> <servlet-class>FormServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>formServlet</servlet-name> <url-pattern>formServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/formServlet</welcome-file> </welcome-file-list> </web-app> Deploy form processing servlet application to tomcat server You just need to create war file of our web application and copy it to webapp directory under your tomcat installation to deploy application to tomcat. Open command prompt and go to root directory of our application (FormExample). Create a war file using following command. jar -cvf formexample.war * It will create formexample.war file under FormExample directory. Copy the war file to webapp directory under tomcat installation.

Thats it, now you are ready to start the tomcat server and see example in action. Setting up a Servlet development environmentupApplet Servlet Communication Example

Simple Servlet example 60 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

You have learned about J2EE web containers,J2EE web application structure and basics of Java Servlets in previousServlet tutorials. This Servlet tutorial provides a very simple servlet example. What is covered in this Servlet example 1. How to write the servlet class. 2. How to compile the Servlet class. 3. How to extract the HTML form parameters from HttpServletRequest. 4. web.xml deployment descriptor file. 5. How to create the war (web application archive) file. 6. How to deploy and run the sample web application in tomcat web container. You need the Java SDK and tomcat web server installed, to run the example Servlet application developed in this tutorial. Setting up the Servlet development environment tutorial explains how to setup the development environment. If you dont have the basic understanding of the J2EE web containers and web application structure, read the previous Servlet tutorials which explain these basic things. This is a very simple web application containing a HTML file and a servlet. The HTML document has a form which allows the user to enter the name, when the form is submitted application displays the welcome message to the user. First of all we need to create the directory structure for our sample web application as explained in the tutorialUnderstanding the directory structure of web applications. Create the directory structure as shown in below figure.

61 SDTL SCOE-IT

Create the HTML file. Copy the following code into form.html file and save it under servlet-example/pages directory. <html> <head> <title>The servlet example </title> </head> <body> <h1>A simple web application</h1> <form method="POST" action="WelcomeServlet"> <label for="name">Enter your name </label> <input type="text" id="name" name="name"/><br><br> <input type="submit" value="Submit Form"/> <input type="reset" value="Reset Form"/> </form> 62 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

</body> </html> The welcome Servlet class Copy the following code into WelcomeServlet.java file and save it under servlet-example/WEBINF/src/jsptube/tutorials/servletexample directory. Note: it is not necessary to crate /src directory under WEB-INF directory and you can safely exclude WEB-INF/src directory when creating WAR file. You can put the source files any where you want, but dont forget to put the compiled classes into WEB-INF/classes directory before creating the WAR file. package jsptube.tutorials.servletexample; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WelcomeServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { super.init(config); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * Get the value of form parameter */ String name = request.getParameter("name"); String welcomeMessage = "Welcome "+name; /* * Set the content type(MIME Type) of the response. */ response.setContentType("text/html"); PrintWriter out = response.getWriter(); 63 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

/* * Write the HTML to the response */ out.println("<html>"); out.println("<head>"); out.println("<title> A very simple servlet example</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>"+welcomeMessage+"</h1>"); out.println("<a href="/servletexample/pages/form.html">"+"Click here to go back to input page "+"</a>"); out.println("</body>"); out.println("</html>"); out.close(); }

public void destroy() { } } Now

compile

the

servlet

class

as

explained

below.

Open the command prompt and change the directory to the servlet-example/WEBINF/src/jsptub/tutorials/servletexample directory. Compile the WelcomeServlet.java using the following command.javac WelcomeServlet.java It will create the file WelcomeServlet.class in the same directory. Copy the class file to classes directory. All the Servlets and other classes used in a web application must be kept under WEB-INF/classes directory. Note: to compile a servlet you need to have servlet-api.jar file in the class path. The deployment descriptor (web.xml) file. Copy the following code into web.xml file and save it directly under servlet-example/WEB-INF directory. <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>jsptube.tutorials.servletexample.WelcomeServlet</servlet-class> </servlet> <servlet-mapping>
12: Study of Servelets, JSP, JDBC API

64 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

<servlet-name>WelcomeServlet</servlet-name> <url-pattern>/WelcomeServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> /pages/form.html </welcome-file> </welcome-file-list> </web-app> Create the WAR (Web application archive) file. Web applications are packaged into a WAR (web application archive). There are many different ways to create a WAR file. You can use jar command, ant or an IDE like Eclipse. This tutorial explains how to create the WAR file using jar tool. Open the command prompt and change the directory to the servlet-example directory, and execute the following command. jar cvf servletexample.war * This command packs all the contents under servlet-example directory, including subdirectories, into an archive file called servletexample.war.

We used following command-line options:


-c option to create new WAR file. -v option to generate verbose output. -f option to specify target WAR file name.

You can use following command to view the content of servletexample.war file. Jar tvf servletexample.war. This command lists the content of the WAR file. Deploying the application to tomcat web container. Deployment steps are different for different J2EE servers. This tutorial explains how to deploy the sample web application to tomcat web container. If you are using any other J2EE server, consult the documentation of the server. 65 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

A web application can be deployed in tomcat server simply by copying the war file to <TOMCAT_HOME>/webapp directory.

Copy servletexample.war to <TOMCAT_HOME>/webapp directory. Thats it! You have successfully deployed the application to tomcat web server. Once you start the server, tomcat will extract the war file into the directory with the same name as the war file. To start the server, open the command prompt and change the directory to

<TOMCAT_HOME/bin> directory and run the startup.bat file. Our sample application can be accessed at http://localhost:8080/servletexample/. If tomcat server is running on port other than 8080 than you need to change the URL accordingly. If the application has been deployed properly, you should see the screen similar to below when you open the application in browser.

Enter your name in text box and click on submit button. It will display welcome message with your name as shown in below figure.

66 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

The next step is to understand how the application works. How the application works. When you access the application by navigating to URL http://localhost:8080/servletexample/ the web server serves the form.html file. \pages\form.html file is specified as welcome file in web.xml file so web server serves this file by default. When you fill the form field and click on submit form button, browser sends the HTTP POST request with name parameter. Based on the servlet mapping in web.xml, the web container delegates the request to WelcomeServlet class. When the request is received by WelcomeServlet it performs following tasks.

Extract the name parameter from HttpServletRequest object. Generate the welcome message. Generate the HTML document and write the response to HttpServletResponse object.

Browser receives the HTML document as response and displays in browser window.

67 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

The next step is to understand the code. Understanding the code. Package declaration WelcomeServlet class is a part of jsptube.tutorials.servletexample package. First line of code declaresthepackage. package jsptube.tutorials.servletexample; Import servlet packages: The Java servlet API consists of two packages: javax.servlet and javax.servlet.http. Of these two packages, the javax.servlet package contains classes and interfaces that are independent of HTTP protocol. javax.servlet.http package contains classes and interfaces that are specific to HTTP protocol. The next lines of code import the required classes and interfaces. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; These are the most common classes and interfaces that you will need to import in every servlet. Servlet class declaration: Next line of code declares the WelcomeServlet class. public class WelcomeServlet extends HttpServlet { Every servlet class needs to implement javax.servlet.Servlet interface. HttpServlet class provides HTTP specific implementation of Servlet interface. Generally Servlets in web application implements javax.servlet.Servlet interface indirectly by extending javax.servlet.http.HttpServlet class.

68 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

The init() method: Next lines of code declares the init() method. Init() method is a Servlet life cycle method and defined in javax.servlet.Servlet interface. public void init(ServletConfig config) throws ServletException { super.init(config); } Init() method is used to initialize the servlet. In our example servlet, init() method doesnt do anything, it just calls the super class version of the method. Service the HTTP POST request: Next lines of code declares the doPost() method. doPost() method is defined in HttpServlet class. doPost() method is used to handle the HTTP POST request. This method takes HttpSevletRequest and HttpServletResponse objects as arguments. HttpServletRequest object encapsulates the information contained in the request. HttpServletResponse object encapsulates the HTTP response. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br /> You may wonder why there is no service() method defined in the WelcomeServlet class. The answer is: because it is implemented by HttpServlet class. HttpServlet class provides the implementation of service() method which calls either doGet() or doPost() method based on the HTTP request method. Since we have used POST method in our HTML form, doPost() is called. Extract request parameters from HttpServletRequest object. Following line of code extracts the value of name parameter. String name = request.getParameter("name"); getParameter() method of HttpServletRequest interface is used to extract the value of form parameters. getParameter() method takes the name of the form field as String argument and returns whatever user has entered into the form as String value.

69 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

The next line is very simple it constructs the welcome message. String welcomeMessage = "Welcome "+name; Generate Response: The next line sets the content type of the response, in out example, this is text/html. response.setContentType("text/html"); Response can be returned to the client by writing to the java.io.PrintWriter object associated with ServletResponse. Following line obtains the PrintWriter object from HttpServletResponse object. PrintWriter out = response.getWriter();<br /> Following lines of code writes the HTML to the response. out.println("<html>"); out.println("<head>"); out.println("<title> A very simple servlet example</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>"+welcomeMessage+"</h1>"); out.println("<a href="/servletexample/pages/form.html">"+"Click here to go back to input page "+"</a>"); out.println("</body>"); out.println("</html>");

70 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Close out.close();

the

PrintWriter

object.

Destroy() method: Next lines of code declares the destroy() method. Destroy() method is a servlet life cycle method and defined in javax.servlet.Servlet interface. public void destroy() { }

Destroy method is called by the web container when removing servlet instance out of service or when the server is shutting down. The web.xml Deployment descriptor file: Web.xml file is called the deployment descriptor, it includes the configuration of our web application. The first line in the deployment descriptor specifies the version of the XML and encoding used. Following lines declares the XML name space. <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=http://java.sun.com/xml/ns/javaee app_2_5.xsd version="2.5"> Next is the servlet definition. Every Servlets in a web application must be defined in the web.xml file using <servlet> tag. Following lines defines the WelcomeServlet. <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>jsptube.tutorials.servletexample.WelcomeServlet</servlet-class> http://java.sun.com/xml/ns/javaee/web-

71 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

</servlet> Servlet-name tag specifies the name of the servlet, this name is used later in servlet-mapping. Servlet-class specifies the fully qualified class name of the servlet.

Next is servlet mapping. Servlet mapping is used to map the URLs to a servlet. The following servlet mapping definition specifies that the request for the URL /WelcomeServlet should be handled by WelComeServlet class. <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/WelcomeServlet</url-pattern> </servlet-mapping> We have used /WelcomeServlet as the value of action attribute in the HTML form. <form method="POST" action="/WelcomeServlet">

So when the form is submitted, browser sends the POST request to path /WelcomeServlet which is than handled by WelcomServlet class. Next is welcome file list. Any public resource, such as an HTML or JSP document, can be specified as a welcome file using the <welcome-file-list> element in the deployment descriptor. When you type the URL path pointing to a web application (for example

http://localhost:8080/servletexample), the web container displays the welcome file automatically. Following lines specifies /pages/form.html as the welcome file. So when you access the URL http://localhost:8080/servletexample, web container server pages/form.html file. <welcome-file-list> <welcome-file> /pages/form.html </welcome-file>

72 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

</welcome-file-list> Next line ends the <web-app> tag. </web-app> Congratulations! You have learned how to develop simple web applications using Servlets. Source code of this tutorial is attached here. I suggest that you download the source code and try to run the application on your computer and see how it works.

2. Introduction to JDBC.
JDBC stands for Java Database Connectivity, which is a standard Java API for databaseindependent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks commonly associated with database usage: Making a connection to a database Creating SQL or MySQL statements Executing that SQL or MySQL queries in the database Viewing & Modifying the resulting records Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as: Java Applications Java Applets Java Servlets Java ServerPages (JSPs) Enterprise JavaBeans (EJBs) All of these different executables are able to use a JDBC driver to access a database and take advantage of the stored data.JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code. 73 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC Architecture consists of two layers: 1. JDBC API: This provides the application-to-JDBC Manager connection. 2. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection. The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application:

Common JDBC Components:


The JDBC API provides the following interfaces and classes:

74 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

DriverManager: This interface manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection. Driver: This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manage objects of this type. It also abstracts the details associated with working with Driver objects Connection: Interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only. Statement: You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures. ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. SQLException: This class handles any errors that occur in a database application.

What is a JDBC driver?


The JDBC API defines the Java interfaces and classes that programmers use to connect to databases and send queries. A JDBC driver implements these interfaces and classes for a particular DBMS vendor. A Java program that uses the JDBC API loads the specified driver for a particular DBMS before it actually connects to a database. The JDBC DriverManager class then sends all JDBC API calls to the loaded driver. The four types of JDBC drivers are:

JDBC-ODBC bridge plus ODBC driver, also called Type 1. 75 SCOE-IT

SDTL

12: Study of Servelets, JSP, JDBC API

Translates JDBC API calls into Microsoft Open Database Connectivity (ODBC) calls that are then passed to the ODBC driver. The ODBC binary code must be loaded on every client computer that uses this type of driver.

Native-API, partly Java driver, also called Type 2. Converts JDBC API calls into DBMS-specific client API calls. Like the bridge driver, this type of driver requires that some binary code be loaded on each client computer.

JDBC-Net, pure Java driver, also called Type 3. Sends JDBC API calls to a middle-tier net server that translates the calls into the DBMSspecific network protocol. The translated calls are then sent to a particular DBMS.

Native-protocol, pure Java driver, also called Type 4. Converts JDBC API calls directly into the DBMS-specific network protocol without a middle tier. This allows the client applications to connect directly to the database server.

Describe the JSP technology.


JavaServer Pages (JSP) technology provides a simplified, fast way to create dynamic web content. JSP technology enables rapid development of web-based applications that are serverand platform-independent. JavaServer Pages (JSP) is a Java technology that helps software developers serve dynamically generated web pages based on HTML, XML, or other document types JSP pages typically comprise of:

Static HTML/XML components. Special JSP tags Optionally, snippets of code written in the Java programming language called "scriptlets."

JSP Advantages
Write Once Run Anywhere: JSP technology brings the "Write Once, Run Anywhere" paradigm to interactive Web pages. JSP pages can be moved easily across platforms, and across web servers, without any changes. 76 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Dynamic content can be served in a variety of formats: There is nothing that mandates the static template data within a JSP page to be of a certain format. Consequently, JSP can service a diverse clientele ranging from conventional browsers using HTML/DHTML, to handheld wireless devices like mobile phones and PDAs using WML, to other B2B applications using XML. Recommended Web access layer for n-tier architecture: Sun's J2EE Blueprints, which offers guidelines for developing large-scale applications using the enterprise Java APIs, categorically recommends JSP over servlets for serving dynamic content. Completely leverages the Servlet API: If you are a servlet developer, there is very little that you have to "unlearn" to move over to JSP. In fact, servlet developers are at a distinct advantage because JSP is nothing but a high-level abstraction of servlets. You can do almost anything that can be done with servlets using JSP--but more easily!

JSP using scripting elements, page directive and standard tags.


List of the tags used in Java Server Pages:

Declaration tag Expression tag Directive tag Scriptlet tag Action tag

Declaration tag: Declaration tag is used to define functions, methods and variables that will be used in Java Server Pages. Notation of the Declaration tag is shown below: <%! %>

77 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

At the start of Declaration tag one must place <%! Inside Declaration tag one can declare variables or methods. Declaration tag ends with the notation %>. Also care must be taken to place a semicolon that is ; at the end of each code placed inside Declaration tag.

Directive tag:
The directive tag gives special information about the page to JSP Engine. This changes the way JSP Engine processes the page. Using directive tag, user can import packages, define error handling pages or session information of JSP page. General notation of directive tag is as follows: There are three types of directive tag.
page Include Tag Lib

Syntax and usage of directive tag

Page directive:
General syntax for the page directive is <%@ page optional attribute ... %> There are many optional attributes available for page directive. Each of these attributes are used to give special processing information to the JSP Engine changing the way the JSP Engine processes the page. Some of the optional attributes available for page directive are:

language extends import session buffer autoFlush isThreadSafe info errorPage IsErrorPage contentType

Syntax and usage of some of the optional attributes available for page directive discussed below.

78 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Language: This attribute is used to denote the language used by a file. Language denotes the scripting language used in scriptlets, declarations, and expressions in the JSP page and any included files.

Syntax of language attribute available for page directive is <%@ page language = "lang" %> In the above statement page and language are keywords and one places whatever language " ". the file uses inside For example if one wants to mention the language as java which is generally mentioned for all it is done as shown below: <%@ page language = "java" %>

Extends:
This is used to signify the fully qualified name of the Super class of the Java class used by the JSP engine for the translated Servlet. Syntax of extends attribute available for page directive is <%@ page extends = "package.class"%> In the above statement page and extends are keywords.

Import:
The import attribute is used to import all the classes in a java package into the current JSP page. With this facility, the JSP page can use other java classes. Syntax of import attribute available for page directive is <%@ page import = "java.util.*" %> In the above statement page and import are keywords. If there are many Java packages that the JSP page wants to import, the programmer can use import more than once in a JSP page or separate the Java packages with commas, as shown below: <%@ page import="{package.class | package.*}, ..." %>

79 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Session:
The session attribute, when set to true, sets the page to make use of sessions. NOTE: by default, the session attribute value is set to true therefore, all JSP pages have session data available. If the user sets the session attribute to false, it should be performed in this section. When the session attribution is set to false, the user cannot use the session object, or a <jsp:useBean> element with scope=session in the JSP page which, if used, would give error. Syntax of session attribute available for page directive is <%@ page session="true|false" %> In the above statement page and session are keywords. And either true or false value can be setted and by default the value is true. General syntax of Declaration Tag: <%! statement2; //start //variables of or declaration methods tag statement1; declaration ..........; ..........;

%>

//end of declaration tag

For example:

<%! private private %> int int example test = = 0 5 ; ;

Expression tag:
Expression tag is used to display output of any data on the generated page. The data placed in Expression tag prints on the output stream and automatically converts data into string. The Expression tag can contain any Java expression used for printing output equivalent to out.println().Thus, an expression tag contains a scripting language expression which is evaluated, automatically converts data to a String and the outputs are displayed. Notation of Expression tag is shown below: <%= %> 80 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Expression tag must begin with <%= Inside Expression tag, the user embeds any Java expression. Expression tag ends with the notation %>. NOTE: Expression should not contain a semicolon between codes, as with Declaration tag. General syntax of Expression Tag:
<%! statement %> //end of declaration tag //start of //Java declaration tag Expression

For example:
<%! Exfdate: <%= new java.util.Date() %> %>

Above example displays current date and time as Date() is placed inside the Expression tag <%= %>

Buffer:
If a programmer likes to control the use of buffered output for a JSP page then the buffer attribute can be made use of for achieving this. Syntax of buffer attribute available for page directive is <%@ page buffer = "none|8kb|sizekb" %> In the above statement page and buffer are keywords. The size of buffer size is mentioned in kilobytes. This is used by the out object to handle output sent from the compiled JSP page to the client web browser. The default value is 8kb. If a user specifies a buffer size then the output is buffered with at least the size mentioned by the user. For example one can specify as: <%@ page buffer = "none" %>

Scriptlet tag:
Scriptlet tag is a type tag used for inserting Java Code into JSP. Notation of the Scriptlet tag is: 81 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

&lt;% %&gt; To begin the Scriptlet tag, the user must add &lt;% . Inside the Scriptlet tag, the user can add any valid Scriptlet, meaning any valid Java Code. User can write the code in between the Scriptlet tag accesses any variable or bean declared. The Scriptlet tag ends with the notation %&gt;.

Action Tag:
Action tag is used to transfer the control between pages and is also used to enable the use of server side JavaBeans. Instead of using Java code, the programmer uses special JSP action tags to either link to a Java Bean set its properties, or get its properties. General syntax of Action Tag:
<jsp:action attributes />

In the above statement jsp is a keyword. There are many action tags that are available for Java Server Pages. The most commonly used action tags are three of them and they are namely:
include forward useBean

Syntax, attributes and usage of above three action tags are provided in brief.

Include action tag:


include is a type of directive tag. include tag has the same concept as that of the include directive. The include tag is used to include either static or dynamic content, wherever required. General syntax of include action Tag:
<jsp:include page="{relativeURL | <%= expression %>}" flush="true" />

In the above statement, the words jsp, include, flush and page are keywords. The include action tag includes a static file or it is used to send a request to a dynamic file. If the included file is a static file, the contents are included as such in the called JSP file. In

82 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

contrast, if the included file is dynamic, then a request sends to the dynamic file. Once the include action is completed, the result is sent back. If the file is dynamic one can use the syntax as below:
<jsp:include page="{relativeURL | <%= expression %>}" flush="true" /> <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /> </jsp:include>

The file is dynamic and extra attribute clause passed is jsp:param clause, and this is used to pass the name and value of a parameter to the dynamic file. In the above, the words jsp, include, flush, page, param, name and value are keywords. In the above syntax for dynamic file inclusion, the name attribute specifies the parameter name and its case-sensitive literal string. The value attribute specifies the parameter value, taking either a case-sensitive literal string or an expression that is evaluated at request time. In the syntax of include action Tag we relative URL placed within " " denotes the location of the file to be included or denotes the pathname to be included. This can also be an expression which is taken automatically as string, denoting the relative URL. the pathname must not contain the protocol name, port number, or domain name. Both absolute and relative representations can be made for denoting the URL.

The flush attribute can only take on value "true" as mentioned in syntax notation. Do not to include the value if false for the flush attribute. The syntax used for including dynamic file had &lt;jsp:param&gt; clause allows the user to pass one or more name/value pairs as parameters to an included file. This is the syntax for dynamic file, meaning that the included file is a dynamic file (i.e. either a JSP file or a servlet, or other dynamic file). Also, the user can pass more than one parameter to the included file by using more than one &lt;jsp:param&gt; clause.

83 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

The Example An example to include a static file exforsys.html in the include action tag:
<jsp:include page="exforsys.html" flush="true" />

Let us see an example of dynamic file inclusion in the include action tag which is done as below:
<jsp:include page="example/test.jsp"> <jsp:include name="username" value="exforsys" /> </jsp:include>

Let us see about the other two commonly used action tags namely forward action tag and useBean action tag with syntax, usage, example and explanation in detail

Forward action tag:


The forward action tag is used to transfer control to a static or dynamic resource. The static or dynamic resource to which control has to be transferred is represented as a URL. The user can have the target file as an HTML file, another JSP file, or a servlet. Any of the above is permitted. NOTE: The target file must be in the same application context as the forwarding JSP file. General syntax of forward action Tag:

<jsp:forward page="{relativeURL | <%= expression %>}" /> &nbsp;

Another syntax representation for forward action Tag is as below:


<jsp:forward page ="{relativeURL | <%= expression %>}" /> <jsp:param name ="parameterName" value="parameterValue" | <%= expression %>}" /> </jsp:forward>

In the above statement, jsp, forward, page, param, name and value are all keywords. The relative URL of the file to which the request is forwarded is represented as a String, an expression or as absolute or relative representation to the current JSP file denoting the pathname. 84 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

NOTE: Do not include protocol name, port number, or domain name in the pathname. The file can be a JSP file or a servlet, or any other dynamic file. If the user follows the second syntax representation of forward action Tag, then the target file should be dynamic where jsp:param&gt; clause is used. This allows the sending of one or more name/value pairs as parameters to a dynamic file. The user can pass more than one parameter to the target file by using more than one &lt;jsp:param&gt; clause. In the above second representation, the name attribute is used to specify the parameter name and its case-sensitive literal string. The value attribute can be specified by the parameter value taking either a case-sensitive literal string or an expression that is evaluated at request time. For example:
<jsp:forward page ="exforsys.html" /> <jsp:forward page ="/example/test" /> <jsp:param name ="username" value="exforsys" /> </jsp:forward> &nbsp;

useBean action tag: The useBean action tag is the most commonly used tag because of its powerful features. It allows a JSP to create an instance or receive an instance of a Java Bean. It is used for creating or instantiating a bean with a specific name and scope. This is first performed by locating the instance of the bean. General syntax of useBean action Tag:
<jsp:useBean id="beanInstanceName" scope="page|request|session|application" { class="package.class" | type="package.class" | class="package.class" type="package.class" | beanName="{package.class | <%= expression %>}" type="package.class" } { /> | > other elements </jsp:useBean> }

85 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

What are Java Beans and its advantages?


JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. JavaBeans is a portable, platform-independent component model written in the Java programming language with the JavaBeans API you can create reusable, platform-independent components using JavaBeans-compliant application builder tools such as NetBeans or Eclipse, you can combine these components into applets.

Introduction to BDK (Bean Development Kit).


JavaBeans and the Bean Development Kit JavaBeans are reusable software components written in Java. These components may be built into an application using an appropriate building environment. The Bean Development Kit (BDK) from Sun includes a simple example of a building environment which uses beans, called the beanbox, and some sample beans. This note will tell you how to set up and use the BDK on the Computer Science & Informatics Fedora Linux workstations and how to add your own beans to the BeanBox. The BDK The BDK needs to create some directories and copy some les to your lespace before you can use it. So, the rst time you want to use the BDK, give the following command: % bdk-user-setup This will create a directory called BDK1.1 and sub-directories BDK1.1/jars and BDK1.1/beanbox together with some links to les in the Bean Development Kit installation directory. Running the BeanBox Change directory to BDK1.1/beanbox and type the command ./run.sh: % cd BDK1.1/beanbox % ./run.sh & The BeanBox starts and loads beans from the JAR (Java Archive) les in the BDK1.1/jars directory. It then displays four windows on the screen:

86 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

the ToolBox which lists all beans the BeanBox has found, the BeanBox which is a canvas where you will drop beans and connect them together, the Properties sheet which is used to set the properties of the current bean, the MethodTracer simple debugging facility. Adding beans to the canvas To add beans to the BeanBox canvas, click on the beans name or icon in the ToolBox window, then click on the location in the BeanBox canvas where you want the newInformation for Users: bean to appear. The bean that appears on the BeanBox canvas is the current selected bean shown by a hatched border around the bean) and its properties appear in the Properties sheet. The properties in the Properties sheet can be edited by typing new values or by special editors (eg for colours). For example, in the diagram below, we have added two ExplicitButton beans and a Juggler bean to the canvas. Click on the left hand bean labelled Press. This bean becomes the current selected bean. In the Properties sheet, change the name in the label from Press to Stop. The name on the selected button changes to Stop when you press the Return key. Wiring up eventsWe can connect events from a selected bean to another bean. Let us wire up the Stop button to stop the juggler. Select the Stop button and choose Edit!Events!button

push!actionPerformed. Now as you move the mouse, a red line attached to the Stop button moves with it. Move the mouse to the Juggler bean and click the mouse button. A new EventTargetDialog window which lists available events appears. Scroll down and choose stopJuggling. Click on OK. The actionPerformed event from the Stop button will now cause the stopJuggling method of the Juggler bean to be called. In order to cause this to happen, the BeanBox generates adapter code, compiles it and loads it automatically. So clicking on the Stop button now stops the Juggler. You can similarly set up a Start button to restart the Juggler. Choose the other Press button on the canvas, rename it Start, choose Edit!Events!button push!actionPerformed and this time select startJuggling from the EventTargetDialog window. Documentation For more information refer to the Web-based documentation at URL http://www.cs.cf.ac.uk/applications/java/BDK1.1/. 2 Writing beans and adding them to the BeanBox You may write your own beans which the BeanBox can use. A bean is packaged into a JAR archive le which contains SDTL a le, called the manifest, which species which class les in the archive are 87 SCOE-IT

12: Study of Servelets, JSP, JDBC API

beans, all the class les associated with the component (the bean), any data les (eg image les) needed by the bean.

Subsequent sections tell you how to create the JAR le and how to load the JAR le into the BeanBox so that it can use your bean. Packaging a bean with makebean As an example, we will add the ImageViewer bean given in the book Core Java, Volume II by Horstmann and Cornell, to the BeanBox. The source les used to build the bean must be placed in a separate directory. Use % mkdir directory-name to create the directory where directory-name is the name of the directory, e.g. ImageViewer, then copy or create the source les there. So, for the ImageViewer bean we have: Information for Users: Introductory Note 615 5 % ls -l ImageViewer total 68 -rw-r--r-- 1 robert 45724 Jun 1 15:39 Cay.gif -rw-r--r-- 1 robert 1105 Jun 1 15:39 ImageViewerBean.java -rw-r--r-- 1 robert 20132 Jun 1 15:39 Tower.gif File ImageViewerBean.java is the Java source le and the .gif les are data les used by the bean to draw images. To turn these les into a JavaBean, change to the ImageViewer directory and type makebean followed by the names of the Java and data les which make up the bean: % makebean ImageViewerBean.java *.gif You will see output like: jar cfm ImageViewerBean.jar ImageViewerBean.mf *.class Cay.gif Tower.gif The bean is given the same name as the rst Java le on the makebean command line. (In this case, there is only one Java le and the bean is called ImageViewerBean). The makebean command has made the ImageViewerBean.jar JavaBean JAR archive and three other les: % ls -l 88 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

total 137 -rw-r--r-- 1 robert 45724 Jun 1 15:39 Cay.gif -rw-r--r-- 1 robert 1597 Jun 2 10:53 ImageViewerBean.class -rw-r--r-- 1 robert 525 Jun 2 10:53 ImageViewerBean.gmk -rw-r--r-- 1 robert 67275 Jun 2 10:53 ImageViewerBean.jar -rw-r--r-- 1 robert 1105 Jun 1 15:39 ImageViewerBean.java -rw-r--r-- 1 robert 48 Jun 2 10:53 ImageViewerBean.mf -rw-r--r-- 1 robert 20132 Jun 1 15:39 Tower.gif File ImageViewerBean.mf is the manifest which has been created automatically by makebean. It species a single class corresponding to the rst named Java le. It looks like: Name: ImageViewerBean.class Java-Bean: True The manifest le tells the BDK to display the bean ImageViewerBean in its ToolBox when the JAR les is loaded. ImageViewerBean.gmk is a makefile which makebean supplies to GNU make in order to compile the Java source and build the JAR le. Makebean runs GNU make for you, you do not have to do it yourself. ImageViewerBean.class is the class le which has been compiled from ImageViewerBean.java. There is a copy of it in the JAR le. Bean name, multi-module beans and manifests The above example is simple because the bean is made up of only one Java source le. If you have a bean which needs more than one Java source le, you must name all of the Java les in the makebean command. The name of the first Java le listed is taken to be the name of the bean. E.g. % makebean MyBean.java Utility.java Picture.gif would create a JavaBean called MyBean in a le MyBean.jar. As in the case of ImageViewerBean, makebean will create a manifest le specifying that the class compiled from the rst named Java le is a bean. Name: MyBean.class Java-Bean: True If more than one class le in the archive is to be a bean, you must create the manifest le yourself before running makebean. 2.3 Using your bean in the BeanBox The simplest way to make your bean available to the BeanBox is to move its JAR le into the BDK jars directory, e.g.: % mv ImageViewerBean.jar /BDK1.1/jars

89 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

The new bean will appear in the ToolBox when you next start the BeanBox (with .(run.sh/. Alternatively, you can load any JavaBean JAR le into the BeanBox by choosing File!LoadJar... from the BeanBox menu and browsing for your JAR le.

The Plugin The Sysdeo Tomcat Plugin is our best friend. After you have installed it, you will notice these buttons and menues in your IDE.

The left button starts Tomcat, the middle button stops it, the right button restarts Tomcat. Right now, they wont work if you press them. To enable them, you first need to configure a few things. Go to the menu Window-> Preferences there, you will see this dialogue box.

Now you need to go to the menu item Tomcat and select your Tomcat version. At the time of writing that would be the 4.1 5.x version. Now we adjust the field Tomcat Home to point to the install directory that we selected before at install time. The Sysdeo plugin now knows where to look for the server.xml file and automatically assumes the standard path to look for the file. Eclipse is now able to manage this configuration file, i.e. add a new&lt;context&gt; for a new application. 90 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

The Tomcat servlet container, features multiple user roles, such as the Administrator that we have already added to the user configuration upon installation. All users and passwords are found (in plain text, so take care to handle this safely) in the conf/tomcat-users.xml file. We now need to add another user called Manager that was not added to the file at installation time. Therefor we scroll down the menu point Tomcat and click the item Tomcat Manager App. Now we can add a username and a password for the manager. Subsequently we click on Add user to tomcat-users.xml and leave the configuration menu.

91 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Now we are ready to test start our Tomcat server. Click on the start button in the Tomcat menu and watch the console output. If Tomcat boots up without any stacktraces open your browser, and try to open the following addresshttp://localhost:8080/ . If you see an image that is similar, to the one below everything is working okay.

Hello World For now, we stop out Tomcat server and take a look at our very own, first servlet. First, we need to open a new project in the navigator window.

In the project window we select Tomcat Project

click on the Next button and call our new project Hello World 92 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

After a click on the next Button we now can adjust under which URI (Uniform Resource Identifier) we want our new application to respond to our requests. To illustrate what part of the URL this is, just take a look at the fat part in the following address: http://localhost:8080/HelloWorld/hello. The default adjustments on the other controls should be fine by now, so we dont bother to adjust them. They should look similar to following image.

<="" a="" style="padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; margin-top: 0px; margin-right: 0px; marginbottom: 0px; margin-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottomwidth: 0px; border-left-width: 0px; border-style: initial; border-color: initial; "> Enlarge
If we now Finish the Wizard, we can see, that Eclipse has created a whole bunch of new directories. It should look similar to this:

Now we can create a new class named HelloServlet in the directory WEB-INF/src. Now we can copy and paste following code into this class.

93 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

import java.io.*; import javax.servlet.http.*; import javax.servlet.*; public class HelloServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("Hello, Brave new World!"); out.close(); } } Our View should now look like this:

Unfortunately we are not yet finished. We still need to create the web.xmldescriptor, which contains certain elements of configuration specific to our application and the server behaviour. So we create the file web.xml in the directory WEB-INF (Note: not in the directory WEBINF/src !!!). For our simple application, the following parameters should be fine. <!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'> <web-app> <servlet> 94 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

<servlet-name>hello</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app> What follows now is a little explanation of what we just copied and pasted intoweb.xml . The Doctype is an xml specific item that tells the xml parser where to look for the dtd consistency rules for our xml document. The dtd ensures that no wrong parameter combinations are entered. The main tag &lt;web-app&gt;contains all preferences for our servlet. The &lt;servlet&gt; tag basically contains the name (&lt;servlet-name&gt;) that will be used throughout the xml document to reference our servlet and its linked class (&lt;servlet-class&gt;) . The tag &lt;servlet-mapping&gt; is responsible for telling the server, to what document name in the URL our application should respond to. Note, that the correct order of these tags has to be retained to form a validweb.xml descriptor. If we followed all steps correctly, we should now be able to fire up Tomcat again. Our workspace should now look like that:

So, if we now enter the right combination of URI and resource name into the address bar of our browser (in our case this would actually behttp://localhost:8080/HelloWorld/hello) we should be able to see the output from our very first servlet.

95 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

Oh, yeah if you want to enable your Tomcat engine to serve JSPs too, you just have to add the following lines to the web.xml file and put the jsp files in the top level directory of your eclipse project. <servlet> <servlet-name>jspAssign</servlet-name> <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> <init-param> <param-name>logVerbosityLevel</param-name> <param-value>WARNING</param-value> </init-param> <init-param> <param-name>fork</param-name> <param-value>false</param-value> </init-param> <load-on-startup>3</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jspAssign</servlet-name> <url-pattern>/*.jsp</url-pattern> </servlet-mapping>

Frequently asked questions.


1. Explain working of Java Virtual Machine (JVM) Explain the working cycle of the JDBCODBC connectivity? 2. What is the purpose of creating ODBC data source in establishing a connection between Java application & database? 3. When would you use a JDBC-ODBC Bridge? 4. Name the method that gives the existing isolation level in JDBC.

96 SDTL SCOE-IT

12: Study of Servelets, JSP, JDBC API

5. Consider the following:-ID [_______]Name [_______]Marks [_______]NEW EDIT CLOSEThis is a form which I have made. What i need is When I click on NEW button, if textboxes should 6. Can we use Type1 driver in web Application?If possible give me a simple example for all driver types? 7. What are the Database transactions? How we can maintain transactions using JDBC? Explain with example? 8. What are the Database transactions? How we can maintain transactions using JDBC? Explain with example? 9. What are the ways to write comments in the JSP page? Give example. 10. Write Sample Code to pass control from one JSP page to another? 11. How will you handle the exception without sending to error page? How will you set a message detail to the exception object? 12. What is JSP Fragment? 13. What is the difference between jsp and servlet life cycles? 14. Why we need web container to Deploy the servlet or jsp ? 15. Why main() is not written in servlets programs? 16. What is the difference between http session and application session? 17. Where do you declare methods in JSP? 18. How to disable browser "Back" and "Forward" button from a JSP page? 19. Can we use main method inside JSP? Why? 20. How do you create Http Session that never times out ? 21. How do you write custom tags like tag library 22. How will you provide security to web application? 23. Name the internal objects of JSP? 24. What is the different between session and cookies? Where is the session information stored? In RAM of the Client or Disk of the Client or it is stored on the server? 25. Describe the functions of Controller? 26. What is the Difference Between Web Container and Web Server? 27. Explain the server process how will server identifies that and response to corresponding servlet and how it sends to that response to correct user ? 28. What is web.xml?2)what is the filter?3)How to we create a new JSTL class?4)When we are developing the project which collections mostly used?5)Difference between reqeust.getAttribute,and request.getParameter? 29. What is the use of Service() in servlets? How is that method invoked? 30. What is the difference between doGet methods,doGet()and service() used in servlet?can we use service() 31. Why do we need to implement 3rd party support for using connection pooling ? 32. What are Java Servlets? 33. What do I need to develop servlets? 34. Where can I get more information on servlets? 35. How does servlet performance compare to applets? 36. How does servlet performance compare to CGI? 37. Should I use single-threaded, or multi-threaded, servlets? 38.How do I send cookies from a servlet? 39. How do I read browser cookies from a servlet? 40. How do I make cookies expire after a set time period?

97 SDTL SCOE-IT

41. Why aren't cookies stored by my servlets accessible to my CGI scripts or ASP pages? 42. How can I void a cookie, and delete it from the browser? 43.How do I display a particular web page from an applet? 44.How do I display more than one page from an applet? 45. How can I fetch files using HTTP? 46. How do I use a proxy server for HTTP requests? 47.What is a malformed URL, and why is it exceptional? 48.How do I URL encode the parameters of a CGI script? 49.Why is a security exception thrown when using java.net.URL or java.net.URLConnection from an applet? 50. How do I prevent caching of HTTP requests?

98 SDTL SCOE-IT

13: Mini project based on Part I, Part II Part III

AIM

: Mini project based on Part I, Part II Part III

OBJECTIVE

: Design and implement a Mini Project Based on Fundamental of Java Programming and client side programming.

THEORY

: 1. Problem Statement of project. 2. Description of Project. 3. Java concept used in Project.

INSTRUCTIONS

: 1. Form a group of two students. 2. Select a topic for Mini Project a. (E.g. Payroll system, student information system, etc.) 3. Use suitable Fundamental of Java Programming and client side a. Programming (e.g HTML, Java Applet, JavaScript) for b. Designing a mini project. 4. Use Serve side Programming Concepts

99 SDTL SCOE-IT

Potrebbero piacerti anche