Web Technologies Material
Web Technologies Material
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.
Java JDK 8
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.
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).
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:
Abstraction: Abstraction is a process where you show only “relevant” data and
“hide” unnecessary details of an object from the user.
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.
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);
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
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
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.
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).
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).
abstractclassAnimal{
publicabstractvoidanimalSound();
publicvoidsleep(){
System.out.println("Zzz");
From the example above, it is not possible to create an object of the Animal class:
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{
publicabstractvoidanimalSound();
// Regular method
publicvoidsleep(){
System.out.println("Zzz");
}
}
classPigextendsAnimal{
publicvoidanimalSound(){
classMain{
publicstaticvoidmain(String[]args){
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{
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{
classPigimplementsAnimal{
publicvoidanimalSound(){
publicvoidsleep(){
System.out.println("Zzz");
classMain{
publicstaticvoidmain(String[]args){
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
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.
opened or closed
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
HTML code:
<applet code="Test" width=300, height=100>
</applet>
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
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.
Component class
Container
Panel
Window class
Frame
Creating a Frame
import java.awt.*;
Testawt()
8
}
9
package testawt;
import java.awt.*;
import java.awt.event.*;
public Testawt()
}
10
Points to note:
Applets
Applets are small Java applications which can be accessed on an
Internet server, transported over the Internet, and can be installed
11
PROGRAM :-
import java.awt.*;
import java.applet.*;
}
12
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
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.
import java.awt.*;
import java.applet.*;
//initialization
14
//suspend execution
Example of an Applet
import java.applet.*;
import java.awt.*;
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
16
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.
The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
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.
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:
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
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.
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
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);
}
}
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.
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
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.
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;-
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 JPanelSwing() {
super("JPanel Demo Program");
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
pack();
setLocationRelativeTo(null);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JPanelSwing().setVisible(true);
}
});
}
}
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);
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
1.Java BorderLayout
o BorderLayout(): creates a border layout but with no gaps
between the components.
import java.awt.*;
import javax.swing.*;
Border(){
f=new JFrame();
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
import java.awt.*;
import javax.swing.*;
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
import java.awt.*;
import javax.swing.*;
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
import java.awt.*;
import javax.swing.*;
public BoxLayoutExample1 () {
buttons = new Button [5];
PROG:-
<ol>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ol>
Output:
1. Aries
2. Bingo
3. Leo
4. Oracle
<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
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>
<!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.
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 .
Tag Description
<col> It is used with <colgroup> element to specify column properties for each column.
<!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
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
PROG:-
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
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.
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>
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.
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.
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:-
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>
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!
Variables are used to store values (name = "John") or expressions (sum = x + y).
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.
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 two = 3;
document.write("First No: = " + one + "<br />Second No: = " + two + " <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.
<html>
<head>
<script>
function myFunction() {
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
</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.
EG:-
<html>
<body>
<h2>JavaScript in Body</h2>
<script>
function myFunction() {
</script>
</body>
</html>
O/P:-
JavaScript in Body
A Paragraph.
Try it
Using innerHTML
eg:-
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
O/P:-
11
Using document.write()
For testing purposes, it is convenient to use document.write():
<html>
<body>
</body>
</html>
O/P:-
My First Web Page
My first paragraph.
Try it
Using window.alert()
<html>
<body>
<script>
alert(5 + 6);
</script>
</body></html>
O/P:-
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.
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>
</body></html>
The <img> tag is empty, it contains attributes only, and does not have a closing tag.
<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>
</body></html>
<html>
<head>
<style>
img {
width: 100%;
</style>
</head>
<body>
<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>
<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>
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:
JavaScript Primitives
A primitive value is a value that has no properties or methods.
string
number
boolean
null
undefined
John Doe
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:
Uses of DHTML
Following are the uses of DHTML (Dynamic HTML):
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>
</title>
<script type="text/javascript">
function dateandtime()
alert(Date());
</script>
</head>
<body bgcolor="orange">
<center> <p>
</p> </center>
</font>
</body>
</html>
o/p;-
<html>
<head>
</title>
</head>
<body>
Find Grade
</button>
<p id="demo"></p>
<script type="text/javascript">
function checkGrade() {
p = document.getElementById("percentage").value;
x=parseInt(p);
document.getElementById("demo").innerHTML =
"A1";
document.getElementById("demo").innerHTML =
"A2";
document.getElementById("demo").innerHTML =
"A3";
</script>
</body>
</html>
o/p:-
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:-
Green Blue
XML :-
XML stands for eXtensible Markup Language.
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).
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)>
]>
EG:-
<!DOCTYPE note [
<!ENTITY nbsp " ">
<!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; ©right;</footer>
</note>
An entity has three parts: it starts with an ampersand (&), then comes the entity name,
and it ends with a semicolon (;).
With a DTD, you can verify that the data you receive from the outside world is valid.
XML Schema:-
An XML Schema describes the structure of an XML document, just like a DTD.
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>
With XML Schema, independent groups of people can agree on a standard for
interchanging data.
XML DOM:-
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>
<button type="button"
</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>";
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:-
We can use JDBC API to handle database using Java program and can perform the
following activities:
client API. It is comparatively faster than Type-1 driver but it requires native
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
CONNECTIONS;-
The following 5 steps are the basic steps involve in connecting a
Java application with Database using JDBC.
2. Create a Connection
System.out.println("Hello JavaWorld"); }}
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.
import java.sql. * ;
public class JDBCTutorial {
SQLException,
Class.forName(driverName);
//Obtaining a connection
//Obtaining a statement
con.close();
}}
The above example shows the basic steps to access a database using
Prog:-
importjava.sql.*;
importjava.util.*;
class Main
System.out.println("enter name");
System.out.println("enter class");
Connection con=null;
try
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(url,user,pass);
Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
else
System.out.println("insertion failed");
con.close();
catch(Exception ex)
System.err.println(ex);
} }
o/p:-
JDBC Connection
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.
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:
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.
Connection connection =
DriverManager.getConnection(url, user, password);
The user and password parameters are the user name and password for
your database.
Connection connection =
DriverManager.getConnection(url, properties);
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.
try(Connection connection =
DriverManager.getConnection(url, user, password)) {
connection.setAutoCommit(true);
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);
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);
connection.commit();
} catch (SQLException e) {
connection.rollback();
}
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:
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:
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
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.
Prepared Statement
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
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:
VARCHAR(255));
pstmt.setString(1, "Amit");
pstmt.setInt(2, 3000);
pstmt.setString(3, "Hyderabad");
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");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
CallableStatement
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
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");
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 −
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 −
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.
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
Returns the int in the current row in the column named columnName.
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.
Updates the current row by updating the corresponding row in the database.
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");
con.close(); } }
NETWORK PROGRAMMING AND RMI:-
The java.net package provides support for two protocols. They are as follows:
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
6. Socket
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:
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]
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
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]
URI URL
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.
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.
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.
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.
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 −
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 −
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
Verification − As soon you start the client, you would see the following output in the server.
UDP DATAGRAMS AND SOCKETS:-
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
while (true)
buf = inp.getBytes();
// the data.
DatagramPacket DpSend =
// the data.
ds.send(DpSend);
if (inp.equals("bye"))
break;
} }
Output:
Hello
I am Client.
...
Bye
Server side Implementation
System.out.println("Client:-" + data(receive));
Unit-VI
INTRODUCTION TO JSP
Java Server Pages is a kind of scripting language in which we can embed Java
code along with html elements.
Advantages of JSP:
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:
Presentation
JSP with some GUI
PureServlet Business
logic
Anatomy of JSP
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
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:
printlnstatement.
<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
Requestxyz.jsp read
s
Translation phase
client
generates Xyzservlet.java
Xyzservlet.class
Executes
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.
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.
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.
Java DevelopmentKit
Any web server such as ApacheTomcat
Installing JDK:
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:
Here we can change default downloading directory to required location. Click on “Next”
Step-3:
Step-4:
our PC. Go to
Create a new variable path with its value as location where bin directory of JDK is located.
INSTALLATION OF TOMCAT:
Step-1:
When we download tomcat and click on installer following screen appears. Click on “Next”
Step-3:
Step-4:
Step-6:
We can also set username and password for administrator login. Then click “Next” button.
completed. Step-7:
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.
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.
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.
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.
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).
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
printlnstatement.
<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:
Example:Javabean,EJB
Example:HTML,JSP
Example:Servlet
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.
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.
JSP
ELEMENTS/Components 3
Types
1. Directive Elements
2. ActionElements
3. ScriptingElements
Directive Elements:
page
inlcud
e
K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology
E-mail:toyellaswamy@gmail.com
taglib
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:
Include Directive:
includes a static file,merging its content with the including page before the
combined results is converted to jsp page implementationclass.
Syntax:
contextrelativepath"%> Example:
Taglib Directive
page. Syntax:
[uri="tagliburi|tagdir="contextrealtivepath"]%> Example:
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:
Tag Directive:
files. Syntax:
Example:
Variable Directive:
Action Elements:
Action elements are XML element syntax and represent components that are
invoked when a client request the jsp page.
<jsp:useBean>
<jsp:getProperty>
<jsp:setProperty>
<jsp:include>
<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:setProperty>
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:
For example:
<jsp:include page="shoppingcart.jsp" flush="true"/>
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: