[go: up one dir, main page]

0% found this document useful (0 votes)
10 views183 pages

Web Technologies Material

The document provides an overview of Java, detailing its history, features, and basic syntax, emphasizing its object-oriented nature and platform independence. It includes instructions for setting up a Java programming environment, writing a simple Java program, and understanding key concepts such as classes, objects, methods, and OOP principles like abstraction and encapsulation. Additionally, it outlines the necessary tools and editors for Java development, along with examples to illustrate fundamental programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views183 pages

Web Technologies Material

The document provides an overview of Java, detailing its history, features, and basic syntax, emphasizing its object-oriented nature and platform independence. It includes instructions for setting up a Java programming environment, writing a simple Java program, and understanding key concepts such as classes, objects, methods, and OOP principles like abstraction and encapsulation. Additionally, it outlines the necessary tools and editors for Java development, along with examples to illustrate fundamental programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 183

Web technologies

Unit-1 java basics


Introduction of java
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun
Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of
Java and its widespread popularity, multiple configurations were built to suit various
types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively.
Java is guaranteed to be Write Once, Run Anywhere.
Java is −
 Object Oriented − In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
 Platform Independent − Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
 Simple − Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors,
with the presence of Java runtime system.
 Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is written in
ANSI C with a clean portability boundary, which is a POSIX subset.
 Robust − Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
 Multithreaded − With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.
 Interpreted − Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more rapid
and analytical since the linking is an incremental and light-weight process.
 High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
 Distributed − Java is designed for the distributed environment of the internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and resolve
accesses to objects on run-time.

History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many
set-top box projects. The language, initially called ‘Oak’ after an oak tree that stood
outside Gosling's office, also went by the name ‘Green’ and ended up later being
renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write
Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open
-source, aside from a small portion of code to which Sun did not hold the copyright.

Tools You Will Need


For performing the examples discussed in this tutorial, you will need a Pentium 200-
MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).
You will also need the following softwares −

 Linux 7.1 or Windows xp/7/8 operating system

 Java JDK 8

 Microsoft Notepad or any other text editor


This tutorial will provide the necessary skills to create GUI, networking, and web
applications using Java.

Local Environment Setup


If you are still willing to set up your environment for Java programming language, then
this section guides you on how to download and set up Java on your machine.
Following are the steps to set up the environment.
Java SE is freely available from the link Download Java. You can download a version
based on your operating system.
Follow the instructions to download Java and run the .exe to install Java on your
machine. Once you installed Java on your machine, you will need to set environment
variables to point to correct installation directories −
Setting Up the Path for Windows
Assuming you have installed Java in c:\Program Files\java\jdk directory −
 Right-click on 'My Computer' and select 'Properties'.
 Click the 'Environment variables' button under the 'Advanced' tab.
 Now, alter the 'Path' variable so that it also contains the path to the Java
executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32',
then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program
Files\java\jdk\bin'.

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD


Environment variable PATH should be set to point to where the Java binaries have
been installed. Refer to your shell documentation, if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end
of your '.bashrc: export PATH = /path/to/java:$PATH'

Popular Java Editors


To write your Java programs, you will need a text editor. There are even more
sophisticated IDEs available in the market. But for now, you can consider one of the
following −
 Notepad − On Windows machine, you can use any simple text editor like
Notepad (Recommended for this tutorial), TextPad.
 Netbeans − A Java IDE that is open-source and free which can be downloaded
from https://www.netbeans.org/index.html.
 Eclipse − A Java IDE developed by the eclipse open-source community and can
be downloaded from https://www.eclipse.org/.

Java Basic Syntax


When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do
class, object, methods, and instance variables mean.
 Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An
object is an instance of a class.
 Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
 Methods − A method is basically a behavior. A class can contain many methods.
It is in methods where the logics are written, data is manipulated and all the
actions are executed.
 Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.

First Java Program


Let us look at a simple code that will print the words Hello World.
Example
publicclassMyFirstJavaProgram{

/* This is my first java program.


* This will print 'Hello World' as the output
*/

publicstaticvoid main(String[]args){
System.out.println("Hello World");// prints Hello World
}
}
Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps −
 Open notepad and add the code as above.
 Save the file as: MyFirstJavaProgram.java.
 Open a command prompt window and go to the directory where you saved the
class. Assume it's C:\.
 Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If
there are no errors in your code, the command prompt will take you to the next
line (Assumption : The path variable is set).
 Now, type ' java MyFirstJavaProgram ' to run your program.
 You will be able to see ' Hello World ' printed on the window.
Output
C:\>javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World

Basic Syntax
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity − Java is case sensitive, which means
identifier Hello and hello would have different meaning in Java.
 Class Names − For all class names the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first letter
should be in Upper Case.
Example: class MyFirstJavaClass
 Method Names − All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner word's
first letter should be in Upper Case.
Example: public void myMethodName()
 Program File Name − Name of the program file should exactly match the class
name.
When saving the file, you should save it using the class name (Remember Java
is case sensitive) and append '.java' to the end of the name (if the file name and
the class name do not match, your program will not compile).
But please make a note that in case you do not have a public class present in
the file then file name can be different than class name. It is also not mandatory
to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should
be saved as 'MyFirstJavaProgram.java'
 public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.

Java Identifiers
All Java components require names. Names used for classes, variables, and methods
are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
 All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).
 After the first character, identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value.
 Examples of illegal identifiers: 123abc, -salary.
Reserved words in java
The following list shows the reserved words in Java. These reserved words may not be
used as constant or variable or any other identifier names.

abstract assert boolean break

byte case catch char

class const continue default


do double else enum

extends final finally float

for goto if implements

import instanceof int interface

long native new package

private protected public return

short static strictfp super

switch synchronized this throw

throws transient try void

volatile while

OOPs Concepts
1. What is an Object
2. What is a class
3. Constructor in Java
4. Object Oriented Programming Features

Abstraction
Encapsulation
Inheritance
Polymorphism
Abstract Class and Methods

What is an Object
Object: is a bundle of data and its behaviour(often known as methods).

Objects have two characteristics: They have states and behaviors.

Examples of states and behaviors


Example 1:
Object: House
State: Address, Color, Area
Behavior: Open door, close door

So if I had to write a class based on states and behaviours of House. I can do it


like this: States can be represented as instance variables and behaviours as
methods of the class. We will see how to create classes in the next section of
this guide.

classHouse {
String address;
String color;
double are;
voidopenDoor() {
//Write code here
}
voidcloseDoor() {
//Write code here
}
...
...
}
Example 2:
Let’s take another example.
Object: Car
State: Color, Brand, Weight, Model
Behavior: Break, Accelerate, Slow Down, Gear change.

Note: As we have seen above, the states and behaviors of an object, can be
represented by variables and methods in the class respectively.

Characteristics of Objects:

If you find it hard to understand Abstraction and Encapsulation, do not worry as I


have covered these topics in detail with examples in the next section of this
guide.
1. Abstraction
2. Encapsulation
3. Message passing

Abstraction: Abstraction is a process where you show only “relevant” data and
“hide” unnecessary details of an object from the user.

Encapsulation: Encapsulation simply means binding object state(fields) and


behaviour(methods) together. If you are creating class, you are doing
encapsulation.

Message passing
A single object by itself may not be very useful. An application contains many
objects. One object interacts with another object by invoking methods on that
object. It is also referred to as Method Invocation. See the diagram below.

What is a Class in OOPs Concepts

A class can be considered as a blueprint using which you can create as many
objects as you like. For example, here we have a class Website that has two data
members (also known as fields, instance variables and object states). This is just
a blueprint, it does not represent any website, however using this we can create
Website objects (or instances) that represents the websites. We have created
two objects, while creating objects we provided separate properties to the
objects using constructor.

publicclassWebsite {
//fields (or instance variable)
StringwebName;
intwebAge;

// constructor
Website(String name, int age){
this.webName = name;
this.webAge = age;
}
publicstaticvoid main(Stringargs[]){
//Creating objects
Website obj1 = newWebsite("beginnersbook", 5);
Website obj2 = newWebsite("google", 18);

//Accessing object data through reference


System.out.println(obj1.webName+" "+obj1.webAge);
System.out.println(obj2.webName+" "+obj2.webAge);
}
}
Output:

beginnersbook5
google18

What is a Constructor

Constructor looks like a method but it is in fact not a method. It’s name is same
as class name and it does not return any value. You must have seen this
statement in almost all the programs I have shared above:

MyClassobj = newMyClass();
If you look at the right side of this statement, we are calling the default
constructor of class myClass to create a new object (or instance).

We can also have parameters in the constructor, such constructors are known
as parametrized constructors.

Example of constructor

publicclassConstructorExample {

int age;
String name;

//Default constructor
ConstructorExample(){
this.name="Chaitanya";
this.age=30;
}

//Parameterized constructor
ConstructorExample(Stringn,int a){
this.name=n;
this.age=a;
}
publicstaticvoid main(Stringargs[]){
ConstructorExample obj1 = newConstructorExample();
ConstructorExample obj2 =
newConstructorExample("Steve", 56);
System.out.println(obj1.name+" "+obj1.age);
System.out.println(obj2.name+" "+obj2.age);
}
}
Output:

Chaitanya30
Steve56

Object Oriented Programming features

These four features are the main OOPs Concepts that you must learn to
understand the Object Oriented Programming in Java

Abstraction

Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user. For example, when you login to
your bank account online, you enter your user_id and password and press login,
what happens when you press login, how the input data sent to server, how it
gets verified is all abstracted away from the you. Read more about it
here: Abstraction in Java.

Encapsulation

Encapsulation simply means binding object state(fields) and behavior(methods)


together. If you are creating class, you are doing encapsulation.

Dynamic binding:-

Dynamic binding:-

Dynamic” means “run time”, and “binding” means “association”. So the term
dynamic binding indicates run time association of objects by java virtual
machine. Here we will see how Java achieves dynamic binding in run time,
which means before the code’s final running but after compilation.

Syntax: For dynamic binding in Java, you should follow the basic syntax of
java with annotations. You may use @Override annotation here to point out
which method we want to override specifically.

How Dynamic Binding Works in Java


Runtime polymorphism works in Java by method overriding. Method
overriding happens when objects have the same method name and
arguments and type as of their parent class but with different functionality. If
a child class has that type of method in it, we call it an overridden method.

Why is it called dynamic binding


Reason being named so, due to the fact that the functionality of the method is
dynamically decided in run time as per the object by JVM. It is also referred to
as “Run time Polymorphism”. when we call an overridden method of child
class through its parent type reference (this phenomenon in java is referred to
as “Upcasting”), then the type of the object indicates which method or
functionality will be invoked. Making of this decision happens during runtime
by JVM after the compilation of code. Hence it is called run time
polymorphism. It is also called “Late binding”, because binding of method and
object, which means the functionality of which object’s method will be
displayed, is decided late, i.e. after compilation.

Rules Regarding Dynamic Binding

 Methods or functions of child and parent class must have the same
name.
 Methods or functions of child and parent class must have the same
parameter.
 The inheritance relationship is mandatory (IS-A relationship).

Limitations in Dynamic Binding

 You cannot override the private methods of a parent class.


 You cannot override Final methods.
 You cannot override static methods.
Examples to Implement Dynamic Binding
We will discuss some code examples of Dynamic Binding here:

Eg-In this example, we will show how the method locate () is displaying
different messages depending on which type of object it is associated with.
When it is associated with the “Continent” type, it is showing messages from
a parent class. When it is associated with the “SubContinent” type, it shows
messages from the child class.

Program:-

class Continent {
public void locate () {
System.out.println("We are in Continent");
}
}
class SubContinent extends Continent {
@Override
public void locate () {
System.out.println("We are in SubContinent");
}
}
public class DynamicBinding {
public static void main(String args[]) {
Continent superObject = new Continent ();
superObject.locate(); //method of super class or parent class is called
SubContinentsubObject = new SubContinent (); // upcasting
subObject.locate();//method of sub class or child class is called by Parent
reference, this is called "Dynamic Binding"
SubContinent subObject2 = new SubContinent ();
subObject2.locate(); //method of sub class or child class is called
}
}

o/p-

we are in continent

we are in subcontinent

we are in subcontinent
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only essential
information to the user.

Abstraction can be achieved with either abstract classes or interfaces (which you will learn
more about in the next chapter).

The abstract keyword is a non-access modifier, used for classes and methods:

 Abstract class: is a restricted class that cannot be used to create objects (to access
it, it must be inherited from another class).
 Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).

An abstract class can have both abstract and regular methods:

abstractclassAnimal{

publicabstractvoidanimalSound();

publicvoidsleep(){

System.out.println("Zzz");

From the example above, it is not possible to create an object of the Animal class:

AnimalmyObj=newAnimal();// will generate an error

To access the abstract class, it must be inherited from another class. Let's convert the
Animal class we used in the Polymorphism chapter to an abstract class:

Prog:-Abstract class

abstractclassAnimal{

// Abstract method (does not have a body)

publicabstractvoidanimalSound();

// Regular method

publicvoidsleep(){

System.out.println("Zzz");

}
}

// Subclass (inherit from Animal)

classPigextendsAnimal{

publicvoidanimalSound(){

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

classMain{

publicstaticvoidmain(String[]args){

PigmyPig=newPig();// Create a Pig object

myPig.animalSound();

myPig.sleep();

Interfaces
Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group related methods with
empty bodies:

Example
// interface

interfaceAnimal{

publicvoidanimalSound();// interface method (does not have a body)

publicvoidrun();// interface method (does not have a body)

To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class:

Example
// Interface

interfaceAnimal{

publicvoidanimalSound();// interface method (does not have a body)

publicvoidsleep();// interface method (does not have a body)

// Pig "implements" the Animal interface

classPigimplementsAnimal{

publicvoidanimalSound(){

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

publicvoidsleep(){

// The body of sleep() is provided here

System.out.println("Zzz");

classMain{

publicstaticvoidmain(String[]args){

PigmyPig=newPig();// Create a Pig object

myPig.animalSound();

myPig.sleep();} }

Java Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to
make searching/locating and usage of classes, interfaces, enumerations and
annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces,
enumerations and annotations ) providing access protection and namespace
management.
Some of the existing packages in Java are −
 java.lang − bundles the fundamental classes
 java.io − classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces,
etc. It is a good practice to group related classes implemented by you so that a
programmer can easily determine that the classes, interfaces, enumerations, and
annotations are related.
Since the package creates a new namespace there won't be any name conflicts with
names in other packages. Using packages, it is easier to provide access control and it
is also easier to locate the related classes.

Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains
the classes, interfaces, enumerations, and annotation types that you want to include in
the package.
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and
annotation types will be placed in the current default package.
To compile the Java programs with package statements, you have to use -d option as
shown below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and
the compiled class files will be placed in that folder.

Example

Let us look at an example that creates a package called animals. It is a good practice
to use names of packages with lower case letters to avoid any conflicts with the
names of classes and interfaces.
Following package example contains interface named animals −
/* File name : Animal.java */
package animals;

interfaceAnimal{
publicvoid eat();
publicvoid travel();
}
Now, let us implement the above interface in the same package animals −
package animals;
/* File name : MammalInt.java */

publicclassMammalIntimplementsAnimal{

publicvoid eat(){
System.out.println("Mammal eats");
}

publicvoid travel(){
System.out.println("Mammal travels");
}

publicintnoOfLegs(){
return0;
}

publicstaticvoid main(Stringargs[]){
MammalInt m =newMammalInt();
m.eat();
m.travel();
}
}
Now compile the java files as shown below −
$ javac -d . Animal.java
$ javac -d . MammalInt.java
Now a package/folder with the name animals will be created in the current directory
and these class files will be placed in it as shown below.
You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels
1

GUI PROGRAMMING WITH JAVA

Event handling:-

Any program that uses GUI (graphical user interface) such as Java
application written for windows, is event driven. Event describes the
change in state of any object. For Example : Pressing a button,
Entering a character in Textbox, Clicking or Dragging a mouse, etc.

Components of Event Handling

Event handling has three main components,

 Events : An event is a change in state of an object.

 Events Source : Event source is an object that generates an


event.

 Listeners : A listener is an object that listens to the event. A


listener gets notified when an event occurs.

How Events are handled?

A source generates an Event and send it to one or more listeners


registered with the source. Once event is received by the listener,
they process the event and then return. Events are supported by a
number of Java packages, like java.util, java.awt and java.awt.event.
2

Important Event Classes and Interface

Event Classes Description Listener Interface

generated when button is pressed,


ActionEvent menu-item is selected, list-item is ActionListener
double clicked

generated when mouse is dragged,


moved,clicked,pressed or released and
MouseEvent MouseListener
also when it enters or exits a
component

generated when input is received from


KeyEvent KeyListener
keyboard

generated when check-box or list item is


ItemEvent ItemListener
clicked

generated when value of textarea or


TextEvent TextListener
textfield is changed

MouseWheelEvent generated when mouse wheel is moved MouseWheelListe

WindowEvent generated when window is activated, WindowListener


deactivated, deiconified, iconified,
3

Event Classes Description Listener Interface

opened or closed

generated when component is hidden,


ComponentEvent ComponentEventL
moved, resized or set visible

generated when component is added or


ContainerEvent ContainerListener
removed from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListene

generated when component gains or loses


FocusEvent FocusListener
keyboard focus

Steps to handle events:

 Implement appropriate interface in the class.


 Register the component with the listener.

Example of Event Handling

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
4

import java.awt.*;
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
5

g.drawString(msg, 20, 40);


}
}

HTML code:
<applet code="Test" width=300, height=100>
</applet>

Java Abstract Window Toolkit(AWT)

AWT includes a big amount of classes and techniques to build and handle apps such
as windows, buttons, scroll bars, etc. The AWT was intended to provide a prevalent
collection of GUI design instruments capable of working on a multitude of platforms.
The tools supplied by the AWT are introduced using the indigenous GUI toolkit of
each platform, thus maintaining each platform's look and feel. This is an benefit of
6

using AWT.But the disadvantage of such an strategy is that when displayed on


another platform, GUI built on one platform may look distinct.

AWT is the basis for Swing, i.e. Swing is a set of GUI interfaces that extend the AWT.
But nowadays AWT is merely used as most GUI Java programs are being
implemented using Swing, due to its rich implementation of GUI controls and
lightweight nature.

Java AWT Hierarchy

 Component class

At the top of the AWT hierarchy is the component category. Component


is an abstract class encapsulating all the visual component
characteristics. Recalling the present foreground and background colors
and the presently chosen text font is accountable for a component item.

 Container

Container is an AWT element containing a different element such as


button, text field, tables, etc. Container is a component class subclass.
Container class keeps track of parts added to a different element.
7

 Panel

Panel class is a container specific subclass. There is no title bar, menu


bar or boundary in the panel. It is a container used to hold parts.

 Window class

Window class produces a window of the highest standard. Window has


no boundaries and menu bar.

 Frame

Frame is a Window subclass and can be resized. It is a container


containing various parts such as button, title bar, textfield, label, etc.
Most AWT apps are developed in Java using the Frame window. Frame
class is made up of two distinct builders

Frame() throws HeadlessException

Frame(String title) throws HeadlessException

Creating a Frame

There are two ways to create a Frame. They are,

 By Instantiating Frame class


 By extending Frame class

Creating Frame Window by Instantiating Frame class

import java.awt.*;

public class Testawt

Testawt()
8

Frame fm=new Frame(); //Creating a frame

abel lb = new Label("welcome to java graphics"); //Creating a label

fm.add(lb);//adding label to the frame

fm.setSize(300, 300); //setting frame size.

fm.setVisible(true); //set frame visibilty true

public static void main(String args[])

Testawt ta = new Testawt();

}
9

Creating Frame window by extending Frame class

package testawt;

import java.awt.*;

import java.awt.event.*;

public class Testawt extends Frame

public Testawt()

Button btn=new Button("Hello World");

add(btn); //adding a new Button.

setSize(400, 500); //setting size.

setTitle("StudyTonight"); //setting title.

setLayout(new FlowLayout());//set default layout for frame.

setVisible(true); //set frame visibilty true.

public static void main (String[] args)

Testawt ta = new Testawt(); //creating a frame.

}
10

Points to note:

 While creating a frame (either by instantiating or extending


Frame class), the following two attributes are a must for
visibility of the frame:
 setSize(int width, int height);
 setVisible(true);
 When you create other components like Buttons, TextFields, etc,
you need to add it to the frame by using the method -
add(Component's Object);
 You can add the following method also for resizing the frame -
setResizable(true);

Applets
 Applets are small Java applications which can be accessed on an
Internet server, transported over the Internet, and can be installed
11

and run automatically as part of a web document.


 The applet can create a graphical user interface after a user gets an
applet. It has restricted access to resources so that complicated
computations can be carried out without adding the danger of
viruses or infringing data integrity.
 Any Java applet is a class that extends the class of
java.applet.Applet.
 There is no main() methods in an Applet class. Using JVM it is
regarded. The JVM can operate an applet application using either a
Web browser plug-in or a distinct runtime environment.
 JVM generates an applet class instant and invokes init() to initialize
an applet.

PROGRAM :-
import java.awt.*;

import java.applet.*;

public class Simple extends Applet

public void paint(Graphics g)

g.drawString("A simple Applet", 20, 20);

}
12

Every Applet application must import 2 packages - java.applet. & java.awt.

Abstract Window Toolkit (AWT) classes are imported by java.awt.*. Applets


communicate (directly or indirectly) via the AWT with the client. The AWT includes
support for a graphical user interface based on a window. Java.applet.* imports the
Applet package containing the Applet class. Any applet you generate must be an
Applet class subclass.

The class in the program must be declared public because code outside of the
program will be accessed to it. Every request in Applet must declare a method for
paint. AWT class defines this method and the applet must override it. Every moment
an applet requires to redisplay its output, the paint() method is called. Another
significant thing to notice about the applet implementation is that an applet
execution does not start with the main method. In reality, there is no primary/main
method in an applet implementation.

Benefits of Applets

 As it operates on the client side, it requires much less response


time.
 Any browser that has JVM operating in it can operate it.

Applet class
13

Applet class provides all the support needed to execute applets, such as initializing
and destroying applets. It also provides techniques/methods for loading and
displaying audio videos and playback pictures.

An Applet Skeleton

These 4 methods are overridden by most applets. These four methods are the
lifecycle of the Applet.

 init() : The first technique to be called is init(). This is where you


initialize the variable. This technique is only called once during the
applet runtime.
 start() : Method start() is called after ini(). This technique is called
after it has been stopped to restart an applet.
 stop() : Method stop() is called to suspend threads that do not need
to operate when the applet is not noticeable.
 destroy() : The destroy() technique/method is called if you need to
remove your applet from memory entirely.

Note: The stop() method is always called/executed before destroy() method.

Example of an Applet Skeleton

import java.awt.*;

import java.applet.*;

public class AppletTest extends Applet

public void init()

//initialization
14

public void start ()

//start or resume execution

public void stop()

//suspend execution

public void destroy()

//perform shutdown activity

public void paint (Graphics g)

//display the content of window

Example of an Applet

import java.applet.*;

import java.awt.*;

public class MyApplet extends Applet


15

int height, width;

public void init()

height = getSize().height;

width = getSize().width;

setName("MyApplet");

public void paint(Graphics g)

g.drawRoundRect(10, 30, 120, 120, 2, 3);

}
16

Running Applet using Applet Viewer

Write a brief HTML file as mentioned above to run an Applet with an applet viewer. If
you name it as run.htm, your applet program will operate the following command.

f:/>appletviewer run.htm

77777777JAVA SWINGS
Java Swing tutorial is a part of Java Foundation Classes (JFC) that
is used to create window-based applications. It is built on the top of
AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight


components.

The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.

Difference between AWT and Swing


There are many differences between java Awt and swing that are given below
17

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

4) AWT provides less components than Swing. Swing provides more powerful components such as
tables, lists, scrollpanes, colorchooser, tabbedpane etc.

5) AWT doesn't follows MVC(Model View Controller) Swing follows MVC.


where model represents data, view represents
presentation and controller acts as an interface
between model and view.

MVC architectural:
Model designs based on MVC architecture follow the MVC design pattern and they
separate the application logic from the user interface when designing software. As
the name implies MVC pattern has three layers, which are:

 Model – Represents the business layer of the application


 View – Defines the presentation of the application
 Controller – Manages the flow of the application

In Java Programming context, the Model consists of simple Java classes, the View
displays the data and the Controller consists of servlets. This separation results in
user requests being processed as follows:

1. The browser on the client sends a request for a page to the controller present
on the server
2. The controller performs the action of invoking the model, thereby, retrieving
18

the data it needs in response to the request


3. The controller then gives the retrieved data to the view
4. The view is rendered and sent back to the client for the browser to display

Separating a software application into these three distinct components is a good


idea for a number of reasons. Let’s take a look at what those are.

Advantages of MVC Architecture in Java


MVC architecture offers a lot of advantages for a programmer when developing
applications, which include:

 Multiple developers can work with the three layers (Model, View, and Controller)
simultaneously
 Offers improved scalability, that supplements the ability of the application to grow
 As components have a low dependency on each other, they are easy to maintain
 A model can be reused by multiple views which provides reusability of code
 Adoption of MVC makes an application more expressive and easy to understand
 Extending and testing of the application becomes easy

Now you know why the MVC is the most popular design patterns in the web
programming world. But, if you are still struggling to get your head around the
concept of MVC, don’t worry. We will dig deep into each of these layers and learn
their purpose with the help of an example program.

Implementation of MVC using Java

To implement a web application based on MVC design pattern, we will create

 Course Class, which acts as the model layer


 CourseView Class, which defines the presentation layer (view layer)
 CourseContoller Class, which acts as a controller

The Model Layer

In the MVC design pattern, the model is the data layer which
defines the business logic of the system and also represents the
state of the application. The model objects retrieve and store the
state of the model in a database. Through this layer, we apply rules
to data, which eventually represents the concepts our application
manages. Now, let’s create a model using Course Class.

} package MyPackage;
public class Course {
private String CourseName;
private String CourseId;
private String CourseCategory;
19

public String getId() {


return CourseId;
}
public void setId(String id) {
this.CourseId = id;
} public String getName() {
return CourseName;
}
public void setName(String name) {
this.CourseName = name;
} public String getCategory() {
return CourseCategory;
} public void setCategory(String category) {
this.CourseCategory = category; }
}

The View Layer

This layer of the MVC design pattern represents the output of the
application or the user interface. It displays the data fetched from the
model layer by the controller and presents the data to the user whenever
asked for. It receives all the information it needs from the controller and
it doesn’t need to interact with the business layer directly. Let’s create a
view using CourseView Class.
}
package MyPackage;public class CourseView {
public void printCourseDetails(String CourseName,String
CourseId,
String CourseCategory){
System.out.println("Course Details: ");
System.out.println("Name: " + CourseName);
System.out.println("Course ID: " + CourseId);
System.out.println("Course Category: " + CourseCategory);
}
}

The Controller Layer


20

The Controller is like an interface between Model and View. It receives


the user requests from the view layer and processes them, including the
necessary validations. The requests are then sent to the model for data
processing. Once they are processed, the data is again sent back to the
controller and then displayed on the view. Let’s create CourseContoller
Class which acts as a controller.
package MyPackage;public class CourseController {
private Course model;
private CourseView view;
public CourseController(Course model, CourseView view){
this.model = model;
this.view = view;
} public void setCourseName(String name){
model.setName(name);
} public String getCourseName(){
return model.getName();
} public void setCourseId(String id){
model.setId(id);
} public String getCourseId(){
return model.getId();
} public void setCourseCategory(String category){
model.setCategory(category);
} public String getCourseCategory(){
return model.getCategory();
}
public void updateView(){
view.printCourseDetails(model.getName(), model.getId(), model.getCategory());
}
}

A cursory glance at the code will tell us that this controller class is just
responsible for calling the model to get/set the data and updating the
view based on that. Now let’s have a look at how all of these are tied
together.

Main Java Class


21

Let’s call this class “MVCPatternDemo.java”. Check out the


code below.
package MyPackage;
public class MVCPatternDemo {
public static void main(String[] args) { //fetch student record based
on his roll no from the database
Course model = retriveCourseFromDatabase(); //Create a view : to
write course details on console
CourseView view = new CourseView(); CourseController controller =
new CourseController(model, view);
controller.updateView(); //update model data
controller.setCourseName("Python");
System.out.println("nAfter updating, Course
Details are as follows");
controller.updateView();
}
private static Course retriveCourseFromDatabase()
{
Course course = new Course();
course.setName("Java");
course.setId("01");
course.setCategory("Programming");
return course;
}
}

The above class fetches the course data from the Further, it also invokes
the function using which the user enters the set of values. It then pushes
those values into the Course model. Then, it initializes the view we had
created earlier in the article. CourseController class and binds it to
the Course class and the CourseView class. The updateView() method
which is a part of the controller then updates the course details on the
console. Check out the output below.

Output
Course Details:
22

Name: Java
Course ID: 01
Course Category: Programming
After updating, Course Details are as follows
Course Details:
Name: Python
Course ID: 01
Course Category: Programming

HIERARCHY FOR SWING COMPONENTS:-


23

As seen from the above hierarchy we have Container classes –


frame, dialog, Panel, Applet, etc. There are also Component
classes derived from the JComponent class of Swing API.
Some of the classes that inherit from JComponent are JLabel,
JList, JTextBox, etc.
24

Some of the important classes of Swing API are as follows:


 JWindow: The JWindow class of Swing inherits the
Window class directly. The JWindow class uses
‘BorderLayout’ as the default layout.
 JPanel: JPanel is a descendent of JComponent class
and is on similar lines to AWT class Panel and has
‘FlowLayout’ as the default layout.
 JFrame: JFrame descends from the Frame
class. The components added to the Frame are
called contents of the Frame.
 JLabel: JLabel class is a subclass of the
JComponent. It is used to create text labels in the
application.
 JButton: The push-button functionality in Swing is
provided by JButton. We can associate a string, an
icon, or both with the JButton object.
 JTextField: JTextField class provides a text field in
which we can edit a single line of text.
JFrame In Java
A Frame, in general, is a container that can contain other
components such as buttons, labels, text fields, etc. A Frame
window can contain a title, a border, and also menus, text fields,
buttons, and other components. An application should contain
a frame so that we can add components inside it.

The Frame in Java Swing is defined in class


javax.swing.JFrame. JFrame class inherits the java.awt.Frame
class. JFrame is like the main window of the GUI application
using swing.

We can create a JFrame window object using two approaches:

1) By Extending The JFrame Class


25

The first approach is creating a new class to construct a Frame. This


class inherits from the JFrame class of the javax.swing package.

The following program implements this approach.


import javax.swing.*;
class FrameInherited extends JFrame{ //inherit from JFrame class
JFrame f;
FrameInherited(){
JButton b=new JButton("JFrame_Button");//create button object
b.setBounds(100,50,150, 40);

add(b);//add button on frame


setSize(300,200);
setLayout(null);
setVisible(true);
}
}
public class Main {
public static void main(String[] args) {
new FrameInherited(); //create an object of FrameInherited class
}
}
O/P:-

In the above program, we have created a frame from the


26

JFrame class by creating an instance of the JFrame class.

JPanel In Java
A panel is a component that is contained inside a frame
window. A frame can have more than one-panel components
inside it with each panel component having several other
components.

In easier terms, we can use panels to partition the frame. Each


panel groups several other components inside it. In other words,
we use panels to organize components inside the frame.

The swing API class that implements the panel component is


JPanel. JPanel class inherits from JComponent and has
FlowLayout as its default layout.

The following program demonstrates the creation of a panel


container in a frame using javax.swing package classes.

import javax.swing.*;
class JPanelExample {
JPanelExample(){
JFrame frame = new JFrame("Panel Example"); //create a frame
JPanel panel = new JPanel(); //Create JPanel Object
panel.setBounds(40,70,100,100); //set dimensions for Panel
JButton b = new JButton("ButtonInPanel"); //create JButton object
b.setBounds(60,50,80,40); //set dimensions for button
panel.add(b); //add button to the panel
frame.add(panel); //add panel to frame
frame.setSize(400,400);
frame.setLayout(null);
27

frame.setVisible(true);
}
}
public class Main {
public static void main(String[] args) {
new JPanelExample(); //create an object of FrameInherited class
}
}
Output:

CONTAINERS;-

Swing Containers can be described as a special


component that can hold the gathering of components.
It will have the capability to provide the gap to put the
28

components. Swing tool kit provided the two types of


Swing Containers they are top level containers and low
level containers, top level containers are heavy wait
Swing Containers such as JFrame, JApplet, JWindow,
JDialogue and low level Swing Containers are light
weight containers such as JPanel. The commonly used
containers are JFrame, JPanel, JWindow.
The difference between the component and container is
that component is an object that can provide the visual
representation, where as container is also a component
that can hold the gathering of components as follows.
29

JPanel is a light weight Swing Containers and used to gather


the all the components. The basic declaration of JPanel is as
follows.

public class JPanel


extends JComponent
implements Accessible

Below is the source code to build panel in Swing.

JPanelSwing.java

package swing;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class JPanelSwing extends JFrame {

private JLabel labelUsername = new JLabel("Enter username:


");
private JLabel labelPassword = new JLabel("Enter password:
");
30

private JTextField textUsername = new JTextField(20);


private JPasswordField fieldPassword = new
JPasswordField(20);
private JButton buttonLogin = new JButton("Login");

public JPanelSwing() {
super("JPanel Demo Program");

// create a new panel with GridBagLayout manager


JPanel newPanel = new JPanel(new GridBagLayout());

GridBagConstraints constraints = new


GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(10, 10, 10, 10);

// add components to the panel


constraints.gridx = 0;
constraints.gridy = 0;
newPanel.add(labelUsername, constraints);

constraints.gridx = 1;
newPanel.add(textUsername, constraints);

constraints.gridx = 0;
constraints.gridy = 1;
newPanel.add(labelPassword, constraints);

constraints.gridx = 1;
newPanel.add(fieldPassword, constraints);

constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.CENTER;
newPanel.add(buttonLogin, constraints);
31

// set border for the panel


newPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Login Panel"));

// add the panel to this frame


add(newPanel);

pack();
setLocationRelativeTo(null);
}

public static void main(String[] args) {


// set look and feel to the system look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLook
AndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JPanelSwing().setVisible(true);
}
});
}
}

Create a class that should extend JFrame and include labels,


text fields, button component.

private JLabel labelUsername = new JLabel("Enter username: ");


private JLabel labelPassword = new JLabel("Enter password: ");
private JTextField textUsername = new JTextField(20);
private JPasswordField fieldPassword = new JPasswordField(20);
private JButton buttonLogin = new JButton("Login");
32

Create a constructor, create a panel with GridBagLayout manager.

Public JPanelSwing() {
super("JPanel Demo Program");
JPanel newPanel = new JPanel(new GridBagLayout());

Set the border for the panel and add to the frame.

newPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Login Panel"));
add(newPanel);

Set the look and feel of window application.


try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel
ClassName());
} catch (Exception ex) {
ex.printStackTrace();
}

Output:
Output will be as follows.Where created one text field, password field,
login button also and created look & feel to the window application as
follows.
33

When user click on open a frame button “Welcome To SPlessons ”


message will be opened.
34

SIMPLE SWING APPLICATION:-

LAYOUT MANAGER TYPES:-

Java Layout Manager


The Layout manager is used to layout (or arrange) the GUI Java
components inside a container. There are many layout
managers, but the most frequently used are-

1.Java BorderLayout
o BorderLayout(): creates a border layout but with no gaps
between the components.

import java.awt.*;
import javax.swing.*;

public class Border {


JFrame f;
35

Border(){
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

2.Java FlowLayout:-
Fields of FlowLayout class

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered
alignment and a default 5 unit horizontal and vertical gap.
36

2. FlowLayout(int align): creates a flow layout with the given


alignment and a default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow
layout with the given alignment and the given horizontal
and vertical gap.

import java.awt.*;
import javax.swing.*;

public class MyFlowLayout{


JFrame f;
MyFlowLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
37

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}

3.Java GridBagLayout;-
Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column


per component in a row.
2. GridLayout(int rows, int columns): creates a grid
layout with the given rows and columns but no gaps
between the components.
3. GridLayout(int rows, int columns, int hgap, int
vgap): creates a grid layout with the given rows and
columns alongwith given horizontal and vertical
gaps.
38

import java.awt.*;
import javax.swing.*;

public class MyGridLayout{


JFrame f;
MyGridLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
39

f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}

4. JAVA BOX

1. public static final int X_AXIS


2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS
Constructor of BoxLayout class
1. BoxLayout(Container c, int axis): creates a box
layout that arranges the components with the given
axis.
40

import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample1 extends Frame {


Button buttons[];

public BoxLayoutExample1 () {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
41

setLayout (new BoxLayout (this, BoxLayout.Y_AXIS))


;
setSize(400,400);
setVisible(true);
}

public static void main(String args[]){


BoxLayoutExample1 b=new BoxLayoutExample1();
}
}
II-UNIT
HTML
HTML Lists
HTML Lists are used to specify lists of information. All lists may contain one or more
list elements. There are three different types of HTML lists:

1. Ordered List or Numbered List (ol)


2. Unordered List or Bulleted List (ul)
3. Description List or Definition List (dl)

HTML Ordered List or Numbered List


In the ordered HTML lists, all the list items are marked with numbers by default. It is
known as numbered list also. The ordered list starts with <ol> tag and the list items
start with <li> tag.

PROG:-

<ol>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ol>

Output:

1. Aries
2. Bingo
3. Leo
4. Oracle

HTML Ordered List


Let's see the example of HTML ordered list that displays 4 topics in numbered list.
Here we are not defining type="1" because it is the default type.

<ol>
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ol>

O/P:-

Output:

I. HTML
II. Java
III. JavaScript
IV. SQL

ol type="A"
A. HTML
B. Java
C. JavaScript
D. SQL

HTML Unordered List


HTML Unordered List or Bulleted List displays elements in bulleted format . We can
use unordered list where we do not need to display items in any particular order. The
HTML ul tag is used for the unordered list. There can be 4 types of bulleted list:

o disc
o circle
o square
o none
o o represent different ordered lists, there are 4 types of attributes in <ul> tag.
Type Description

Type "disc" This is the default style. In this style, the list items are marked with bullets.

Type "circle" In this style, the list items are marked with circles.

Type "square" In this style, the list items are marked with squares.

Type "none" In this style, the list items are not marked .

HTML Unordered
<ul>
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ul>

O/P:-
HTML

Java

JavaScript

SQL

ul type="circle"
<ul type="circle">
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ul>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>The type attribute with CSS property</h2>
<ul style="list-style-type: square;">
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ul>
</body>
</html>

O/P The type attribute with CSS property


HTML
Java
JavaScript
SQL

HTML Description List


HTML Description List or Definition List displays elements in definition form like in
dictionary. The <dl>, <dt> and <dd> tags are used to define description list.

The 3 HTML description list tags are given below:

1. <dl> tag defines the description list.


2. <dt> tag defines data term.
3. <dd> tag defines data definition (description).

<!DOCTYPE html>
<html>
<body>
<dl>
<dt>HTML</dt>
<dd>is a markup language</dd>
<dt>Java</dt>
<dd>is a programming language and platform</dd>
<dt>JavaScript</dt>
<dd>is a scripting language</dd>
<dt>SQL</dt>
<dd>is a query language</dd>
</dl>
</body>
</html>
O/P-
HTML
is a markup language
Java
is a programming language and platform
JavaScript
is a scripting language
SQL
is a query language

HTML Table
HTML table tag is used to display data in tabular form (row * column).
There can be many columns in a row.

We can create a table to display data in tabular form, using <table>


element, with the help of <tr> ,<td>, and <th> elements.

In Each table, table row is defined by <tr> tag, table header is defined by
<th>, and table data is defined by <td> tags.

HTML tables are used to manage the layout of the page e.g.
header section, navigation bar, body content, footer section etc.
But it is recommended to use div tag over table to manage the
layout of the page .

HTML Table Tags

Tag Description

<table> It defines a table.

<tr> It defines a row in a table.

<th> It defines a header cell in a table.

<td> It defines a cell in a table.

<caption> It defines the table caption.

<colgroup> It specifies a group of one or more columns in a table for formatting.

<col> It is used with <colgroup> element to specify column properties for each column.

<tbody> It is used to group the body content in a table.

<thead> It is used to group the header content in a table.

<tfooter> It is used to group the footer content in a tabl

<!DOCTYPE>
<html>
<body>
<table>
<tr><th>First_Name</th><th>Last_Name</th><th>Marks</th><
/tr>
<tr><td>Sonoo</td><td>Jaiswal</td><td>60</td></tr>
<tr><td>James</td><td>William</td><td>80</td></tr>
<tr><td>Swati</td><td>Sironi</td><td>82</td></tr>
<tr><td>Chetna</td><td>Singh</td><td>72</td></tr>
</table>
</body>
</html>
O/P-
First_Name Last_Name
Sonoo Jaiswal
James William
Swati Sironi
Chetna Singh

HTML Table with Border


There are two ways to specify border for HTML tables.

1. By border attribute of table in HTML


2. By border property in CSS

PROG:-

<!DOCTYPE>

<html>

<body>

<table border="1">
<tr><th>First_Name</th><th>Last_Name</th><th>Marks</
th></tr>

<tr><td>Sonoo</td><td>Jaiswal</td><td>60</td></tr>

<tr><td>James</td><td>William</td><td>80</td></tr>

<tr><td>Swati</td><td>Sironi</td><td>82</td></tr>

<tr><td>Chetna</td><td>Singh</td><td>72</td></tr>

</table>

</body>

</html>
First_Name Last_Name
Sonoo Jaiswal
James William
Swati Sironi
Chetna Singh
HTML Table Borders

HTML tables can have borders of different styles and shapes.

How To Add a Border


When you add a border to a table, you also add borders around each
table cell:

To add a border, use the CSS border property on table, th,


and td elements:

PROG:-
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>

<h2>Table With Border</h2>


<p>Use the CSS border property to add a border to
the table.</p>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
</html>
O/P:-
Table With Border
Use the CSS border property to add a border to the table.

Firstname Lastname Age


Jill Smith 50
Eve Jackson 94
John Doe 80

Style Table Borders


If you set a background color of each cell, and give the border a
white color (the same as the document background), you get the
impression of an invisible border:
PROG:-
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid white;
border-collapse: collapse;
}
th, td {
background-color: #96D4D4;
}
</style>
</head>
<body>
<h2>Table With Invisible Borders</h2>
<p>Style the table with white borders and a background
color of the cells to make the impression of invisible
borders.</p>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
</html>

O/P:-
Table With Invisible Borders
Style the table with white borders and a background color of the cells to
make the impression of invisible borders.

Firstname Lastname Age


Jill Smith 50
Eve Jackson 94
John Doe 80

HTML Table Width


To set the width of a table, add the style attribute to
the <table> element:

Example
Set the width of the table to 100%:
PROG:-
<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
border-collapse: collapse;
}
</style>

<body>
<h2>100% wide HTML Table</h2>

<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body></html>

O/P:-
100% wide HTML Table
Firstname Lastname Age
Jill Smith 50
Eve Jackson 94
John Doe 80

FORM IN HTML
An HTML form is used to collect user input. The user input is
most often sent to a server for processing.
Prog:-
<!DOCTYPE html>
<html>
<body>
<h2>HTML Forms</h2>
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"
value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"
value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
<p>If you click the "Submit" button, the form-data will be sent to
a page called "/action_page.php".</p>
</body>
</html>
o/p:-

HTML Forms
First name:

Jo h n

Last name:

Doe

S u b m it

If you click the "Submit" button, the form-data will be sent to a page called
"/action_page.php".

Frames
HTML provides programmers for dividing a single browser display into
multiple window sections, where each section holds the capability to
load individual URLs. This concept of HTML providing multiple frames at
one browser display is called frameset, and all the frame tags are used
within the container tag <frameset>. So the entire separation of HTML
pages is possible using the concept of frames. In his chapter, you will be
learning about the frames and how they are used for creating multiple
sections in a single browser display.
Html frameset tag:-
This tag is used for defining a specific window or frame inside the <frameset> tag. Every
<frame> within the <frameset> tag may use attributes for different purpose like: border,
resizing capability, include scrolling etc. The main use of frames is for displaying menu(s) in
any portion of your page along with the content in another part of the page. Multiple HTML
pages can be seen within the single vide-port of the browser window using this tag. Let's see
how:

Eg:-

<html>

<head>
<title>Example for Frame</title>
</head>
<frameset cols="20%,*">
<frame src="Ol.html"> 1st FRAME
<frame src="marquee.html"> 2nd FRAME
</frameset>

</html>

Various attributes frame tags:-

 src: is implemented for fetching the HTML file that needs to be loaded in one
of the frames. It takes the value as filename.html or filename.htm within
double-quotes.

 name: facilitates you in giving a name to your frame, and hence you can
indicate which frame(s) you are supposed to load into your page.

 frameborder: is used for specifying if the borders are being shown in the
frame you are using, and you can assign values either: 1 (yes) or 0 (no) for it.

 marginwidth: facilitates in specifying the frame borders width spacing in the


left and right sides. It takes the value in pixels.

 marginheight: facilitates in specifying the frame borders height spacing in top


and bottom sides. It also takes the value in pixels.

 Noresize: In general, it is possible to resize your frame just by clicking and


dragging the frame borders. But this attribute helps users stop resizing the
frames. It is written something like: noresize = "noresize".

 scrolling: is used for activating and deactivating the scroll-bar appearance in


your frame and takes either yes, no, or auto as values to be assigned to it
within double-quotes.

Cascading Style Sheets (CSS)

Cascading Style Sheets (CSS) is used to format the layout of a webpage.With


CSS, you can control the color, font, the size of text, the spacing between
elements, how elements are positioned and laid out, what background images or
background colors are to be used, different displays for different devices and
screen sizes, and much more!

Types of CSS (Cascading Style Sheet)

Cascading Style Sheet(CSS) is used to set the style in web pages that contain
HTML elements. It sets the background color, font-size, font-family, color, …
etc property of elements on a web page.

There are three types of CSS which are given below:


 Inline CSS
 Internal or Embedded CSS
 External CSS

Inline CSS: Inline CSS contains the CSS property in the body section attached
with element is known as inline CSS. This kind of style is specified within an
HTML tag using the style attribute.
Eg:-
<html>
<head>
<title>Inline CSS</title>
</head>

<body>
<p style = "color:#009900; font-size:50px;
font-style:italic; text-align:center;">
GeeksForGeeks
</p>

</body>
</html>

o/p:-

Internal or Embedded CSS:


This can be used when a single HTML document must be styled uniquely.
The CSS rule set should be within the HTML file in the head section i.e the
CSS is embedded within the HTML file.

Example:

<html>
<head>
<title>Internal CSS</title>
<style>
.main {
text-align:center;
}
.GFG {
color:#009900;
font-size:50px;
font-weight:bold;
}
.geeks {
font-style:bold;
font-size:20px;
}
</style>
</head>
<body>
<div class = "main">
<div class ="GFG">GeeksForGeeks</div>

<div class ="geeks">


A computer science portal for geeks
</div>
</div>
</body>
</html>

o/p:-

External CSS:
External CSS contains separate CSS file which contains only style property
with the help of tag attributes (For example class, id, heading, … etc). CSS
property written in a separate file with .css extension and should be linked to
the HTML document using link tag. This means that for each element, style
can be set only once and that will be applied across web pages.
Example: The file given below contains CSS property. This file save with .css
extension.
<html>
<head>
<link rel="stylesheet" href="geeks.css"/>
</head>

<body>
<div class = "main">
<div class ="GFG">GeeksForGeeks</div>
<div id ="geeks">
A computer science portal for geeks
</div>
</div>
</body>
</html>

o/p:-

Properties of CSS:
Inline CSS has the highest priority, then comes Internal/Embedded followed
by External CSS which has the least priority. Multiple style sheets can be
defined on one page. If for an HTML tag, styles are defined in multiple style
sheets then the below order will be followed.
 As Inline has the highest priority, any styles that are defined in the
internal and external style sheets are overridden by Inline styles.
 Internal or Embedded stands second in the priority list and
overrides the styles in the external style sheet.
 External style sheets have the least priority. If there are no styles
defined either in inline or internal style sheet then external style
sheet rules are applied for the HTML tags.
Supported Browser:
 Google Chrome
 Internet Explorer
 Firefox
 Opera
 Safari

Java scrip
Introduction:-
JavaScript is a very powerful client-side scripting language. JavaScript
is used mainly for enhancing the interaction of a user with the webpage.
In other words, you can make your webpage more lively and interactive,
with the help of JavaScript. JavaScript is also being used widely in game
development and Mobile application development.

Eg;-
<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
alert("Hello World!");
</script>
</head>
<body>
</body>
</html>
o/p:-
Hello World!

 javaScript is a client-side scripting language developed by Brendan Eich.


 JavaScript can be run on any operating systems and almost all web
browsers.
 You need a text editor to write JavaScript code and a browser to display
your web page.

javaScript Variable: Declare, Assign a Value with Example

Variables are used to store values (name = "John") or expressions (sum = x + y).

Declare Variables in JavaScript


Before using a variable, you first need to declare it. You have to use the
keyword var to declare a variable like this:

var name;
Assign a Value to the Variable
You can assign a value to the variable either while declaring the variable or after
declaring the variable.

var name = "John";

OR

var name;

name = "John";
Naming Variables
Though you can name the variables as you like, it is a good programming
practice to give descriptive and meaningful names to the variables. Moreover,
variable names should start with a letter and they are case sensitive. Hence the
variables student name and studentName are different because the letter n in a
name is different (n and N).

Eg;-
<html>

<head>

<title>Variables!!!</title>

<script type="text/javascript">

var one = 22;

var two = 3;

var add = one + two;

var minus = one - two;

var multiply = one * two;

var divide = one/two;

document.write("First No: = " + one + "<br />Second No: = " + two + " <br
/>");

document.write(one + " + " + two + " = " + add + "<br/>");

document.write(one + " - " + two + " = " + minus + "<br/>");

document.write(one + " * " + two + " = " + multiply + "<br/>");

document.write(one + " / " + two + " = " + divide + "<br/>");

</script>

</head>

o/p;-

First No: = 22
Second No: = 3
22 + 3 = 25
22 - 3 = 19
22 * 3 = 66
22 / 3 = 7.333333333333333
JavaScript in <head> or <body>
We can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.

The function is invoked (called) when a button is clicked

<html>

<head>

<script>

function myFunction() {

document.getElementById("demo").innerHTML = "Paragraph changed.";

</script>

</head>

<body>

<h2>JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>

</html>

O/P:-

JavaScript in Head
A Paragraph.
Try it

JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.

The function is invoked (called) when a button is clicked:

EG:-
<html>

<body>

<h2>JavaScript in Body</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>

function myFunction() {

document.getElementById("demo").innerHTML = "Paragraph changed.";

</script>

</body>

</html>

O/P:-

JavaScript in Body
A Paragraph.

Try it

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML
eg:-

<html>

<body>

<h2>My First Web Page</h2>

<p>My First Paragraph.</p>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML = 5 + 6;

</script>

</body>

</html>

O/P:-

My First Web Page


My First Paragraph.

11

Using document.write()
For testing purposes, it is convenient to use document.write():

<html>

<body>

<h2>My First Web Page</h2>

<p>My first paragraph.</p>


<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>

</html>

O/P:-
My First Web Page
My first paragraph.

Try it

Using window.alert()
<html>

<body>

<h2>My First Web Page</h2>

<p>My first paragraph.</p>

<script>

alert(5 + 6);

</script>

</body></html>

O/P:-

My First Web Page


My first paragraph.

Using console.log()
<html>
<body>
<h2>Activate Debugging</h2>
<p>F12 on your keybord will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>
<script>
console.log(5 + 6);
</script>
</body></html>

O/P:-

Activate Debugging
F12 on your keybord will activate debugging.

Then select "Console" in the debugger menu.

Then click Run again.

HTML Images
<html>
<body>
<h2>HTML Image</h2>
<img src="pic_trulli.jpg" alt="Trulli" width="500" height="333">
</body>
</html>
eg:-

<html>

<body>

<h2>HTML Image</h2>

<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">

</body></html>

HTML Images Syntax


The HTML <img> tag is used to embed an image in a web page.
Images are not technically inserted into a web page; images are linked to web pages.
The <img> tag creates a holding space for the referenced image.

The <img> tag is empty, it contains attributes only, and does not have a closing tag.

The <img> tag has two required attributes:

 src - Specifies the path to the image


 alt - Specifies an alternate text for the image

<html>

<body>

<h2>Alternative text</h2>

<p>The alt attribute should reflect the image content, so users who cannot see
the image gets an understanding of what the image contains:</p>

<img src="img_chania.jpg" alt="Flowers in Chania" width="460" height="345">

</body></html>

Width and Height, or Style


The width, height, and style attributes are all valid in HTML.

<html>

<head>

<style>

/* This style sets the width of all images to 100%: */

img {
width: 100%;

</style>

</head>

<body>

<h2>Width/Height Attributes or Style?</h2>

<p>The first image uses the width attribute (set to 128 pixels), but the style in the head
section overrides it, and sets the width to 100%.</p>

<img src="html5.gif" alt="HTML5 Icon" width="128" height="128">

<p>The second image uses the style attribute to set the width to 128 pixels, this will not
be overridden by the style in the head section:</p>

<img src="html5.gif" alt="HTML5 Icon"

style="width:128px;height:128px;">

</body>

</html>

Eg:-
<html>
<body>
<h2>Animated Images</h2>
<p>HTML allows moving images:</p>
<img src="programming.gif" alt="Computer man"
style="width:48px;height:48px;">
</body>
</html>
o/p:-

Animated Images
HTML allows moving images:

Objects in java scripts:-


JavaScript, almost "everything" is an object.

 Booleans can be objects (if defined with the new keyword)


 Numbers can be objects (if defined with the new keyword)
 Strings can be objects (if defined with the new keyword)
 Dates are always objects
 Maths are always objects
 Regular expressions are always objects
 Arrays are always objects
 Functions are always objects
 Objects are always objects

All JavaScript values, except primitives, are objects

JavaScript Primitives
A primitive value is a value that has no properties or methods.

A primitive data type is data that has a primitive value.

JavaScript defines 5 types of primitive data types:

 string
 number
 boolean
 null
 undefined

Value Type Comment

"Hello" string "Hello" is always "Hello"

3.14 number 3.14 is always 3.14

true boolean true is always true

false boolean false is always false

null null (object) null is always null

undefined undefined undefined is always undefine

Objects are Variables


<html>
<body>
<h2>JavaScript Objects</h2>
<p>Creating an object:</p>
<p id="demo"></p>
<script>
let person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>
</body>
</html>
o/p:-
JavaScript Objects
Creating an object:

John Doe

Creating a JavaScript Object


With JavaScript, you can define and create your own objects.

There are different ways to create new objects:

 Create a single object, using an object literal.


 Create a single object, with the keyword new.
 Define an object constructor, and then create objects of the constructed type.
 Create an object using Object.create().

Using an Object Literal


 This is the easiest way to create a JavaScript Object.

 Using an object literal, you both define and create an object in one statement.

 An object literal is a list of name:value pairs (like age:50) inside curly braces {}.

 The following example creates a new JavaScript object with four properties:
Eg:-
<html>
<body>
<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>
<p id="demo"></p>
<script>
const person = {firstName:"John", lastName:"Doe",
age:50,eyeColor:"blue"};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years
old.";
</script>
</body>
</html>
o/p:-
JavaScript Objects
Creating a JavaScript Object:

John is 50 years old.


DYNAMIC HTML:-
DHTML stands for Dynamic Hypertext Markup
language i.e., Dynamic HTML.

Uses of DHTML
Following are the uses of DHTML (Dynamic HTML):

o It is used for designing the animated and interactive web pages


that are developed in real-time.
o DHTML helps users by animating the text and images in their
documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus
or rollover buttons.
o This term is also used to create various browser-based action
games.
o It is also used to add the ticker on various websites, which needs
to refresh their content automatically.

Difference between HTML and DHTML

HTML (Hypertext Markup DHTML (Dynamic Hypertext Markup language)


language)
1. HTML is simply a markup 1. DHTML is not a language, but it is a set of technologies
language. of web development.
2. It is used for developing and 2. It is used for creating and designing the animated and
creating web pages. interactive web sites or pages.
3. This markup language creates 3. This concept creates dynamic web pages.
static web pages.
4. It does not contain any server- 4. It may contain the code of server-side scripting.
side scripting code.
5. The files of HTML are stored with 5. The files of DHTML are stored with the .dhtm extension in
the .html or .htm extension in a a system.
system.
6. A simple page which is created 6. A page which is created by a user using the HTML, CSS, D
by a user without using the scripts and JavaScript technologies called a DHTML page.
or styles called as an HTML page.
7. This markup language does not 7. This concept needs database connectivity because it
need database connectivity. interacts with users.

DHTML JavaScript
JavaScript can be included in HTML pages, which creates the content of the page as
dynamic. We can easily type the JavaScript code within the <head> or <body> tag of
a HTML page. If we want to add the external source file of JavaScript, we can easily
add using the <src> attribute.

Following are the various examples, which describes how to use the JavaScript
technology with the DHTML:

<HTML>

<head>

<title>

Method of a JavaScript

</title>

</head>

<body>

<script type="text/javascript">

document.write("JavaTpoint");

</script></body></html>

o/p;-
JavaScript and HTML event
A JavaScript code can also be executed when some event occurs. Suppose, a user
clicks an HTML element on a webpage, and after clicking, the JavaScript function
associated with that HTML element is automatically invoked. And, then the
statements in the function are performed.

<head>

<title>

DHTML with JavaScript

</title>

<script type="text/javascript">

function dateandtime()

alert(Date());

</script>

</head>

<body bgcolor="orange">

<font size="4" color="blue">

<center> <p>

Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>


# to check the today's date and time.

</p> </center>

</font>

</body>

</html>

o/p;-

JavaScript and HTML DOM

<html>

<head>

<title> Check Student Grade

</title>

</head>

<body>

<p>Enter the percentage of a Student:</p>


<input type="text" id="percentage">

<button type="button" onclick="checkGrade()">

Find Grade

</button>

<p id="demo"></p>

<script type="text/javascript">

function checkGrade() {

var x,p, text;

p = document.getElementById("percentage").value;

x=parseInt(p);

if (x>90 && x <= 100) {

document.getElementById("demo").innerHTML =
"A1";

} else if (x>80 && x <= 90) {

document.getElementById("demo").innerHTML =
"A2";

} else if (x>70 && x <= 80) {

document.getElementById("demo").innerHTML =
"A3";

</script>

</body>
</html>

o/p:-

Enter the percentage of a Student:

Find Grade
CSS with JavaScript in DHTML

<html>
<head>
<title>
getElementById.style.property example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on
the following different buttons. </p>
<button onclick="change_Color('green');"> Green
</button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">

function change_Color(newColor) {
var element =
document.getElementById('demo').style.color =
newColor;
}
</script>

</body>
</html>
o/p:-

This text changes color when click on the following different


buttons.

Green Blue

XML :-
XML stands for eXtensible Markup Language.

XML was designed to store and transport data.

XML was designed to be both human- and machine-readable.

Why Study XML


XML plays an important role in many different IT systems.

XML is often used for distributing data over the Internet.

It is important (for all types of software developers!) to have a good understanding


of XML.

Important XML Standards


XML standards:
 XML AJAX
 XML DOM
 XML XPath
 XML XSLT
 XML XQuery
 XML DTD
 XML Schema
 XML Services

XML Does Not Use Predefined Tags


The XML language has no predefined tags.

The tags in the example above (like <to> and <from>) are not defined in any XML
standard. These tags are "invented" by the author of the XML document.

HTML works with predefined tags like <p>, <h1>, <table>, etc.

With XML, the author must define both the tags and the document structure.

XML is Extensible
Most XML applications will work as expected even if new data is added (or removed).

Imagine an application designed to display the original version of note.xml (<to>


<from> <heading> <body>).

Then imagine a newer version of note.xml with added <date> and <hour> elements,
and a removed <heading>.

The way XML is constructed, older version of the application can still work:

XML DTD
The purpose of a DTD is to define the structure and the legal elements and attributes of
an XML document:

Note.dtd:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

The DTD above is interpreted like this:

 !DOCTYPE note - Defines that the root element of the document is


note
 !ELEMENT note - Defines that the note element must contain the
elements: "to, from, heading, body"
 !ELEMENT to - Defines the to element to be of type "#PCDATA"
 !ELEMENT from - Defines the from element to be of type
"#PCDATA"
 !ELEMENT heading - Defines the heading element to be of type
"#PCDATA"
 !ELEMENT body - Defines the body element to be of type
"#PCDATA"

#PCDATA means parseable character data.

EG:-

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE note [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
]>

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>
An entity has three parts: it starts with an ampersand (&), then comes the entity name,
and it ends with a semicolon (;).

When to Use a DTD?


With a DTD, independent groups of people can agree to use a standard DTD for
interchanging data.

With a DTD, you can verify that the data you receive from the outside world is valid.

You can also use a DTD to verify your own data.

XML Schema:-
An XML Schema describes the structure of an XML document, just like a DTD.

An XML document with correct syntax is called "Well Formed".

An XML document validated against an XML Schema is both "Well Formed" and
"Valid".

<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

The Schema above is interpreted like this:

 <xs:element name="note"> defines the element called "note"


 <xs:complexType> the "note" element is a complex type
 <xs:sequence> the complex type is a sequence of elements
 <xs:element name="to" type="xs:string"> the element "to" is of type string (text)
 <xs:element name="from" type="xs:string"> the element "from" is of type
string
 <xs:element name="heading" type="xs:string"> the element "heading" is of
type string
 <xs:element name="body" type="xs:string"> the element "body" is of type
string

XML Schemas are More Powerful than DTD


 XML Schemas are written in XML
 XML Schemas are extensible to additions
 XML Schemas support data types
 XML Schemas support namespaces

Why Use an XML Schema?


With XML Schema, your XML files can carry a description of its own format.

With XML Schema, independent groups of people can agree on a standard for
interchanging data.

With XML Schema, you can verify data.

XML Schemas Support Data Types


One of the greatest strengths of XML Schemas is the support for data types:

 It is easier to describe document content


 It is easier to define restrictions on data
 It is easier to validate the correctness of data
 It is easier to convert data between different data types

XML Schemas use XML Syntax


Another great strength about XML Schemas is that they are written in XML:

 You don't have to learn a new language


 You can use your XML editor to edit your Schema files
 You can use your XML parser to parse your Schema files
 You can manipulate your Schemas with the XML DOM
 You can transform your Schemas with XSLT

XML DOM:-

Document Object Model (DOM) is a platform and language-neutral interface that


allows programs and scripts to dynamically access and update the content,
structure, and style of a document."

The HTML DOM defines a standard way for accessing and manipulating HTML
documents. It presents an HTML document as a tree-structure.

The XML DOM defines a standard way for accessing and manipulating XML documents.
It presents an XML document as a tree-structure.

Understanding the DOM is a must for anyone working with HTML or XML
Eg:-

<!DOCTYPE html>

<html>

<body>

<h1 id="demo">This is a Heading</h1>

<button type="button"

onclick="document.getElementById('demo').innerHTML = 'Hello World!'">Click Me!

</button>

</body>

</html>

o/p:-

This is a Heading
Click Me!

Eg:

<!DOCTYPE html>

<html>

<body>

<p id="demo"></p>

<script>

Var text,parser,xmlDoc;

Text=”<bookstore><book>:+

"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +

"<year>2005</year>" +

"</book></bookstore>";

parser = new DOMParser();

xmlDoc = parser.parseFromString(text,"text/xml");

document.getElementById("demo").innerHTML =

xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;

</script>

</body>

</html>

o/p:-

Everyday Italian

Presenting XML:-

XML documents are presented using Extensible Stylesheet which expresses


stylesheets. XSL stylesheet are not the same as HTML cascading stylesheets. They
create a style for a specific XML element, with XSL a template is created. XSL
basically transforms one data structure to another i.e., XML to HTML. Example Here
is the XSL file for the XML document of Example This line must be included in the
XML document which reference stylesheet
III-UNIT
JDBC:-
INTRODUCTION:-
DBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing 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.
Before moving further, you need to have a good understanding of the following
two subjects −
 Core JAVA Programming
 SQL or MySQL Database

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and execute the query with
the database. But, ODBC API uses ODBC driver which is written in C language (i.e.
platform dependent and unsecured). That is why Java has defined its own API (JDBC
API) that uses JDBC drivers (written in Java language).
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 −
 JDBC API − This provides the application-to-JDBC Manager connection.
 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 −
 DriverManager − This class manages a list of database drivers. Matches
connection requests from the java application with the proper database
driver using communication sub protocol. 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 manages objects of this type. It also abstracts
the details associated with working with Driver objects.
 Connection − This 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.

We can use JDBC API to handle database using Java program and can perform the
following activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

Types of JDBC drivers


There are four types of JDBC drivers:-

1. Type-1 Driver or JDBC-ODBC Bridge

This driver acts as a bridge between JDBC and ODBC. It converts


JDBC calls into ODBC calls and then sends the request to ODBC
driver. It is easy to use but execution time is slow.
2. Type-2 Driver or Native API Partly Java Driver
This driver uses JNI (Java Native Interface) call on database specific native

client API. It is comparatively faster than Type-1 driver but it requires native

library and cost of application also increases.


3. Type-3 Driver or Network Protocol Driver
These drivers communicate to JDBC middleware server using proprietary

network protocol. This middleware translates the network protocol to

database specific calls. They are database independent. They can switch

from one database to another but are slow due to many network calls.
4. Type-4 or Thin Driver
This driver is also called pure Java driver because they directly interact with

the database. It neither requires any native library nor middleware server. It

has better performance than other drivers but comparatively slow due to an

increase in a number of network calls.


Conclusion
This article specifies the JDBC architecture, its interfaces and types of

drivers to communicate or interact with the database.Now a day’s

databases are maintained in every sector hence updating them and

retrieving data from them is necessary. So understanding the architecture

would help to understand the basic JDBC concepts.

CONNECTIONS;-
The following 5 steps are the basic steps involve in connecting a
Java application with Database using JDBC.

1. Register the Driver

2. Create a Connection

3. Create SQL Statement

4. Execute SQL Statement

5. Closing the connection

These drivers communicate to JDBC middleware server using proprietary


network protocol. This middleware translates the network protocol to
database specific calls. They are database independent. They can switch
from one database to another but are slow due to many network calls.
Prog:- lass WhatIsJdbc{

public static void main(String args[]){

System.out.println("Hello JavaWorld"); }}

Now compile the code by entering the command: javac WhatIsJdbc.java.


Compiling will output the WhatIsJdbc.class file. Execute this file from the
command line with the call: java WhatIsJdbc.

Prerequisites of JDBC
 JDK(Java Development Kit)
 Oracle Database: Download it
from http://www.oracle.com/technetwork/database/database-
technologies/express-edition/downloads/index.html
 JDBC driver for Oracle Database: Download it
from http://www.oracle.com/technetwork/apps-tech/jdbc-
112010-090769.html. Add ojdbc6.jar to the project library.

Steps to connect Java program and database:


Creating a simple JDBC application
package com.techvidvan.jdbctutorial;

import java.sql. * ;
public class JDBCTutorial {

public static void main(String args[]) throws ClassNotFoundException,

SQLException,

String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";

String url = "jdbc:odbc:XE";

String username = "John";

String password = "john12";

String query1 = "insert into students values(101, 'Pooja')";

//Load the driver class

Class.forName(driverName);

//Obtaining a connection

Connection con = DriverManager.getConnection(url, username, password);

//Obtaining a statement

Statement stmt = con.createStatement();

//Executing the query

int count = stmt.executeUpdate(query1);

System.out.println("The number of rows affected by this query= " + count);

//Closing the connection

con.close();

}}

The above example shows the basic steps to access a database using

JDBC. We used the JDBC-ODBC bridge driver to connect to the database.

We have to import the java.sql package that provides basic SQL


functionality.

Prog:-

importjava.sql.*;

importjava.util.*;

class Main

public static void main(String a[])

//Creating the connection

String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "system";

String pass = "12345";

//Entering the data

Scanner k = new Scanner(System.in);

System.out.println("enter name");

String name = k.next();

System.out.println("enter roll no");

int roll = k.nextInt();

System.out.println("enter class");

String cls = k.next();

//Inserting data using SQL query


String sql = "insert into student1
values('"+name+"',"+roll+",'"+cls+"')";

Connection con=null;

try

DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

//Reference to connection interface

con = DriverManager.getConnection(url,user,pass);

Statement st = con.createStatement();

int m = st.executeUpdate(sql);

if (m == 1)

System.out.println("inserted successfully : "+sql);

else

System.out.println("insertion failed");

con.close();

catch(Exception ex)

System.err.println(ex);

} }

o/p:-
JDBC Connection

The JDBC Connection class, java.sql.Connection, represents a database


connection to a relational database. Before you can read or write data from
and to a database via JDBC, you need to open a connection to the
database.

1.Loading the JDBC Driver


The first thing you need to do before you can open a JDBC connection to a
database is to load the JDBC driver for the database. Actually, from Java 6
this is no longer necessary, but doing so will not fail. You load the JDBC
driver like this:

Class.forName("driverClassName");

Each JDBC driver has a primary driver class that initializes the driver when
it is loaded. For instance, to load the H2Database driver, you write this:

Class.forName("org.h2.Driver");

You only have to load the driver once. You do not need to load it before
every connection opened. Only before the first JDBC connection opened.

2.Opening the JDBC Connection


You open a JDBC Connection by call the java.sql.DriverManager class
method getConnection(). There are three variants of this method. I will
show each variant in the following sections.

Open Connection With URL

The first method variant only takes a URL to the database as parameter.
This is how calling getConnection() only with the URL as parameter
looks:

String url = "jdbc:h2:~/test"; //database specific url.

Connection connection =
DriverManager.getConnection(url);

The url is the url to your database. You should check the documentation
for your database and JDBC driver to see what the format is for your
specific database. The url shown above is for a H2Database.

Open Connection With URL, User and Password

The second variant of getConnection() takes both a database URL, a


user name and a password as parameters. Here is an example of calling
that variant of getConnection() :

String url = "jdbc:h2:~/test"; //database specific url.


String user = "sa";
String password = "";

Connection connection =
DriverManager.getConnection(url, user, password);

The user and password parameters are the user name and password for
your database.

Open Connection With URL and Properties

The third variant of getConnection() takes a database URL and


a Properties object as parameter. Here is an example of calling this
variant of getConnection():

String url = "jdbc:h2:~/test"; //database specific url.


Properties properties = new Properties( );
properties.put( "user", "sa" );
properties.put( "password", "" );

Connection connection =
DriverManager.getConnection(url, properties);

The Properties object is used to pass special properties the database


needs when opening the connection. Exactly what properties a given
database needs, depends on the database and its features etc. You will
have to check the documentation for given database and its JDBC driver to
see that.

3.Closing the JDBC Connection


Once you are done using the database connection you should close it. This
is done by calling the Connection.close() method, like this:

connection.close();

It is important to close a JDBC Connection once you are done with it. A
database connection takes up an amount of resources, both inside your
own application, but especially on the database server. Therefore, keeping
database connections open that are unused will require the database to
keep unnecessary resources allocated for the connection.

Closing the Connection via Try-With-Resources

It is possible to close a JDBC Connection automatically via the Java Try-


with-resources construct that was added in Java 7. Here is an example of
how to do that:

String url = "jdbc:h2:~/test"; //database specific url.


String user = "sa";
String password = "";

try(Connection connection =
DriverManager.getConnection(url, user, password)) {

//use the JDBC Connection inhere }


4.setAutoCommit()
The JDBC Connection setAutoCommit() method is used to switch the
connection into, or out of, auto commit mode. In auto commit mode each
single update sent to the database will be committed immediately, as if
executed within its own transaction. When not in auto commit mode, each
database transaction must be explicitly committed by calling
the Connection commit() method. This is explained in more detail in the
tutorial about JDBC Transactions.

Here is an example of switching a JDBC Connection into auto commit


mode:

connection.setAutoCommit(true);

And here is an example of switching a JDBC Connection out of auto


commit mode:

connection.setAutoCommit(false);

The default mode of a JDBC Connection if the auto commit mode is not
specified is to have auto commit mode switched on.

5.commit()
The JDBC Connection commit() method commits a transaction. Exactly
how transactions work and should be handled is covered in the JDBC
Transactions . Here is a simple example of committing a transaction via a
JDBC Connection. Please note that the correct exception handling has
been kept out of this example to make it brief.

connection.setAutoCommit(false);

// perform operations on the JDBC Connection


// which are to be part of the transaction

connection.commit();

Keep in mind, that if some of the operations in the transaction fail, you
would most likely want to call the rollback() method instead
of commit().

6.rollback()
The Java JDBC Connection rollback() method rolls back the operations
executed within the currently ongoing transaction. Exactly how to handle
the calls to commit() and / or rollback() is covered in the JDBC
Transactions Tutorial. Here is a simple example of calling the
JDBC Connection rollback() method:

try{
connection.setAutoCommit(false);

// perform operations on the JDBC Connection


// which are to be part of the transaction

connection.commit();
} catch (SQLException e) {
connection.rollback();
}

Notice how rollback() is called within the catch-block of a try-catch block.


In case an exception is thrown while trying to carry out the operations in
the transaction, the whole transaction is rolled back.

7.createStatement()
The JDBC Connection createStatement() creates a JDBC
Statement object. A Statement instance can be used to execute SQL
updates against the database, or to execute SQL queries against the
database. Here is an example of creating a JDBC Statement instance via
the JDBC Connection createStatement() method:

Statement statement = connection.createStatement();

8.prepareStatement()
The JDBC Connection prepareStatement() creates a JDBC
PreparedStatement object. A PreparedStatement instance can be used
to execute SQL updates against the database, or to execute SQL queries
against the database. Here is an example of creating a
JDBC PreparedStatement instance via the
JDBC Connection prepareStatement() method:

String sql = "select * from people where id=?";

PreparedStatement preparedStatement =
connection.prepareStatement(sql);

getMetaData()
The JDBC Connection getMetaData() method returns a JDBC
DatabaseMetaData object which can be used to introspect the database
the JDBC Connection is connected to. What you can do with
the DatabaseMetaData is covered in the JDBC DatabaseMetaData
Tutorial. Here is an example of creating a

JDBC DatabaseMetaData object via the

JDBC Connection getMetaData() method:

DatabaseMetaData databaseMetaData = connection.getMetaData();

Statement
The Statement interface represents the static SQL statement. It helps you to create a
general purpose SQL statements using Java.

Creating a statement
You can create an object of this interface using the createStatement() method of
the Connection interface.
Create a statement by invoking the createStatement() method as shown below.

Statement stmt = null;


try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
...
}
Executing the Statement object
Once you have created the statement object you can execute it using one of the
execute methods namely, execute(), executeUpdate() and, executeQuery().
 execute(): This method is used to execute SQL DDL statements, it returns a
boolean value specifying whether the ResultSet object can be retrieved.
 executeUpdate(): This method is used to execute statements such as insert,
update, delete. It returns an integer value representing the number of rows
affected.
 executeQuery(): This method is used to execute statements that returns
tabular data (example SELECT statement). It returns an object of the class
ResultSet.

Prepared Statement

The PreparedStatement interface extends the Statement interface. It represents a


precompiled SQL statement which can be executed multiple times. This accepts
parameterized SQL quires and you can pass 0 or more parameters to this query.

Initially, this statement uses place holders “?” instead of parameters, later on, you
can pass arguments to these dynamically using the setXXX() methods of
the PreparedStatement interface.

Creating a PreparedStatement

You can create an object of the PreparedStatement (interface) using


the prepareStatement() method of the Connection interface. This method accepts a
query (parameterized) and returns a PreparedStatement object.

When you invoke this method the Connection object sends the given query to the
database to compile and save it. If the query got compiled successfully then only it
returns the object.

To compile a query, the database doesn’t require any values so, you can use (zero or
more) placeholders (Question marks “?”) in the place of values in the query.

For example, if you have a table named Employee in the database created using the
following query:

CREATE TABLE Employee(Name VARCHAR(255), Salary INT NOT NULL, Location

VARCHAR(255));

Then, you can use a PreparedStatement to insert values into it as shown


below.

//Creating a Prepared Statement

String query="INSERT INTO Employee(Name, Salary, Location)VALUES(?, ?, ?)";

Statement pstmt = con.prepareStatement(query);

Setting values to the place holders


The PreparedStatement interface provides several setter methods such
as setInt(), setFloat(), setArray(), setDate(), setDouble() etc.. to set
values to the place holders of the prepared statement.
These methods accepts two arguments one is an integer value
representing the placement index of the place holder and the other is an
int or, String or, float etc… representing the value you need to insert at
that particular position.
Once you have created a prepared statement object (with place holders)
you can set values to the place holders of the prepared statement using
the setter methods as shown below:

pstmt.setString(1, "Amit");

pstmt.setInt(2, 3000);

pstmt.setString(3, "Hyderabad");

Executing the Prepared Statement


Once you have created the PreparedStatement object you can execute it using one
of the execute() methods of the PreparedStatement interface namely, execute(),
executeUpdate() and, executeQuery().
 execute(): This method executes normal static SQL statements in the current
prepared statement object and returns a boolean value.

 executeQuery(): This method executes the current prepared statement and


returns a ResultSet object.

 executeUpdate(): This method executes SQL DML statements such as insert


update or delete in the current Prepared statement. It returns an integer value
representing the number of rows affected.

import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");

stmt.setInt(1,101);//1 specifies the first parameter in the query


stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);}

}
}

CallableStatement

The CallableStatement interface provides methods to execute stored procedures.


Since the JDBC API provides a stored procedure SQL escape syntax, you can call
stored procedures of all RDBMS in a single standard way.

Creating a CallableStatement
You can create an object of the CallableStatement (interface) using
the prepareCall() method of the Connection interface.

This method accepts a string variable representing a query to call the stored
procedure and returns a CallableStatement object.

A CallableStatement can have input parameters or, output parameters or, both. To
pass input parameters to the procedure call you can use place holder and set values
to these using the setter methods (setInt(), setString(), setFloat()) provided by the
CallableStatement interface.

Suppose, you have a procedure name myProcedure in the database you can prepare
a callable statement as:

Preparing a CallableStatement

CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");

Setting values to the input parameters


You can set values to the input parameters of the procedure call using the setter
methods.

These accept two arguments one is an integer value representing the placement
index of the input parameter and the other is an int or, String or, float etc…
representing the value you need to pass an input parameter to the procedure.

Note: Instead of index you can also pass the name of the parameter in String format.

cstmt.setString(1, "Raghav");

cstmt.setInt(2, 3000);

cstmt.setString(3, "Hyderabad");

Executing the Callable Statement


Once you have created the CallableStatement object you can execute it using one of
the execute() method.

cstmt.execute();

RESULT SETS :-

The SQL statements that read data from a database query, return the data in a
result set. The SELECT statement is the standard way to select rows from a
database and view them in a result set. The java.sql.ResultSet interface represents
the result set of a database query.

A ResultSet object maintains a cursor that points to the current row in the result set.
The term "result set" refers to the row and column data contained in a ResultSet
object.

The methods of the ResultSet interface can be broken down into three categories −

 Navigational methods − Used to move the cursor around.

 Get methods − Used to view the data in the columns of the current row being
pointed by the cursor.

 Update methods − Used to update the data in the columns of the current row.
The updates can then be updated in the underlying database as well.

The cursor is movable based on the properties of the ResultSet. These properties
are designated when the corresponding Statement that generates the ResultSet is
created.

JDBC provides the following connection methods to create statements with desired
ResultSet −

 createStatement(int RSType, int RSConcurrency);

 prepareStatement(String SQL, int RSType, int RSConcurrency);

 prepareCall(String sql, int RSType, int RSConcurrency);

The first argument indicates the type of a ResultSet object and the second
argument is one of two ResultSet constants for specifying whether a result set is
read-only or updatable.

Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you
will automatically get one that is TYPE_FORWARD_ONLY.

Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.

ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward,

and the result set is not sensitive to changes made


by others to the database that occur after the result
set was created.

ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward,

and the result set is sensitive to changes made by


others to the database that occur after the

result set was created.

Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency
type, you will automatically get one that is CONCUR_READ_ONLY.

Concurrency Description

ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default

ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

All our examples written so far can be written as follows, which


initializes a Statement object to create a forward-only, read only
ResultSet object −
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) {
....
}
finally {
....
}

Navigating a Result Set


There are several methods in the ResultSet interface that involve moving the cursor,
including −

.N. Methods & Description

1 public void beforeFirst() throws SQLException

Moves the cursor just before the first row.

2 public void afterLast() throws SQLException


Moves the cursor just after the last row.

3 public boolean first() throws SQLException


Moves the cursor to the first row.

4 public void last() throws SQLException


Moves the cursor to the last row.

5 public boolean absolute(int row) throws SQLException


Moves the cursor to the specified row.

6 public boolean relative(int row) throws SQLException


Moves the cursor the given number of rows forward or backward, from where it
is currently pointing.

7 public boolean previous() throws SQLException


Moves the cursor to the previous row. This method returns false if the previous
row is off the result set.
8 public boolean next() throws SQLException
Moves the cursor to the next row. This method returns false if there are no more
rows in the result set.

9 public int getRow() throws SQLException


Returns the row number that the cursor is pointing to.

10 public void moveToInsertRow() throws SQLException


Moves the cursor to a special row in the result set that can be used to insert a
new row into the database. The current cursor location is remembered.

11 public void moveToCurrentRow() throws SQLException


Moves the cursor back to the current row if the cursor is currently at the insert row;
otherwise, this method does nothing

Viewing a Result Set


The ResultSet interface contains dozens of methods for getting the data of the
current row.
There is a get method for each of the possible data types, and each get method has
two versions −
 One that takes in a column name.
 One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to
use one of the getInt() methods of ResultSet –

S.N. Methods & Description

1 public int getInt(String columnName) throws SQLException

Returns the int in the current row in the column named columnName.

2 public int getInt(int columnIndex) throws SQLException


Returns the int in the current row in the specified column index. The column index starts a
1, meaning the first column of a row is 1, the second column of a row is 2, and so on.
There are update methods for the eight primitive data types, as well as String,
Object, URL, and the SQL data types in the java.sql package.

Updating a row in the result set changes the columns of the current row in the
ResultSet object, but not in the underlying database. To update your changes to the
row in the database, you need to invoke one of the following methods.

S.N. Methods & Description

1 public void updateRow()

Updates the current row by updating the corresponding row in the database.

2 public void deleteRow()


Deletes the current row from the database

3 public void refreshRow()


Refreshes the data in the result set to reflect any recent changes in the database.

4 public void cancelRowUpdates()


Cancels any updates made on the current row.

5 public void insertRow()


Inserts a row into the database. This method can only be invoked when the cursor is
pointing to the insert row.

Example of Scrollable ResultSet:-

import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:5
21:xe","system","oracle");
Statement stmt=con.creteStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Re
sultSet.CONCUR_UPDATABE);
ResultSet rs=stmt.execteQuery("select * from emp765");

/getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close(); } }
NETWORK PROGRAMMING AND RMI:-

WHY NETWORKED JAVA

Network programming refers to writing programs that execute across


multiple devices (computers), in which the devices are connected to
each other via a network. Java encapsulates classes and interfaces to
allow low-level communication details. In this article, I will give you a
brief insight into the fundamentals of Java Networking.
Java Networking is a notion of connecting two or more computing devices together
to share the resources. Java program communicates over the network at
the application layer. java.net package is useful for all the Java networking classes
and interfaces.

The java.net package provides support for two protocols. They are as follows:

 TCP − Transmission Control Protocol allows reliable communication between


two applications. TCP is typically used over the Internet Protocol, which is
referred to as TCP/IP.
 UDP − User Datagram Protocol is a connection-less protocol that allows
packets of data to be transmitted between applications.

Networking Terminologies
The widely used Java networking terminologies used are as follows:

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1. IP Address
The IP address is a unique number assigned to a node of a network e.g.
192.168.0.1. It is composed of octets that range from 0 to 255.

2. Protocol
A protocol is a set of rules followed for communication. For exampl

 TCP
 FTP
 Telnet
 SMTP
 POP etc.

3. Port Number
The port number uniquely identifies different applications. It acts as a
communication endpoint between applications. To communicate between
two applications, the port number is used along with an IP Address.

4. MAC Address

A MAC address is basically a hardware identification number which uniquely


identifies each device on a network. For example, an Ethernet card may have a MAC
address of 00:0d:83:b1:c0:8e.

5. Connection-oriented and connection-less protocol

In the connection-oriented protocol, acknowledgment is sent by the receiver. So it is


reliable but slow. The example of a connection-oriented protocol is TCP. But, in the
connection-less protocol, acknowledgment is not sent by the receiver. So it is not
reliable but fast. The example of a connection-less protocol is UDP.

6. Socket

A socket in Java is one endpoint of a two-way communication link between two


programs running on the network. A socket is bound to a port number so that the
TCP layer can identify the application that data is destined to be sent to.

Inet Address
Inet Address is used to encapsulate both the numerical IP address and the domain
name for that address. It can handle both IPv4 and Ipv6 addresses. Below figure
depicts the subclasses of Inet Address class.

To create an Inet Address object, you have to use Factory methods. Basically, there
are three commonly used Inet Address factory methods. They are as follows:

1. static InetAddress getLocalHost() throws UnknownHostException


2. static InetAddress getByName (String hostname)
throws UnknownHostException
3. static InetAddress[ ] getAllByName (String hostname)
throws UnknownHostException

 URLs AND URIs


4. }

What is URI?
A URI or Uniform Resource Identifier is a string identifier that refers to a resource on
the internet. It is a string of characters that is used to identify any resource on
the internet using location, name, or both.

A URI has two subsets; URL (Uniform Resource Locator) and URN (Uniform
Resource Number). If it contains only a name, it means it is not a URL. Instead of
directly URI, we mostly see the URL and URN in the real world.
A URI contains scheme, authority, path, query, and a fragment. Some most common URI
schemes are HTTP, HTTPs, ftp, Idap, telnet, etc.

Syntax of URI
The Syntax of URI is given below:

1. scheme:[//authority]path[?query][#fragment]

o Scheme: The first component of URI is scheme that contain a sequence of


characters that can be any combination of letter, digit, plus sign, or hyphen (_),
which is followed by a colon (:). The popular schemes are http, file, ftp, data,
and irc. The schemes should be registered with IANA.
o Authority: The authority component is optional and preceded by two slashes
(//). It contains three sub-components:
o userinfo: It may contain a username and an optional password
separated by a colon. The sub-component is followed by the @ symbol.
o host: It contains either a registered name or an IP address. The IP
address must be enclosed within [] brackets.
o Port: Optional
o Path: It consists of a sequence of path segments separated by a slash(/). The
URI always specifies it; however, the specified path may be empty or of 0
lengths.
o Query: It is an optional component, which is preceded by a question mark(?).
It contains a query string of non-hierarchical data.
o Fragment: It is also an optional component, preceded by a hash(#) symbol. It
consists of a fragment identifier that provides direction to a secondary
resource.

Some examples of URI


1. mailto:hey.Doe@example.com
2. news:comp.infosystems.www.servers.unix
3. urn:oasis:names:specification:docbook:dtd:xml:4.1.2

What is the URL?


1. A URL or Uniform Resource Locator is used to find the location of the resource

on the web. It is a reference for a resource and a way to access that resource. A

URL always shows a unique resource, and it can be an HTML page, a CSS

document, an image, etc.

2. A URL uses a protocol for accessing the resource, which can be HTTP, HTTPS,
FTP, etc.
3. It is mainly referred to as the address of the website, which a user can find in
their address bars. An example of an URL is given below:

Syntax of URL
Each HTTP URL follow the syntax of its generic URI. Hence the syntax of the URL is
also similar to the syntax of URI. It is given below:

1. scheme:[//authority]path[?query][#fragment]

The above URL is made up of the following components:


o Scheme: The URL's first component is a scheme, which represents a protocol
that a browser must need to use to request the resource. The commonly used
protocols for websites are HTTP or HTTPS.
o Authority: The authority includes two sub-components, domain name and
Port, separated by a colon. The domain name can be anything, the registered
name of the resource like javatpoint.com, and port is the technical gate to
access the resource on a webserver. The port number 80 is used for
HTTP and 443 is used for HTTPS.
o Path: The path indicates the complete path to the resource on the webserver.
It can be like /software/htp/index.html.
o Query String: It is the string that contains the name and value pair. If it is used
in a URL, it follows the path component and gives the information. Such
as "?key1=value1&key2=value2".
o Fragment: It is also an optional component, preceded by a hash(#) symbol. It
consists of a fragment identifier that provides direction to a secondary
resource.

Key differences between URI and URL


o URI contains both URL and URN to identify the name and location or both of a
resource; in contrast, URL is a subset of URI and only identifies the location of
the resource.
o The example of URI is urn:isbn:0-476-27557-4, whereas the example of URL,
is https://google.com.
o The URI can be used to find resources in HTML, XML, and other files also,
whereas, URL can only be used to locate a web page.

URI URL

URI is an acronym for Uniform Resource URL is an acronym for Uniform


Identifier. Resource Locator.

URI contains two subsets, URN, which URL is the subset of URI, which
tell the name, tells the only location of the
and URL, which tells the location. resource.

All URIs cannot be URLs, as they can tell either All URLs are URIs, as every URL
name or can only contain the location.
location.
A URI aims to identify a resource and differentiate A URL aims to find the location
it from other resources by using the name of or address of a resource on the
the resource or location of the resource. web.

An example of a URI can be ISBN 0-486-35557-4. An example of an URL is


https://www.javatpoint.com.

It is commonly used in XML and tag library files It is mainly used to search the
such as JSTL and XSTL to identify the resources webpages on the internet.
and binaries.

The URI scheme can be protocol, designation, The scheme of URL is usually
specification, a protocol such as HTTP, HTTPS,
or anything. FTP, etc.

REMOTE METHOD INVOCATION(RMI):-

RMI stands for Remote Method Invocation. It is a mechanism that allows an object
residing in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication
between Java programs. It is provided in the package java.rmi.

Architecture of an RMI Application


In an RMI application, we write two programs, a server program (resides on the
server) and a client program (resides on the client).
 Inside the server program, a remote object is created and reference of that
object is made available for the client (using the registry).
 The client program requests the remote objects on the server and tries to
invoke its methods.
The following diagram shows the architecture of an RMI application.
The components of this architecture;-

 Transport Layer − This layer connects the client and the server. It manages
the existing connection and also sets up new connections.
 Stub − A stub is a representation (proxy) of the remote object at client. It
resides in the client system; it acts as a gateway for the client program.
 Skeleton − This is the object which resides on the server
side. stub communicates with this skeleton to pass request to the remote
object.
 RRL(Remote Reference Layer) − It is the layer which manages the references
made by the client to the remote object.

Working of an RMI Application


The following points summarize how an RMI application works −
 When the client makes a call to the remote object, it is received by the stub
which eventually passes this request to the RRL.
 When the client-side RRL receives the request, it invokes a method
called invoke() of the object remoteRef. It passes the request to the RRL on
the server side.
 The RRL on the server side passes the request to the Skeleton (proxy on the
server) which finally invokes the required object on the server.
 The result is passed all the way back to the client.

Marshalling and Unmarshalling


 Whenever a client invokes a method that accepts parameters on a remote
object, the parameters are bundled into a message before being sent over the
network. These parameters may be of primitive type or objects. In case of
primitive type, the parameters are put together and a header is attached to it.
In case the parameters are objects, then they are serialized. This process is
known as marshalling.

 At the server side, the packed parameters are unbundled and then the
required method is invoked. This process is known as unmarshalling.

RMI Registry
 RMI registry is a namespace on which all server objects are placed. Each time
the server creates an object, it registers this object with the RMIregistry
(using bind() or reBind() methods). These are registered using a unique name
known as bind name.
 To invoke a remote object, the client needs a reference of that object. At that
time, the client fetches the object from the registry using its bind name
(using lookup() method).
Goals of RMI
Following are the goals of RMI −

 To minimize the complexity of the application.

 To preserve type safety.

 Distributed garbage collection.

 Minimize the difference between working with local and remote objects

To write an RMI Java application, you would have to follow the steps given below −

 Define the remote interface

 Develop the implementation class (remote object)

 Develop the server program

 Develop the client program

 Compile the application

 Execute the application

Defining the Remote Interface


A remote interface provides the description of all the methods of a particular
remote object. The client communicates with this remote interface.
To create a remote interface −
 Create an interface that extends the predefined interface Remote which
belongs to the package.
 Declare all the business methods that can be invoked by the client in this
interface.
 Since there is a chance of network issues during remote calls, an exception
named RemoteException may occur; throw it.
Following is an example of a remote interface. Here we have defined an interface
with the name Hello and it has a method called printMsg().
import java.rmi.Remote;
import java.rmi.RemoteException;

// Creating Remote interface for our application


public interface Hello extends Remote {
void printMsg() throws RemoteException;
}

Developing the Implementation Class (Remote Object)


We need to implement the remote interface created in the earlier step. (We can
write an implementation class separately or we can directly make the server
program implement this interface.)
To develop an implementation class −

 Implement the interface created in the previous step.

 Provide implementation to all the abstract methods of the remote interface.


Following is an implementation class. Here, we have created a class
named ImplExample and implemented the interface Hello created in the previous
step and provided body for this method which prints a message.

Implementing the remote interface


public class ImplExample implements Hello {

// Implementing the interface method


public void printMsg() {
System.out.println("This is an example RMI program");
}
}

Developing the Server Program


An RMI server program should implement the remote interface or extend the
implementation class. Here, we should create a remote object and bind it to
the RMIregistry.
To develop a server program −
 Create a client class from where you want invoke the remote object.
 Create a remote object by instantiating the implementation class as shown
below.
 Export the remote object using the method exportObject() of the class
named UnicastRemoteObject which belongs to the package java.rmi.server.
 Get the RMI registry using the getRegistry() method of
the LocateRegistry class which belongs to the package java.rmi.registry.
 Bind the remote object created to the registry using the bind() method of the
class named Registry. To this method, pass a string representing the bind
name and the object exported, as parameters.
Following is an example of an RMI server program.
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server extends ImplExample {


public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();

// Exporting the object of implementation class


// (here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

// Binding the remote object (stub) in the registry


Registry registry = LocateRegistry.getRegistry();

registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}

Developing the Client Program


Write a client program in it, fetch the remote object and invoke the required method
using this object.
To develop a client program −
 Create a client class from where your intended to invoke the remote object.
 Get the RMI registry using the getRegistry() method of
the LocateRegistry class which belongs to the package java.rmi.registry.
 Fetch the object from the registry using the method lookup() of the
class Registry which belongs to the package java.rmi.registry.
To this method, you need to pass a string value representing the bind name
as a parameter. This will return you the remote object.
 The lookup() returns an object of type remote, down cast it to the type Hello.
 Finally invoke the required method using the obtained remote object.
Following is an example of an RMI client program.

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {


private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);

// Looking up the registry for the remote object


Hello stub = (Hello) registry.lookup("Hello");

// Calling the remote method using the obtained object


stub.printMsg();

// System.out.println("Remote method invoked");


} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}

Compiling the Application


To compile the application −

 Compile the Remote interface.

 Compile the implementation class.

 Compile the server program.

 Compile the client program.


Or,
Open the folder where you have stored all the programs and compile all the Java
files as shown below.
Javac *.java
Executing the Application

Step 1 − Start the rmi registry using the following command.


start rmiregistry

This will start an rmi registry on a separate window as shown below.


Step 2 − Run the server class file as shown below.
Java Server

Step 3 − Run the client class file as shown below.


java Client

Verification − As soon you start the client, you would see the following output in the server.
UDP DATAGRAMS AND SOCKETS:-

Datagram Sockets are Java’s mechanism for network communication via


UDP instead of TCP. Java provides Datagram Socket to communicate over
UDP instead of TCP. It is also built on top of IP. Datagram Sockets can be
used to both send and receive packets over the Internet.
One of the examples where UDP is preferred over TCP is the live coverage of
TV channels. In this aspect, we want to transmit as many frames to live
audience as possible not worrying about the loss of one or two frames. TCP
being a reliable protocol add its own overhead while transmission.
Another example where UDP is preferred is online multiplayer gaming. In
games like counter-strike or call of duty, it is not necessary to relay all the
information but the most important ones. It should also be noted that most
of the applications in real life uses careful blend of both UDP and TCP;
transmitting the critical data over TCP and rest of the data via UDP.
This article is a simple implementation of one-sided client-server program
wherein the client sends messages to server and server just prints it until the
client sends “bye”.
Java Datagram programming model Steps

1.Creation of DatagramSocket:- First, a datagramSocket object is created to


carry the packet to the destination and to receive it whenever the server
sends any data. To create a datagramSocket following constructors can be
used:
protected DatagramSocket DatagramSocket():
Syntax: public DatagramSocket()
throws SocketException
Creates a datagramSocket and binds it to any available
port on local machine. If this constructor is used, the
OS would assign any port to this socket.
protected DatagramSocket DatagramSocket(int port):
Syntax: public DatagramSocket(int port)
throws SocketException
Parameters:
port - port to which socket is to be bound
Throws:
SocketException - If the socket cannot be bound to the
specific local port. Creates a DatagramSocket and binds
to the specified port on the local machine.

2.Creation of DatagramPacket: In this step, the packet for sending/receiving


data via a datagramSocket is created.

Constructor to send data: DatagramPacket(byte buf[], int length,


InetAddress inetaddress, int port):-
Syntax: public DatagramPacket(byte[] buf,
int offset,
int length,
SocketAddress address)
Parameters:
buf - the packet data.
offset - the packet data offset.
length - the packet data length.
address - the destination socket address.
Constructs a DatagramPacket for sending data at specified address and
specified port.

 Constructor to receive the data:


DatagramPacket(byte buf[], int length):-
Syntax: public DatagramPacket(byte buf[],
int length)
Parameters:
buf - the packet data.
length - the packet data length.
Constructs a DatagramPacket for receiving the data of length length
in the byte array buf.
3.Invoke a send() or receive() call on socket object
Syntax: void send(DatagramPacket packet)
throws SocketException
Parameters:
packet - Datagrampacket to send.
Throws:
SocketException - If there is an error in binding.
IllegalArgumentException - if address is not supported by the
socket.
Syntax: void receive(DatagramPacket packet)
throws SocketException
Parameters:
packet - Datagrampacket to receive from this socket.
Throws:
SocketException - If there is an error in binding.
IllegalArgumentException - if address is not supported by the
socke

Client Side Implementation

Java program to illustrate Client side

// Implementation using DatagramSocket

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.util.Scanner;

public class udpBaseClient_2

public static void main(String args[]) throws IOException

Scanner sc = new Scanner(System.in);

// Step 1:Create the socket object for

// carrying the data.

DatagramSocket ds = new DatagramSocket();


InetAddress ip = InetAddress.getLocalHost();

byte buf[] = null;

// loop while user not enters "bye"

while (true)

String inp = sc.nextLine();

// convert the String input into the byte array.

buf = inp.getBytes();

// Step 2 : Create the datagramPacket for sending

// the data.

DatagramPacket DpSend =

new DatagramPacket(buf, buf.length, ip, 1234);

// Step 3 : invoke the send call to actually send

// the data.

ds.send(DpSend);

// break the loop if user enters "bye"

if (inp.equals("bye"))

break;

} }

Output:
Hello
I am Client.
...
Bye
Server side Implementation

Java program to illustrate Server side


// Implementation using DatagramSocket
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class udpBaseServer_2


{
public static void main(String[] args) throws IOException
{
// Step 1 : Create a socket to listen at port 1234
DatagramSocket ds = new DatagramSocket(1234);
byte[] receive = new byte[65535];

DatagramPacket DpReceive = null;


while (true)
{

// Step 2 : create a DatgramPacket to receive the data.


DpReceive = new DatagramPacket(receive, receive.length);

// Step 3 : revieve the data in byte buffer.


ds.receive(DpReceive);

System.out.println("Client:-" + data(receive));

// Exit the server if the client sends "bye"


if (data(receive).toString().equals("bye"))
{
System.out.println("Client sent bye.....EXITING");
break;
}

// Clear the buffer after every message.


receive = new byte[65535];
}
}

// A utility method to convert the byte array


// data into a string representation.
public static StringBuilder data(byte[] a)
{
if (a == null)
return null;
StringBuilder ret = new StringBuilder();
int i = 0;
while (a[i] != 0)
{
ret.append((char) a[i]);
i++;
}
return ret;
}
}
In a nutshell, we can summarize the steps of sending and receiving data over
UDP as follows:-
1. For sending a packet via UDP, we should know 4 things, the
message to send, its length, ipaddress of destination, port at
which destination is listening.
2. Once we know all these things, we can create the socket object for
carrying the packets and packets which actually possess the data.
3. Invoke send()/receive() call for actually sending/receieving packets.
4. Extract the data from the received packet.
Output:
Client:- Hello
Client:- I am client.
...
Client:- bye
Client sent bye.....EXITING
WEB TECHNOLOGIES

Unit-VI

INTRODUCTION TO JSP

Enrichment in server side programming is now a need of web application. We


prefer component based, multithreaded client server application. A lots of server
side technologies such as JSP, servlets, ASP, PHP are used.

Java Server Pages is a kind of scripting language in which we can embed Java
code along with html elements.

Advantages of JSP:

 Jsp is useful for server sideprogramming.


 Jsp can be used along with servlets .Hence business logic for any
application can be developed usingJsp.
 Dynamic contents can be handled using Jsp because jsp allows
scripting and element basedprogramming.
 Jsp allows creating and using our own custom tag libraries. Hence
any application specific requirements can be satisfied using custom
taglibraries.
 Jsp is a specification and not a product. Hence any variety of
applications can be developed.
 Jsp is essential component of J2ee.Hence using Jsp is possible to
develop simple as well as complexapplications.

Problem with Servlet:

In only one class, the servlet alone has to do various tasks such as:

 Acceptance ofrequest
 Processing ofrequest
 Handling of businesslogic
 Generation ofresponse

Hence there are some problems that are associated with servlets:

 For developing a servlet application, we need knowledge of Java as well as htmlcode.


 While developing any web based application, look and feel of web based
application needs to be changed then entire code needs to be changed
andrecompiled.
 There are some web page development tools available using which the
developer can develop web based applications. But servlets don not support
such tools. Even if such tools are used, we need to change embedded html
code manually, which is time consuming and errorprone.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
These problems associated with servlets are due to one and only one reason that is
servlet has to handle all tasks of request processing.JSP is a technology that came
up to overcome these problems.

Jsp is a technology in which request processing, business logic and


presentations are separated out.

Request processing Servlet withrequest


handling class
Processing

Presentation
JSP with some GUI
PureServlet Business

logic

Anatomy of JSP

ANATOMY OF JSP PAGE: Core Java code for


implementation of logic

 JSP page is a simple web page which contains the JSP elements and templatetext.
 The template text can be scripting code such as Html, Xml or a simple plaintext.
 Various Jsp elements can be action tags, custom tags, JSTL library
elements. These JSP elements are responsible for generating
dynamiccontents.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
JSP CODE:

Anatomy of JSP

<%@ page import="java.util.Date;" %> JSP Element


<html>
<head>
<title>
first jsp program</title> Template Text
</head>
<body>
<%
out.println("Hello BTech CSE Students");
out.println("<br><br>"); JSP Element
out.println("Welcome to Jsp Programming");
out.println(new Date().toString());
%>
<center>Have a nice Day</center>
<br><br> Tempalte Text
</body>
</html>

When JSP request gets processed template text and JSP elements are merged
together and sent to the browser as response.

JSP Processing:

JSP pages can be processed using JSP Container only. Following are the steps
that need to be followed while processing the request for JSP page:

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
 Client makes a request for required JSP page to server. The server must
have JSP container so that JSP request can be processed. For instance:
let the client makes request for xyz.jsppage.
 On receiving this request the JSP container searches and then reads the
desiredJSP page. Then this JSP page is converted to correspondingservlet.
 Basically any JSP page is a combination of template text and JSP

elements. Every template text is converted to corresponding

printlnstatement.

Every JSP element is converted into corresponding Java code.

This phase is called Translation phase, output of it is a servlet.for instance:xyz.jsp


is converted toxyzservlet.java

<html>
Th out.println(“<html>”);

<head> out.println(“<head>”);
 This servlet is compiled to generate servlet class file. Using this class
response is generated. This phase is called request processingphase.
 The Jsp container thus executes servlet classfile.
 A requested page is then returned to client asresponse.

Server

Jsp container Xyz.jsp

Requestxyz.jsp read
s
Translation phase
client

generates Xyzservlet.java

Request Processing Phase

Xyzservlet.class

Response is sent to client

Executes

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
JSP Application design with MVC:

The design model of JSP application is called MVC model.MVC stands for Model-
View- Controller. The basic idea in MVC design model is to separate out design
logic into 3 parts- modelling,viewing,controlling.

Any server application is classified in 3 parts such as business


logic,presentation and request processing.

The business logic means coding logic applied for manipulation of application

data. Presentation refers to code written for look and feels of web page like

background color,
font size etc.

Request processing is combination of business logic and

presentation. According to MVC model,

Model corresponds to businesslogic


View corresponds topresentation
Controller corresponds to requestprocessing

Advantages of using MVC design model:

The use of MVC architecture allows developer to keep the separation between
business logic and request processing. Due to this separation it becomes easy to
make changes in presentation without disturbing business logic. The changes in
presentation are often required for accommodating new presentation interfaces.

Setting up JSP environment:

For executing any JSP we require:

 Java DevelopmentKit
 Any web server such as ApacheTomcat

Installing JDK:

JDK can be downloaded from oracle website on to our machine. After


downloading we can install jdk as:

Step-1:
K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology
E-mail:toyellaswamy@gmail.com
Double click on file download option. And you will get license agreement window.
Click on “I Accept” and then “Next”.

Step-2:

Then the setup screen will appear as follows:

Here we can change default downloading directory to required location. Click on “Next”

Step-3:

After installing JDK further Java Runtime Environment will be downloaded.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
After this installation will be completed and following screen will appear.

Step-4:

Now we have to set up environment variables after java is installed in

our PC. Go to

Control panel->System Properties

->Advanced-> Environment variables

Create a new variable path with its value as location where bin directory of JDK is located.

Now JDK is successfully installed.

INSTALLATION OF TOMCAT:

We can download tomcat from

tomcat.apache.org Installation process is as:

Step-1:

When we download tomcat and click on installer following screen appears. Click on “Next”

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
Step-2:

Accept terms by clicking “I Agree”

Step-3:

We can choose components to be installed and click on “Next”.

Step-4:

Now installation directory can be chosen. We can change default path by


clicking on “Browse” and selecting location.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
Step-5:

Now by clicking on “Next” we get configuration window. Here we can set


connector port. Default port is 8080 but we can set other values also excluding
first 1024 values.

Step-6:

We can also set username and password for administrator login. Then click “Next” button.

Then installation process will start

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
Click on Finish and installation procedure gets

completed. Step-7:

Setting up JAVA_HOME variable:

Go to Control panel-> System-> Advanced tab->

Environment Variables. Create a new variable “JAVA_HOME” with value as the


location where jdk is installed.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
Now click on startup.bat batch file and start Tomcat server.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
UNIT-VI

Java Server pages

JSP technology is used to create web application just like Servlet technology. It can
be thought of as an extension to servlet because it provides more functionality than
servlet such as expression language, jstl etc.

A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to
maintain than servlet because we can separate designing and development. It
provides some additional features such as Expression Language, Custom Tag etc.

Advantage of JSP over Servlet

There are many advantages of JSP over servlet. They are as follows:

1) Extension toServlet

JSP technology is the extension to servlet technology. We can use all the features of
servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.

2) Easy tomaintain

JSP can be easily managed because we can easily separate our business logic with
presentation logic. In servlet technology, we mix our business logic with the
presentation logic.

3) Fast Development: No need to recompile andredeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The
servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.

4) Less code thanServlet

In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that
reduces the code. Moreover, we can use EL, implicit objectsetc.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
Life cycle of a JSP Page

The JSP pages follows these phases:

 Translation of JSPPage
 Compilation of JSPPage
 Classloading (class file is loaded by theclassloader)
 Instantiation (Object of the Generated Servlet iscreated).
 Initialization ( jspInit() method is invoked by thecontainer).
 Reqeust processing ( _jspService() method is invoked by thecontainer).
 Destroy ( jspDestroy() method is invoked by thecontainer).

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
ANATOMY OF JSP PAGE:

 JSP page is a simple web page which contains the JSP elements and templatetext.
 The template text can be scripting code such as Html, Xml or a simple plaintext.
 Various Jsp elements can be action tags, custom tags, JSTL library elements.
These JSP elements are responsible for generating dynamiccontents.

Anatomy of JSP

JSP Element
<%@ page import="java.util.Date;" %>
<html>
<head>
<title> Template Text
first jsp program</title>
</head>
<body>
<%
out.println("Hello BTech CSE Students");
JSP Element
out.println("<br><br>");
out.println("Welcome to Jsp Programming");
out.println(new Date().toString());
%>
<center>Have a nice Day</center>
<br><br> TempalteText
</body>
</html>

When JSP request gets processed template text and JSP elements are merged
together and sent to the browser asresponse.

JSP Processing:

JSP pages can be processed using JSP Container only. Following are the steps
that need to be followed while processing the request for JSPpage:

 Client makes a request for required JSP page to server. The server must have
JSP container so that JSP request can be processed. For instance: let the
client makes request for hello.jsppage.
 On receiving this request the JSP container searches and then reads the
desired JSP page. Then this JSP page is converted to correspondingservlet.
 Basically any JSP page is a combination of template text and JSP

elements. Every template text is converted to corresponding

printlnstatement.

Every JSP element is converted into corresponding Java code.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
This phase is called Translation phase, output of it is a servlet.for instance:hello.jsp
is converted to hello_jsp.java

<html>
Th out.println(“<html>”);

<head> out.println(“<head>”);

 This servlet is compiled to generate servlet class file. Using this class
response is generated. This phase is called request processingphase.
 The Jsp container thus executes servlet classfile.
 A requested page is then returned to client asresponse.

Model-View-Controller Architecture:

Model:is used for Buisness Logic

Example:Javabean,EJB

View:is used for PresentationLogic

Example:HTML,JSP

Controller: is used for RequestProcessing

Example:Servlet

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
JSP Access Models
The early JSP specifications advocated two philosophical approaches, popularly
known as Model 1 and Model 2 architectures, for applying JSP technology. These
approaches differ essentially in the location at which the bulk of the request
processing was performed, and offer a useful paradigm for building applications
using JSPtechnology.
Consider the Model 1 architecture, shown below:

In the Model 1 architecture, the incoming request from a web browser is sent directly
to the JSP page, which is responsible for processing it and replying back to the client.
There is still separation of presentation from content, because all data access is
performed using beans.
Although the Model 1 architecture is suitable for simple applications, it may not be
desirable for complex implementations. Indiscriminate usage of this architecture
usually leads to a significant amount of scriptlets or Java code embedded within the
JSP page, especially if there is a significant amount of request processing to be
performed. While this may not seem to be much of a problem for Java developers, it
is certainly an issue if your JSP pages are created and maintained by designers--
which is usually the norm on large projects. Another downside of this architecture is
that each of the JSP pages must be individually responsible for managing
application state and verifying authentication andsecurity.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
The Model 2 architecture, shown above, is a server-side implementation of the
popular Model/View/Controller design pattern. Here, the processing is divided
between presentation and front components. Presentation components are JSP
pages that generate the HTML/XML response that determines the user interface
when rendered by the browser. Front components (also known as controllers) do not
handle any presentation issues, but rather, process all the HTTP requests.

Here, they are responsible for creating any beans or objects used by the presentation
components, as well as deciding, depending on the user's actions, which
presentation component to forward the request to. Front components can be
implemented as either a servlet or JSPpage.

The advantage of this architecture is that there is no processing logic within the
presentation component itself; it is simply responsible for retrieving any objects or
beans that may have been previously created by the controller, and extracting the
dynamic content within for insertion within its static templates.

Consequently, this clean separation of presentation from content leads to a clear


delineation of the roles and responsibilities of the developers and page designers n
the programming team. Another benefit of this approach is that the front
components present a single point of entry into the application, thus making the
management of application state, security, and presentation uniform and easier
tomaintain.

JSP

ELEMENTS/Components 3

Types

1. Directive Elements
2. ActionElements
3. ScriptingElements

Directive Elements:

Directive elements are used to specify information about

the page Syntax:

<%@ directivename attr1="value1" attr2="value2" %>

The directive name and attribute names are case

sensitive. Examples of Some Directives:

page

inlcud

e
K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology
E-mail:toyellaswamy@gmail.com
taglib

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
attribut

e tag

variabl

Page Directive:

This directive can only be used in jsp pages,not tag files.It defines page dependent
attributes,such as scripting language,errorpage,buffer requirements

Syntax:

<%@page[autoFlush="true|false"][buffer="8kb|NNkb|none"][contentType="MIMEType"]
[er
rorPage="pageorContextRelativepath"][extends="classname"][import="packagelist"][i
nfo="i
nfo"][isErrorPage="true|false"][isThreadSafe="true|false"][language="java|language"][
pageE ncoding="encoding"][session="true|false"]%>

Example:

<%@ page language="java" contentType="text/html" %>

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

<%@ page import="java.util.Date" %>

Include Directive:

includes a static file,merging its content with the including page before the
combined results is converted to jsp page implementationclass.

Syntax:

<%@ include file="page or

contextrelativepath"%> Example:

<%@ include file="home.html"%>

Taglib Directive

Declares a tag library,containing custom actions that is used in the

page. Syntax:

<%@ taglib prefix="prefix"

[uri="tagliburi|tagdir="contextrealtivepath"]%> Example:

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
<%@ taglib prefix="ora" uri="orataglib" %>

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
<%@ taglib prefix="mylib" tagdir="/WEB-INF/tags/mylib" %>

Attribute Directive:

This directive can only be used in tag files.It declares the attributes the tag file

supports. Syntax:

<%@attributename="attname"
[description="desc"][required="true|false"][fragment="true|false"
|type="attrDatatype"]%>

Example:

<%@ attribute name="date" type="java.util.Date"%>

Tag Directive:

This directive can only be used in tag

files. Syntax:

<%@ tag [body-content="empty|scriptless|tagdependent"][description="desc"][display


-
name="displayName"][dynamicattributes="attrColVar"][import="packagelist"][languag
e="ja va|language"][page-encoding="encoding"]

Example:

<%@ tag body-content="empty"%>

Variable Directive:

<%@ variable name-given="attrName"|name-from-attribute="attrname" alias="varName"%>

Action Elements:

Action elements are XML element syntax and represent components that are
invoked when a client request the jsp page.

Standard Action Elements:

<jsp:useBean>

<jsp:getProperty>

<jsp:setProperty>

<jsp:include>

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
<jsp:forward>

<jsp:param>

<jsp:plugin>

<jsp:useBean>:

action associtates a javabean with a name in one of the jsp scopes and also makes
it available as a scripting variable

Syntax:

<jsp:useBeanid="beanvariablename"class="classname"[scope="page|request|sessio
n|applicati on]/>

<jsp:getProperty>:

action adds the value of a bean property converted to a string to the response
generated by the page.

Syntax:

<jsp:getProperty name="beanVariableName" property="PropertyName"/>

<jsp:setProperty>

action sets the value of one or more bean

properties. Syntax:

<jsp:setPropertyname="beanVariableName"property="PropertyName"[param="para
meterNa me"|value="value"]/>

Forwarding Requests
With the <jsp:forward> tag, you can redirect the request to any JSP, servlet, or static HTML
page within the same context as the invoking page. This effectively
halts processing of the current page at the point where the redirection occurs,
although all processing up to that point still takes place:
<jsp:forward page="somePage.jsp" />
The invoking page can also pass the target resource bean parameters by placing
them into the request, as shown in the diagram:

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
Including Requests
The <jsp:include> tag can be used to redirect the request to any static or dynamic
resource that is in the same context as the calling JSP page. The calling page can also
pass the target resource bean parameters by placing them into the request, as shown in
the diagram:

For example:
<jsp:include page="shoppingcart.jsp" flush="true"/>

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
Exception Handling
JSP provides a rather elegant mechanism for handling runtime exceptions. Although
you can provide your own exception handling within JSP pages, it may
not be possible to anticipate all situations. By making use of the page
directive's
errorPage attribute, it is possible to forward an uncaught exception to an error handling
JSP page for processing.

For example,
<%@ page isErrorPage="false" errorPage="errorHandler.jsp" %>

informs the JSP engine to forward any uncaught exception to the JSP page
errorHandler.jsp. It is then necessary for errorHandler.jsp to flag itself as a error processing
page using the directive:

<%@ page isErrorPage="true" %>


This allows the Throwable object describing the exception to be accessed within a
scriptlet through the implicit exception object.

K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology


E-mail:toyellaswamy@gmail.com
K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology
E-mail:toyellaswamy@gmail.com

You might also like