0% found this document useful (0 votes)
7 views207 pages

Java 401

The document provides an overview of JavaFX and Swing, two Java-based frameworks for building graphical user interfaces. It highlights the key features, advantages, and differences between the two frameworks, including architecture, multimedia support, and UI design methods. Additionally, it outlines the steps for writing JavaFX programs and includes examples of various layout panes such as FlowPane, BorderPane, HBox, and VBox.

Uploaded by

1230bicky
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)
7 views207 pages

Java 401

The document provides an overview of JavaFX and Swing, two Java-based frameworks for building graphical user interfaces. It highlights the key features, advantages, and differences between the two frameworks, including architecture, multimedia support, and UI design methods. Additionally, it outlines the steps for writing JavaFX programs and includes examples of various layout panes such as FlowPane, BorderPane, HBox, and VBox.

Uploaded by

1230bicky
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

By: Subash Sir

By: Subash Sir


By: Subash Sir
Introduction, JavaFX vs Swing
Introduction:

JavaFX and Swing are both Java-based frameworks used for building graphical
user interfaces (GUIs) in Java applications. GUI frameworks provide a set of tools
and components for creating windows, buttons, menus, and other graphical
elements that allow users to interact with the application.

Swing:
• Swing is an older GUI toolkit for Java that has been a part of the Java
Standard Edition (SE) since its early versions.
• It is built on top of the Abstract Window Toolkit (AWT) and provides a rich
set of components for building desktop applications.
• Swing follows the Model-View-Controller (MVC) architecture, allowing
developers to separate the application's logic (model) from its presentation
(view).

Some key points about Swing include:

1. Mature and Stable: Swing has been around for a long time and is well-
established. Many Java desktop applications have been built using Swing.

2. Lightweight Components: Swing components are lightweight, meaning they


are not dependent on the underlying operating system's widgets. This allows
for consistent behavior across different platforms.

3. Customization: Swing provides a high degree of customization for


components. Developers can create their own look and feel, and the
pluggable look-and-feel architecture allows for different visual styles.

JavaFX:
• JavaFX is a newer GUI toolkit introduced by Oracle as the successor to
Swing.
• It is part of the JavaFX platform, which is included in Java SE starting from
version 8.
• JavaFX is designed to be more modern and to take advantage of newer
technologies.
• Unlike Swing, JavaFX is built on a scenegraph-based architecture, allowing
for more sophisticated and visually appealing UIs.

Some key points about JavaFX include:

1. Rich Multimedia Support: JavaFX provides built-in support for multimedia


elements like audio and video. It also supports 2D and 3D graphics.

2. FXML for UI Design: JavaFX allows developers to design UIs using


FXML, an XML-based markup language. This separation of UI design and
logic can make the development process more manageable.

3. CSS Styling: JavaFX supports styling using Cascading Style Sheets (CSS),
making it easier to achieve a consistent and visually appealing look across
the application.

4. Integration with Java: JavaFX is designed to work seamlessly with Java. It


can be integrated with existing Java codebases, and developers can leverage
their Java skills when working with JavaFX.

Comparison:

1. Age and Maturity: Swing is older and more mature, having been part of Java
for a longer time. JavaFX, being newer, brings modern features and
improvements.

2. Architecture: Swing follows the MVC architecture, while JavaFX is built on


a scenegraph-based architecture.
3. Look and Feel: Swing provides a native look and feel for each platform,
while JavaFX has a consistent appearance across platforms. JavaFX allows
for more extensive customization through CSS styling.

4. Multimedia Support: JavaFX has better built-in support for multimedia


elements, making it a more suitable choice for applications that require rich
media integration.

5. UI Design: JavaFX offers FXML for UI design, providing a separation


between UI and logic. Swing, on the other hand, relies on Java code for UI
construction.

6. Integration: Both Swing and JavaFX can be integrated with existing Java
codebases, but JavaFX's integration tends to be more seamless due to its
modern design.

Ultimately, the choice between JavaFX and Swing depends on factors such as
project requirements, development preferences, and the need for modern features.
While Swing is still widely used, JavaFX is considered the more modern and
feature-rich option for new Java GUI applications.

Steps of Wring JavaFX Programs


Writing JavaFX programs involves several steps, from setting up your
development environment to implementing the graphical user interface and
handling user interactions. Here are the general steps to write JavaFX programs:

1. Setup Development Environment:

• Install Java Development Kit (JDK): Make sure you have the Java
Development Kit installed on your system. JavaFX is included in JDK 8 and
later versions.
• Set up your Integrated Development Environment (IDE): Popular choices
for JavaFX development include IntelliJ IDEA, Eclipse, and NetBeans.
Ensure that your IDE is configured to use the JDK with JavaFX support.
2. Create a JavaFX Project:
• Open your IDE and create a new JavaFX project. This might involve
specifying project details, such as project name, location, and JDK version.
3. Define the Main Application Class:

• Create a class that extends the Application class. This class will serve as the
entry point for your JavaFX application.
import [Link];
import [Link];

public class MyJavaFXApp extends Application {


public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
// Code for initializing and displaying the main stage
}
}
4. Initialize the Stage (Main Window):

• Inside the start method, initialize the main Stage (the main window of your
application).
@Override
public void start(Stage primaryStage) {
[Link]("My JavaFX App");
// Add additional configuration for the stage
[Link](); // Display the stage
}
5. Create UI Elements (Nodes):

• Use JavaFX nodes (UI elements) to build the graphical user interface.
Common nodes include Button, Label, TextField, and Pane.
// Example: Creating a Button
Button myButton = new Button("Click Me");
6. Organize UI Elements:

• Use layout containers (e.g., VBox, HBox, GridPane) to organize and


position UI elements within the main stage.
// Example: Using VBox to organize UI elements vertically
VBox vbox = new VBox(myButton, new Label("Hello, JavaFX!"));
7. Add Event Handlers:

• Implement event handlers to respond to user interactions. Common events


include button clicks, mouse events, and key presses.
// Example: Adding an event handler to the button
[Link](e -> {
[Link]("Button Clicked!");
});
8. Run the Application:

• In your main class (extending Application), call the launch method to start
the JavaFX application.
public static void main(String[] args) {
launch(args);
}
9. Compile and Execute:

• Compile your JavaFX application and run it. The IDE will typically provide
options to build and run your project.
[Link] and Debugging:

• Test your application thoroughly, handle any exceptions, and use debugging
tools provided by your IDE to troubleshoot issues.
These steps provide a basic outline for creating a simple JavaFX application. As
you become more familiar with JavaFX, you can explore advanced features, such
as CSS styling, FXML for UI design, animation, and integration with databases.
Additionally, refer to the official JavaFX documentation and community resources
for more in-depth information and examples.

Complete program:
package application;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SimpleJavaFXApp1 extends Application {


public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
[Link]("Simple JavaFX App1");

// Create a button
Button clickMeButton = new Button("Click Me");

// Create a label to display a message


Label messageLabel = new Label();

// Set an event handler for the button click


[Link](e -> {
[Link]("Button Clicked!");
});

// Create a layout pane (StackPane in this case) and add the button and label to
it
StackPane root = new StackPane();
[Link]().addAll(clickMeButton, messageLabel);

// Create the scene and set it on the stage


Scene scene = new Scene(root, 300, 200);
[Link](scene);

// Show the stage


[Link]();
}
}
Explanation of the code:

• The SimpleJavaFXApp class extends Application and overrides the start


method.
• Inside the start method, we create a button (clickMeButton) and a label
(messageLabel).
• An event handler is set for the button using the setOnAction method. When
the button is clicked, the label's text is set to "Button Clicked!".
• A StackPane is used as the layout pane to stack the button and label.
• A Scene is created with the layout pane as the root, and the scene is set on
the stage (primaryStage).
• The stage is then displayed using [Link]().
• To run this program, make sure you have Java and JavaFX set up on your
system. Compile and run the program using your preferred Java IDE or
command-line tools. The application window should appear, and clicking
the button should update the label with the specified message.

JavaFX Layouts: FlowPane


FlowPane is one of the layout panes provided by JavaFX for arranging its children
in a flow, similar to how text flows in a paragraph. It allows you to add nodes
(such as buttons, labels, etc.) to the pane, and they will be positioned in rows or
columns based on the available space. When the width of the FlowPane is
exceeded, the next node will be placed in the next row or column.
Here's a simple example of using FlowPane in a JavaFX application:

package application;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SimpleJavaFXApp1 extends Application {


public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
[Link]("Simple JavaFX App1");

// Create a button
Button clickMeButton = new Button("Click Me");

// Create a label to display a message


Label messageLabel = new Label();

// Set an event handler for the button click


[Link](e -> {
[Link]("Button Clicked!");
});

// Create a layout pane (StackPane in this case) and add the button and label to
it
StackPane root = new StackPane();
[Link]().addAll(clickMeButton, messageLabel);
// Create the scene and set it on the stage
Scene scene = new Scene(root, 300, 200);
[Link](scene);

// Show the stage


[Link]();
}
}
In this example:

• FlowPane is used to arrange the buttons.


• [Link](10) and [Link](10) set the horizontal and
vertical gaps between nodes, respectively.
• Buttons are added to the FlowPane using [Link]().addAll(...).
• The Scene is created with the FlowPane as its root, and it is set on the Stage.
• The Stage is then displayed.
• When you run this application, you'll see a window with buttons arranged in
a flow, and if the window is resized, the buttons will adjust their positions
accordingly.

BorderPane
BorderPane is another layout pane in JavaFX that divides the content area into five
regions: top, bottom, left, right, and center. Each region can contain a single node,
and the nodes in these regions are laid out in their respective areas. The center
region takes up the remaining space after the other regions have been assigned
their preferred sizes.

Here's a simple example of using BorderPane in a JavaFX application:


package application;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class BorderPaneExample extends Application {


public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
[Link]("BorderPane Example");

// Create buttons for each region


Button topButton = new Button("Top");
Button bottomButton = new Button("Bottom");
Button leftButton = new Button("Left");
Button rightButton = new Button("Right");
Button centerButton = new Button("Center");

// Create a BorderPane and set buttons in different regions


BorderPane borderPane = new BorderPane();
[Link](topButton);
[Link](bottomButton);
[Link](leftButton);
[Link](rightButton);
[Link](centerButton);

// Create the scene and set it on the stage


Scene scene = new Scene(borderPane, 300, 200);
[Link](scene);

// Show the stage


[Link]();
}
}
In this example:

• BorderPane is used to organize buttons in different regions.


• Buttons are created for each region: top, bottom, left, right, and center.
• [Link](...), [Link](...), and so on, are used to set
the buttons in their respective regions.
• The Scene is created with the BorderPane as its root, and it is set on the
Stage.
• The Stage is then displayed.
• When you run this application, you'll see a window with buttons arranged in
a BorderPane. The buttons in each region will stay in their respective areas,
and the center button will take up the remaining space.

Hbox
• The HBox (Horizontal Box) layout pane in JavaFX arranges its children
in a single horizontal row. It's useful when you want to place nodes
horizontally, side by side.
• Each child node takes up its preferred width, and if there is additional
space, it's distributed among the children.
Here's a simple example of using HBox in a JavaFX application:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class HBoxExample extends Application {


public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
[Link]("HBox Example");
// Create buttons
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");

// Create an HBox and add buttons to it


HBox hbox = new HBox();
[Link]().addAll(button1, button2, button3);

// Set the spacing between nodes


[Link](10);

// Create the scene and set it on the stage


Scene scene = new Scene(hbox, 300, 200);
[Link](scene);

// Show the stage


[Link]();
}
}
In this example:

• HBox is used to arrange buttons horizontally.


• Buttons are created and added to the HBox using
[Link]().addAll(...).
• [Link](10) sets the spacing between nodes to 10 pixels.
• The Scene is created with the HBox as its root, and it is set on the Stage.
• The Stage is then displayed.
• When you run this application, you'll see a window with buttons arranged
horizontally in an HBox. The spacing between the buttons is set to 10 pixels.

VBox
The VBox (Vertical Box) layout pane in JavaFX arranges its children in a single
vertical column. It's useful when you want to place nodes vertically, stacked on top
of each other. Each child node takes up its preferred height, and if there is
additional space, it's distributed among the children.

Here's a simple example of using VBox in a JavaFX application:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class VBoxExample extends Application {


public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
[Link]("VBox Example");

// Create buttons
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");

// Create a VBox and add buttons to it


VBox vbox = new VBox();
[Link]().addAll(button1, button2, button3);

// Set the spacing between nodes


[Link](10);

// Create the scene and set it on the stage


Scene scene = new Scene(vbox, 300, 200);
[Link](scene);

// Show the stage


[Link]();
}
}
In this example:

• VBox is used to arrange buttons vertically.


• Buttons are created and added to the VBox using
[Link]().addAll(...).
• [Link](10) sets the spacing between nodes to 10 pixels.
• The Scene is created with the VBox as its root, and it is set on the Stage.
• The Stage is then displayed.
• When you run this application, you'll see a window with buttons arranged
vertically in a VBox. The spacing between the buttons is set to 10 pixels.

GridPane
GridPane is a layout in JavaFX that allows you to create a grid-based layout
for your user interface. It divides the layout into rows and columns, and you
can place your UI components (nodes) in specific cells of the grid. Here's a
basic overview and example of using GridPane in JavaFX:

Basic Structure of GridPane:


import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class GridPaneExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create a GridPane
GridPane gridPane = new GridPane();

// Add nodes to the GridPane and specify their positions in the grid
Button button1 = new Button("Button 1");
[Link](button1, 0, 0); // (columnIndex, rowIndex)

Button button2 = new Button("Button 2");


[Link](button2, 1, 0);

Button button3 = new Button("Button 3");


[Link](button3, 0, 1);

Button button4 = new Button("Button 4");


[Link](button4, 1, 1);

// Set the horizontal and vertical gap between nodes


[Link](10);
[Link](10);

// Create a scene and set it in the stage


Scene scene = new Scene(gridPane, 300, 200);
[Link](scene);

// Set the stage title and show it


[Link]("GridPane Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}
Explanation:
1. GridPane Creation:

Create an instance of GridPane.


2. Adding Nodes:

3. Create the UI components (in this case, buttons).


Use the add method to place each node in the grid. Specify the column index
and row index.
Setting Gaps:

4. Use setHgap and setVgap to set the horizontal and vertical gaps between
nodes.
Scene and Stage:

5. Create a scene with the GridPane and set it in the stage.


Run the Application:

Launch the application with launch(args).

JavaFX UI Controls: Label


In JavaFX, a Label is a UI control that is used to display a non-editable text
or an image. It is often used to provide a description or information in a
graphical user interface. Here's a basic overview and example of using the
Label control in JavaFX:
Example of Using Label:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class LabelExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create a Label with text
Label label = new Label("Hello, JavaFX!");

// Create a StackPane to hold the Label


StackPane stackPane = new StackPane();
[Link]().add(label);

// Create a Scene and set it in the Stage


Scene scene = new Scene(stackPane, 300, 200);
[Link](scene);

// Set the Stage title and show it


[Link]("Label Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}
Explanation:
1. Label Creation:

Create an instance of the Label class and provide the text you want to
display.
StackPane:

2. Create a StackPane layout to hold the label. You can use other layouts as
well based on your design requirements.
Scene and Stage:

3. Create a Scene with the StackPane and set it in the Stage.


Run the Application:

4. Launch the application with launch(args).


This simple example creates a JavaFX application with a single Label
displaying the text "Hello, JavaFX!" within a StackPane. You can customize
the appearance of the label, such as font size, color, and style, using various
properties and methods provided by the Label class.

Here are some common properties and methods of the Label class:

Properties:

1. text: Gets or sets the text to be displayed in the label.


2. font: Gets or sets the font used for the label text.
3. textFill: Gets or sets the color of the label text.

Methods:

1. setText(String text): Sets the text to be displayed in the label.


2. setFont(Font font): Sets the font used for the label text.
3. setTextFill(Paint value): Sets the color of the label text.

TextField
In JavaFX, a TextField is a UI control that allows users to enter and edit a
single line of text. It is commonly used to accept user input in the form of
text. Here's a basic example of using the TextField control in a JavaFX
application:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class TextFieldExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create a Label and a TextField
Label label = new Label("Enter your name:");
TextField textField = new TextField();

// Create a layout (VBox in this example) to hold the Label and


TextField
VBox vbox = new VBox(10); // 10 is the spacing between children
[Link]().addAll(label, textField);

// Create a Scene and set it in the Stage


Scene scene = new Scene(vbox, 300, 200);
[Link](scene);

// Set the Stage title and show it


[Link]("TextField Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}
In this example:

• A Label is used to instruct the user to enter their name.


• A TextField is provided for the user to enter text.
• Both the Label and TextField are added to a VBox layout, which
stacks them vertically.
You can retrieve the text entered by the user using the getText() method of
the TextField class. For example, you might add an event listener to the
TextField to capture the entered text when the user presses the Enter key:

[Link](e -> {
String--- enteredText = [Link]();
[Link]("Entered Text: " + enteredText);
});
• This is a basic usage of the TextField control. You can customize it
further by setting properties like prompt text, maximum length, and
handling events like focus, key press, etc. The JavaFX documentation
provides a comprehensive list of properties and methods available for
the TextField class: TextField (JavaFX 17).

Button
In JavaFX, a Button is a UI control that allows users to trigger an
action when clicked. It's a fundamental component for user interaction
in graphical user interfaces. Here's a basic example of using the
Button control in a JavaFX application:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class ButtonExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create a Button with a label
Button button = new Button("Click Me!");

// Define an action to be performed when the button is clicked


[Link](e -> [Link]("Button clicked!"));

// Create a layout (StackPane in this example) to hold the Button


StackPane stackPane = new StackPane();
[Link]().add(button);
// Create a Scene and set it in the Stage
Scene scene = new Scene(stackPane, 300, 200);
[Link](scene);

// Set the Stage title and show it


[Link]("Button Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}
In this example:
• A Button is created with the label "Click Me!".
• An action is defined using the setOnAction method. In this case, a
simple message is printed to the console when the button is clicked.
• The Button is added to a StackPane layout.
You can perform more complex actions when the button is clicked by
implementing an EventHandler<ActionEvent> or using lambda
expressions, as shown in the example.

• Additionally, you can style the button, set its size, change the text, and
handle various events such as mouse events and keyboard events. The
JavaFX documentation provides a comprehensive list of properties
and methods available for the Button class: Button (JavaFX 17).

RadioButton
In JavaFX, a RadioButton is a UI control that allows users to select a
single option from a group of options. Radio buttons are often used in
groups where only one option can be selected at a time. Here's a basic
example of using the RadioButton control in a JavaFX application:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class RadioButtonExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create RadioButtons
RadioButton radioButton1 = new RadioButton("Option 1");
RadioButton radioButton2 = new RadioButton("Option 2");
RadioButton radioButton3 = new RadioButton("Option 3");

// Create a ToggleGroup to group the RadioButtons


ToggleGroup toggleGroup = new ToggleGroup();
[Link](toggleGroup);
[Link](toggleGroup);
[Link](toggleGroup);

// Create a layout (VBox in this example) to hold the


RadioButtons
VBox vbox = new VBox(10); // 10 is the spacing between
children
[Link]().addAll(radioButton1, radioButton2,
radioButton3);

// Create a Scene and set it in the Stage


Scene scene = new Scene(vbox, 300, 200);
[Link](scene);

// Set the Stage title and show it


[Link]("RadioButton Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}
In this example:

• Three RadioButton instances are created with labels "Option 1",


"Option 2", and "Option 3".
• A ToggleGroup is used to group the radio buttons, ensuring that only
one radio button in the group can be selected at a time.
• The radio buttons are added to a VBox layout.
You can add an event listener to the ToggleGroup to perform actions
when the selected radio button changes:

[Link]().addListener((observable,
oldValue, newValue) -> {
if (newValue != null) {
RadioButton selectedRadioButton = (RadioButton) newValue;
[Link]("Selected Option: " +
[Link]());
}
});
• This example prints the selected option to the console when the user
changes the selection.

• The JavaFX documentation provides a comprehensive list of


properties and methods available for the RadioButton class:
RadioButton (JavaFX 17).

CheckBox
In JavaFX, a CheckBox is a UI control that allows users to toggle
between two states: selected (checked) or unselected (unchecked).
CheckBox controls are commonly used for binary choices. Here's a
basic example of using the CheckBox control in a JavaFX application:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class CheckBoxExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create Checkboxes
CheckBox checkBox1 = new CheckBox("Option 1");
CheckBox checkBox2 = new CheckBox("Option 2");
CheckBox checkBox3 = new CheckBox("Option 3");

// Create a layout (VBox in this example) to hold the Checkboxes


VBox vbox = new VBox(10); // 10 is the spacing between
children
[Link]().addAll(checkBox1, checkBox2, checkBox3);

// Create a Scene and set it in the Stage


Scene scene = new Scene(vbox, 300, 200);
[Link](scene);

// Set the Stage title and show it


[Link]("CheckBox Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}
In this example:

1. Three CheckBox instances are created with labels "Option 1",


"Option 2", and "Option 3".
2. The checkboxes are added to a VBox layout.
You can add an event listener to the CheckBox to perform actions
when the checkbox is checked or unchecked:

[Link](e -> {
if ([Link]()) {
[Link]("Option 1 is selected");
} else {
[Link]("Option 1 is unselected");
}
});
• This example prints a message to the console when the user
checks or unchecks "Option 1".

• The JavaFX documentation provides a comprehensive list of


properties and methods available for the CheckBox class:
CheckBox (JavaFX 17). You can customize the appearance and
behavior of CheckBox controls to suit your application's needs.

Hyperlink
In JavaFX, a Hyperlink is a UI control that represents a
hyperlink that can be clicked to perform an action, such as
opening a web page or triggering some other functionality in
the application. Here's a basic example of using the Hyperlink
control in a JavaFX application:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class HyperlinkExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create a Hyperlink with a label and an action
Hyperlink hyperlink = new Hyperlink("Visit OpenJFX");
[Link](e ->
openWebPage("[Link]

// Create a layout (VBox in this example) to hold the


Hyperlink
VBox vbox = new VBox(10); // 10 is the spacing between
children
[Link]().add(hyperlink);

// Create a Scene and set it in the Stage


Scene scene = new Scene(vbox, 300, 200);
[Link](scene);

// Set the Stage title and show it


[Link]("Hyperlink Example");
[Link]();
}

// Method to open a web page in the default browser


private void openWebPage(String url) {
// Use [Link] to open the default browser
[Link] desktop =
[Link]();
if
([Link]([Link])) {
try {
[Link] uri = new [Link](url);
[Link](uri);
} catch (Exception e) {
[Link]();
}
}
}

public static void main(String[] args) {


launch(args);
}
}
In this example:

• A Hyperlink is created with the label "Visit OpenJFX".


• An action is defined using the setOnAction method. In this
case, the openWebPage method is called when the hyperlink is
clicked.
• The hyperlink is added to a VBox layout.
The openWebPage method uses [Link] to open the
default web browser and navigate to the specified URL.
The JavaFX documentation provides a comprehensive list of
properties and methods available for the Hyperlink class:
Hyperlink (JavaFX 17). You can customize the appearance and
behavior of Hyperlink controls based on your application's
requirements.

Menu
In JavaFX, a Menu is a part of the MenuBar component and
represents a menu item or a sub-menu that can contain other
menu items. A Menu is typically used to organize and group
related functionality in a hierarchical structure. Here's an
example of using the Menu and MenuBar in a JavaFX
application:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MenuExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create Menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");

// Create MenuItems
MenuItem openItem = new MenuItem("Open");
MenuItem saveItem = new MenuItem("Save");
MenuItem cutItem = new MenuItem("Cut");
MenuItem copyItem = new MenuItem("Copy");
MenuItem pasteItem = new MenuItem("Paste");

// Add MenuItems to Menus


[Link]().addAll(openItem, saveItem);
[Link]().addAll(cutItem, copyItem,
pasteItem);

// Create a MenuBar and add Menus to it


MenuBar menuBar = new MenuBar();
[Link]().addAll(fileMenu, editMenu);

// Create a layout (VBox in this example) to hold the


MenuBar
VBox vbox = new VBox();
[Link]().add(menuBar);
// Create a Scene and set it in the Stage
Scene scene = new Scene(vbox, 300, 200);
[Link](scene);

// Set the Stage title and show it


[Link]("Menu Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}
In this example:

• Two Menu instances, "File" and "Edit," are created.


• Five MenuItem instances (Open, Save, Cut, Copy, Paste) are
created and added to the corresponding menus.
• The menus are added to a MenuBar.
• The MenuBar is added to a layout (a VBox in this case).
When you run this application, you'll see a basic window with a
MenuBar containing "File" and "Edit" menus, each with its own
set of menu items.

• The JavaFX documentation provides a comprehensive list of


properties and methods available for the Menu and MenuBar
classes:

Menu (JavaFX 17)


MenuBar (JavaFX 17)

Tooltips
In JavaFX, a Tooltip is a UI control that provides additional
information when the user hovers over a certain node or
control. It's a helpful way to give users more details about an
item without cluttering the main UI. Here's an example of using
Tooltip in a JavaFX application:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class TooltipExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create a Button
Button button = new Button("Hover Me");

// Create a Tooltip and set it on the Button


Tooltip tooltip = new Tooltip("This is a tooltip");
[Link](tooltip);

// Create a layout (StackPane in this example) to hold the


Button
StackPane stackPane = new StackPane();
[Link]().add(button);

// Create a Scene and set it in the Stage


Scene scene = new Scene(stackPane, 300, 200);
[Link](scene);

// Set the Stage title and show it


[Link]("Tooltip Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}
In this example:

• A Button is created with the label "Hover Me."


• A Tooltip is created with the text "This is a tooltip."
• The Tooltip is set on the Button using the setTooltip method.
Now, when you run the application and hover over the button, a
tooltip with the specified text will be displayed.

You can also set a tooltip directly on other JavaFX controls,


such as Label, TextField, etc. The Tooltip class provides
various properties and methods to customize its appearance and
behavior.

Here are a few additional points:

• If you want to create a tooltip without associating it with a


specific node initially, you can use the Tooltip constructor
directly:
Tooltip tooltip = new Tooltip("This is a tooltip");
• You can also set the tooltip text directly using the setTooltip
method without creating a separate Tooltip instance:

[Link](new Tooltip("This is a tooltip"));


The JavaFX documentation provides more details on the
Tooltip class: Tooltip (JavaFX 17).

FileChooser
In JavaFX, a FileChooser is a UI control that allows users to
interact with the file system to open or save files. It provides a
dialog that lets users browse files and directories and select or
specify a file path. Here's an example of using FileChooser in a
JavaFX application:
import [Link];
import [Link];
import [Link];

import [Link];

public class FileChooserExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create a FileChooser
FileChooser fileChooser = new FileChooser();

// Set the title for the FileChooser dialog


[Link]("Open File");

// Show the Open File dialog


File selectedFile =
[Link](primaryStage);

// Check if a file was selected


if (selectedFile != null) {
[Link]("Selected File: " +
[Link]());
} else {
[Link]("No file selected.");
}
}

public static void main(String[] args) {


launch(args);
}
}
In this example:

• A FileChooser is created.
• The setTitle method is used to set the title for the FileChooser
dialog.
• The showOpenDialog method is called to display the Open File
dialog.
• The selected file is obtained from the dialog, and its absolute
path is printed to the console.
• The FileChooser can also be configured to filter specific file
types, set an initial directory, and more. Here's an example with
additional configuration:
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

public class FileChooserExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create a FileChooser
FileChooser fileChooser = new FileChooser();

// Set the title for the FileChooser dialog


[Link]("Save File");

// Set an initial directory


[Link](new
File([Link]("[Link]")));

// Add a file extension filter


ExtensionFilter extFilter = new ExtensionFilter("Text files
(*.txt)", "*.txt");
[Link]().add(extFilter);

// Show the Save File dialog


File selectedFile =
[Link](primaryStage);

// Check if a file was selected


if (selectedFile != null) {
[Link]("Selected File: " +
[Link]());
} else {
[Link]("No file selected.");
}
}

public static void main(String[] args) {


launch(args);
}
}
• In this example, the setInitialDirectory method sets the initial
directory for the dialog, and the getExtensionFilters and add
methods are used to add a filter for text files with a .txt
extension.

• The JavaFX documentation provides more details on the


FileChooser class: FileChooser (JavaFX 17).
By Subash
Sir

5
By: Subash Sir

6Network Programming
Unit-5
Networking Basics
Computers running on the Internet communicate to each other using either the Transmission Control
Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:

When you write Java programs that communicate over the network, you are programming at the
application layer. Typically, you don't need to concern yourself with the TCP and UDP layers. Instead,
you can use the classes in the [Link] package. These classes provide system-independent network
communication. However, to decide which Java classes your programs should use, you do need to
understand how TCP and UDP differ.
Transmission Control Protocol (TCP)
TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data
between two computers.
When two applications want to communicate to each other reliably, they establish a connection and
send data back and forth over that connection. This is analogous to making a telephone call. If you want
to speak to your friend, a connection is established when you dial his phone number and he answers.
You send data back and forth over the connection by speaking to one another over the phone lines. Like
the phone company, TCP guarantees that data sent from one end of the connection actually gets to
the other end and in the same order it was sent. Otherwise, an error is reported.

TCP provides a point-to-point channel for applications that require reliable communications. The
Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of
applications that require a reliable communication channel. The order in which the data is sent and
received over the network is critical to the success of these applications. When HTTP is used to read
from a URL, the data must be received in the order in which it was sent. Otherwise, user end up with a
jumbled HTML file, a corrupt zip file, or some other invalid information.
User Datagram Protocol (UDP)
UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams,
from one computer to another with no guarantees about arrival.

The UDP protocol provides for communication that is not guaranteed between two applications on the
network. UDP is not connection-based like TCP. Rather, it sends independent packets of data, called
datagrams, from one application to another. Sending datagrams is much like sending a letter through
the postal service: The order of delivery is not important and is not guaranteed, and each message is
independent of any other.

For many applications, the guarantee of reliability is critical to the success of the transfer of information
from one end of the connection to the other. However, other forms of communication don't require
such strict standards. In fact, they may be slowed down by the extra overhead or the reliable
connection may invalidate the service altogether.

Consider, for example, a clock server that sends the current time to its client when requested to do so. If
the client misses a packet, it doesn't really make sense to resend it because the time will be incorrect
when the client receives it on the second try. If the client makes two requests and receives packets from
the server out of order, it doesn't really matter because the client can figure out that the packets are out
of order and make another request. The reliability of TCP is unnecessary in this instance because it
causes performance degradation and may hinder the usefulness of the service.

Another example of a service that doesn't need the guarantee of a reliable channel is the ping
command. The purpose of the ping command is to test the communication between two programs over
the network. In fact, ping needs to know about dropped or out-of-order packets to determine how good
or bad the connection is. A reliable channel would invalidate this service altogether.

Many firewalls and routers have been configured not to allow UDP packets. If you're having trouble
connecting to a service outside your firewall, or if clients are having trouble connecting to your service,
you should check whether UDP is permitted.

Ports
The TCP and UDP protocols use ports to map incoming data to a particular process running on a
[Link] speaking, a computer has a single physical connection to the network. All data
destined for a particular computer arrives through that connection. However, the data may be intended
for different applications running on the computer. So how does the computer know to which
application to forward the data? Through the use of ports.

Data transmitted over the Internet is accompanied by addressing information that identifies the
computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which
IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number,
which TCP and UDP use to deliver the data to the right application.

In connection-based communication such as TCP, a server application binds a socket to a specific port
number. This has the effect of registering the server with the system to receive all data destined for that
port. A client can then rendezvous with the server at the server's port.
In datagram-based communication such as UDP, the datagram packet contains the port number of its
destination and UDP routes the packet to the appropriate application.
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port
numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as
HTTP and FTP and other system services. These ports are called well-known ports. Your applications
should not attempt to bind to them.

Networking Classes in the JDK


Through the classes in [Link], Java programs can use TCP or UDP to communicate over the Internet.
The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate over the
network. The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with UDP.

Working with URLs


URL is the acronym for Uniform Resource Locator. It is a reference (an address) to a resource on the
Internet. You provide URLs to your favorite Web browser so that it can locate files on the Internet in the
same way that you provide addresses on letters so that the post office can locate your correspondents.

Java programs that interact with the Internet also may use URLs to find the resources on the Internet
they wish to access. Java programs can use a class called URL in the [Link] package to represent a
URL address.
The term URL can be ambiguous. It can refer to an Internet address or a URL object in a Java program.
Here "URL address" is used to mean an Internet address and "URL object" to refer to an instance of the
URL class in a program.

URL
URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the
[Link] you've been surfing the Web, you have undoubtedly heard the term URL and have used URLs
to access HTML pages from the Web.

It's often easiest, although not entirely accurate, to think of a URL as the name of a file on the World
Wide Web because most URLs refer to a file on some machine on the network. However, remember
that URLs also can point to other resources on the network, such as database queries and command
output.
A URL has two main components:
Protocol identifier: For the URL [Link] the protocol identifier is http.
Resource name: For the URL [Link] the resource name is [Link].

Note that the protocol identifier and the resource name are separated by a colon and two forward
slashes. The protocol identifier indicates the name of the protocol to be used to fetch the resource. The
example uses the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext
documents. HTTP is just one of many different protocols used to access different types of resources on
the net. Other protocols include File Transfer Protocol (FTP), Gopher, File, and News.

The resource name is the complete address to the resource. The format of the resource name depends
entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one
or more of the following components:
Host Name
The name of the machine on which the resource lives.
Filename
The pathname to the file on the machine.
Port Number
The port number to which to connect (typically optional).
Reference
A reference to a named anchor within a resource that usually identifies a specific location within a file
(typically optional).

For many protocols, the host name and the filename are required, while the port number and reference
are optional. For example, the resource name for an HTTP URL must specify a server on the network
(Host Name) and the path to the document on that machine (Filename); it also can specify a port
number and a reference.

Creating a URL
The easiest way to create a URL object is from a String that represents the human-readable form of the
URL address. This is typically the form that another person will use for a URL. In your Java program, you
can use a String containing this text to create a URL object:

URL myURL = new URL("[Link]

The URL object created above represents an absolute URL. An absolute URL contains all of the
information necessary to reach the resource in question. You can also create URL objects from a relative
URL address.

Creating a URL Relative to Another


In your Java programs, you can create a URL object from a relative URL specification. For example,
suppose you know two URLs at the site [Link]:
[Link]
[Link]
You can create URL objects for these pages relative to their common base URL:
[Link] like this:
URL myURL = new URL("[Link]
URL page1URL = new URL(myURL, "[Link]");
URL page2URL = new URL(myURL, "[Link]");
This code snippet uses the URL constructor that lets you create a URL object from another URL object
(the base) and a relative URL specification. The general form of this constructor is:

URL(URL baseURL, String relativeURL)

The first argument is a URL object that specifies the base of the new URL. The second argument is a
String that specifies the rest of the resource name relative to the base. If baseURL is null, then this
constructor treats relativeURL like an absolute URL specification. Conversely, if relativeURL is an
absolute URL specification, then the constructor ignores baseURL.

Other URL Constructors


new URL("http", "[Link]", "/pages/[Link]");
This is equivalent to
new URL("[Link]

The first argument is the protocol, the second is the host name, and the last is the pathname of the file.
Note that the filename contains a forward slash at the beginning. This indicates that the filename is
specified from the root of the host.

The final URL constructor adds the port number to the list of arguments used in the previous
constructor:
URL url = new URL("http", "[Link]", 80, "pages/[Link]");
This creates a URL object for the following URL:
[Link]
If you construct a URL object using one of these constructors, you can get a String containing the
complete URL address by using the URL object's toString method or the equivalent toExternalForm
method.

URL addresses with Special characters


Some URL addresses contain special characters, for example the space character. Like this:
[Link] world/
To make these characters legal they need to be encoded before passing them to the URL constructor.
URL url = new URL("[Link]
Encoding the special character(s) in this example is easy as there is only one character that needs
encoding, but for URL addresses that have several of these characters or if you are unsure when writing
your code what URL addresses you will need to access, you can use the multi-argument constructors of
the [Link] class to automatically take care of the encoding for you.
URI uri = new URI("http", "[Link]", "/hello world/", "");
And then convert the URI to a URL.
URL url = [Link]();

MalformedURLException
Each of the four URL constructors throws a MalformedURLException if the arguments to the constructor
refer to a null or unknown protocol. Typically, you want to catch and handle this exception by
embedding your URL constructor statements in a try/catch pair, like this:
try {
URL myURL = new URL(...);
}
catch (MalformedURLException e) {
// exception handler code here
// ...
}

Parsing a URL
The URL class provides several methods that let you query URL objects. You can get the protocol,
authority, host name, port number, path, query, filename, and reference from a URL using these
accessor methods:

getProtocol
Returns the protocol identifier component of the URL.
getAuthority
Returns the authority component of the URL.
getHost
Returns the host name component of the URL.
getPort
Returns the port number component of the URL. The getPort method returns an integer that is the
port number. If the port is not set, getPort returns -1.
getPath
Returns the path component of this URL.
getQuery
Returns the query component of this URL.
getFile
Returns the filename component of the URL. The getFile method returns the same as getPath, plus
the concatenation of the value of getQuery, if any.
getRef
Returns the reference component of the URL.

Note:
Remember that not all URL addresses contain these components. The URL class provides these methods
because HTTP URLs do contain these components and are perhaps the most commonly used URLs. The
URL class is somewhat HTTP-centric.

You can use these getXXX methods to get information about the URL regardless of the constructor that
you used to create the URL object.

The URL class, along with these accessor methods, frees you from ever having to parse URLs again!
Given any string specification of a URL, just create a new URL object and call any of the accessor
methods for the information you need. This small example program creates a URL from a string
specification and then uses the URL object's accessor methods to parse the URL:

import [Link].*;
import [Link].*;

public class ParseURL {


public static void main(String[] args) throws Exception {
URL aURL = new URL("[Link]
+ "/[Link]?name=networking#DOWNLOADING");

[Link]("protocol = " + [Link]());


[Link]("authority = " + [Link]());
[Link]("host = " + [Link]());
[Link]("port = " + [Link]());
[Link]("path = " + [Link]());
[Link]("query = " + [Link]());
[Link]("filename = " + [Link]());
[Link]("ref = " + [Link]());
}
}

Here is the output displayed by the program:

protocol = http
authority = [Link]
host = [Link]
port = 80
path = /docs/books/tutorial/[Link]
query = name=networking
filename = /docs/books/tutorial/[Link]?name=networking
ref = DOWNLOADING

Reading Directly from a URL


After you've successfully created a URL, you can call the URL's openStream() method to get a stream
from which you can read the contents of the URL. The openStream() method returns a
[Link] object, so reading from a URL is as easy as reading from an input stream.

The following small Java program uses openStream() to get an input stream on the URL
[Link] It then opens a BufferedReader on the input stream and reads from the
BufferedReader thereby reading from the URL. Everything read is copied to the standard output stream:

import [Link].*;
import [Link].*;

public class URLReader {


public static void main(String[] args) throws Exception {

URL oracle = new URL("[Link]


BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));

String inputLine;
while ((inputLine = [Link]()) != null)
[Link](inputLine);
[Link]();
}
}

When you run the program, you should see, scrolling by in your command window, the HTML
commands and textual content from the HTML file located at [Link]

Connecting to a URL
After you've successfully created a URL object, you can call the URL object's openConnection method to
get a URLConnection object, or one of its protocol specific subclasses, e.g. [Link]

You can use this URLConnection object to setup parameters and general request properties that you
may need before connecting. Connection to the remote object represented by the URL is only initiated
when the [Link] method is called. When you do this you are initializing a
communication link between your Java program and the URL over the network. For example, the
following code opens a connection to the site [Link]:

try {
URL myURL = new URL("[Link]
URLConnection myURLConnection = [Link]();
[Link]();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
catch (IOException e) {
// openConnection() failed
// ...
}

A new URLConnection object is created every time by calling the openConnection method of the
protocol handler for this URL.

You are not always required to explicitly call the connect method to initiate the connection. Operations
that depend on being connected, like getInputStream, getOutputStream, etc, will implicitly perform the
connection, if necessary.

Now that you've successfully connected to your URL, you can use the URLConnection object to perform
actions such as reading from or writing to the connection. The next example shows how.

Reading from a URLConnection


The following program performs the same function as the URLReader program shown in Reading
Directly from a URL.
However, rather than getting an input stream directly from the URL, this program explicitly retrieves a
URLConnection object and gets an input stream from the connection. The connection is opened
implicitly by calling getInputStream. Then, like URLReader, this program creates a BufferedReader on the
input stream and reads from it.
import [Link].*;
import [Link].*;

public class URLConnectionReader {


public static void main(String[] args) throws Exception {
URL oracle = new URL("[Link]
URLConnection yc = [Link]();
BufferedReader in = new BufferedReader(new InputStreamReader(
[Link]()));
String inputLine;
while ((inputLine = [Link]()) != null)
[Link](inputLine);
[Link]();
}
}

The output from this program is identical to the output from the program that opens a stream directly
from the URL. You can use either way to read from a URL. However, reading from a URLConnection
instead of reading directly from a URL might be more useful. This is because you can use the
URLConnection object for other tasks (like writing to the URL) at the same time.

Sockets
URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the
Internet. Sometimes your programs require lower-level network communication, for example, when you
want to write a client-server application.

In client-server applications, the server provides some service, such as processing database queries or
sending out current stock prices. The client uses the service provided by the server, either displaying
database query results to the user or making stock purchase recommendations to an investor. The
communication that occurs between the client and the server must be reliable. That is, no data can be
dropped and it must arrive on the client side in the same order in which the server sent it.

TCP provides a reliable, point-to-point communication channel that client-server applications on the
Internet use to communicate with each other. To communicate over TCP, a client program and a server
program establish a connection to one another. Each program binds a socket to its end of the
connection. To communicate, the client and the server each reads from and writes to the socket bound
to the connection.

What Is a Socket?
Normally, a server runs on a specific computer and has a socket that is bound to a specific port number.
The server just waits, listening to the socket for a client to make a connection request.

On the client-side: The client knows the hostname of the machine on which the server is running and
the port number on which the server is listening. To make a connection request, the client tries to
rendezvous with the server on the server's machine and port. The client also needs to identify itself to
the server so it binds to a local port number that it will use during this connection. This is usually
assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new
socket bound to the same local port and also has its remote endpoint set to the address and port of the
client. It needs a new socket so that it can continue to listen to the original socket for connection
requests while tending to the needs of the connected client.

On the client side, if the connection is accepted, a socket is successfully created and the client can use
the socket to communicate with the server.

The client and server can now communicate by writing to or reading from their sockets.
Definition:
A socket 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.

An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely
identified by its two endpoints. That way you can have multiple connections between your host and the
server.

The [Link] package in the Java platform provides a class, Socket, that implements one side of a two-
way connection between your Java program and another program on the network. The Socket class sits
on top of a platform-dependent implementation, hiding the details of any particular system from your
Java program. By using the [Link] class instead of relying on native code, your Java programs
can communicate over the network in a platform-independent fashion.

Additionally, [Link] includes the ServerSocket class, which implements a socket that servers can use
to listen for and accept connections to clients.

If you are trying to connect to the Web, the URL class and related classes (URLConnection, URLEncoder)
are probably more appropriate than the socket classes. In fact, URLs are a relatively high-level
connection to the Web and use sockets as part of the underlying implementation.

Establishing a Simple Server Using Stream Sockets


Establishing a simple server in Java requires five steps.
Step 1: Create a ServerSocket
First step is to create a ServerSocket object. A call to the ServerSocket constructor, such as
ServerSocket server = new ServerSocket( portNumber, queueLength );
registers an available TCP port number and specifies themaximum number of clients that can wait to
connect to the server (i.e., the queue length). The port number is used by clients to locate the server
application on the server computer. This is often called the handshake point. If the queue is full, the
server refuses client connections. The constructor establishes the port where the server waits for
connections from clients—a process known as binding the server to the port. Each client will ask to
connect to the server on this port. Only one application at a time can be bound to a specific port on the
server.
Step 2: Wait for a Connection
Programs manage each client connection with a Socket object. In Step 2, the server listens indefinitely
(or blocks) for an attempt by a client to connect. To listen for a client connection, the program calls
ServerSocket method accept, as in
Socket connection = [Link]();
which returns a Socket when a connection with a client is established. The Socket allows the server to
interact with the client. The interactions with the client actually occur at a different server port from the
handshake point. This allows the port specified in Step 1 to be used again in a multithreaded server to
accept another client connection.
Step 3: Get the Socket’s I/O Streams
Step 3 is to get the OutputStream and InputStream objects that enable the server to communicate with
the client by sending and receiving bytes. The server sends information to the client via an
OutputStream and receives information from the client via an InputStream. The server invokes method
getOutputStream on the Socket to get a reference to the Socket’s OutputStream and invokes method
getInputStream on the Socket to get a reference to the Socket’s InputStream.
Socket con=new Socket("localHost",95);
BufferedReader in=new BufferedReader(new InputStreamReader([Link]()));
PrintWriter out=new PrintWriter([Link](),true);
The beauty of establishing these relationships is that whatever the server writes to the
PrintWriter is sent via the OutputStream and is available at the client’s InputStream, and whatever the
client writes to its OutputStream (with a corresponding PrintWriter ) is available via the server’s
InputStream. The transmission of the data over the network is seamless and is handled completely by
Java.
Step 4: Perform the Processing
In which the server and the client communicate via the OutputStream and InputStream objects.
Step 5: Close the Connection
when the transmission is complete, the server closes the connection by invoking the close method on
the streams and on the Socket.
[Link]();
[Link]();
[Link]();

Establishing a Simple Client Using Stream Sockets


Establishing a simple client in Java requires four steps.
Step 1: Create a Socket to Connect to the Server
In first step we create a Socket to connect to the server. The Socket constructor establishes
the connection. For example, the statement
Socket connection = new Socket( serverAddress, port );
uses the Socket constructor with two arguments—the server’s address (serverAddress) and
the port number. If the connection attempt is successful, this statement returns a Socket. A connection
attempt that fails throws an instance of a subclass of IOException, so many programs simply catch
IOException. An UnknownHostException occurs specifically when the system is unable to resolve the
server name specified in the call to the Socket constructor to a corresponding IP address.
Step 2: Get the Socket’s I/O Streams
Here the client uses Socket methods getInputStream and getOutputStream to obtain references to the
Socket’s InputStream and OutputStream as described earlier.
Step 3: Perform the Processing
In this phase the client and the server communicate via the InputStream and OutputStream objects.
Step 4: Close the Connection
In Step 4, the client closes the connection when the transmission is complete by invoking the close
method on the streams and on the Socket as described earlier.

InetAddress class
Usually, you don't have to worry too much about Internet addresses, the numerical host addresses that
consist of four bytes (or, with IPv6, 16 bytes) such as [Link]. However, you can use the
InetAddress class if you need to convert between host names and Internet addresses.
As of JDK 1.4, the [Link] package supports IPv6 Internet addresses, provided the host operating
system does.
The static getByName method returns an InetAddress object of a host. For example,
InetAddress address = [Link]("HostName");
returns an InetAddress object that encapsulates the sequence of four bytes such as [Link].
Some host names with a lot of traffic correspond to multiple Internet addresses, to facilitate load
balancing. For example,the host name [Link] corresponds to three different Internet addresses.
One of them is picked at random when the host is accessed. You can get all hosts with the
getAllByName method.
InetAddress[] addresses = [Link](host);
String getHostAddress()-returns a string with decimal numbers, separated by periods, for example,
"[Link]".
String getHostName()-returns the host name.

Program for chatting between client and server


//[Link]
import [Link].*;
import [Link].*;
public class Server
{
public static void main(String a[])throws IOException
{
try
{
[Link]("SERVER:......\n");
ServerSocket s=new ServerSocket(95);
[Link]("Server Waiting For The Client");
Socket cs=[Link]();
InetAddress ia=[Link]();
String cli=[Link]();
[Link]("Connected to the client with IP:"+cli);
BufferedReader in=new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out=new PrintWriter([Link](),true);
do
{
BufferedReader din=new BufferedReader(new
InputStreamReader([Link]));
[Link]("To Client:");
String tocl=[Link]();
[Link](tocl);
String st=[Link]();
if([Link]("Bye")||st==null)break;
[Link]("From Client:"+st);
}while(true);
[Link]();
[Link]();
[Link]();
}
catch(IOException e) { }
}
}

//[Link]
import [Link].*;
import [Link].*;
public class Client
{
public static void main(String a[])throws IOException
{
try
{
[Link]("CLIENT:......\n");
Socket con=new Socket("localHost",95);
BufferedReader in=new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out=new PrintWriter([Link](),true);
while(true)
{
String s1=[Link]();
[Link]("From Server:"+s1);
[Link]("Enter the messages to the server:");
BufferedReader din=new BufferedReader(new
InputStreamReader([Link]));
String st=[Link]();
[Link](st);
if([Link]("Bye")||st==null)break;
}
[Link]();
[Link]();
[Link]();
}
catch(UnknownHostException e){ }
}
}

Serving Multiple Clients


There is one problem with the simple server in the preceding example. Suppose we want to allow
multiple clients to connect to our server at the same time. Typically, a server runs constantly on a server
computer, and clients from all over the Internet may want to use the server at the same time. Rejecting
multiple connections allows any one client to monopolize the service by connecting to it for a long time.
We can do much better through the magic of threads.

Every time we know the program has established a new socket connection, that is, when the call to
accept was successful, we will launch a new thread to take care of the connection between the server
and that client. The main program will just go back and wait for the next connection. For this to happen,
the main loop of the server should look like this:

while (true)
{
Socket incoming = [Link]();
Runnable r = new ThreadedEchoHandler(incoming);
Thread t = new Thread(r);
[Link]();
}

The THReadedEchoHandler class implements Runnable and contains the communication loop with the
client in its run method.

class ThreadedEchoHandler implements Runnable


{...
public void run()
{
try
{
InputStream inStream = [Link]();
OutputStream outStream = [Link]();
...process input and send response...
[Link]();
}
catch(IOException e)
{
handle exception
}
}
}
Because each connection starts a new thread, multiple clients can connect to the server at the same
time.
By: Subash Sir

Unit -7
7. Servlets and Java Server Pages

Servlets
Servlets are small programs that execute on the server side of a Web connection. Just as applets
dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of
a Web server.

A servlet is a Java programming language class used to extend the capabilities of servers that host
applications accessed via a request-response programming model. Although servlets can respond to any
type of request, they are commonly used to extend the applications hosted by Web servers. For such
applications, Java Servlet technology defines HTTP-specific servlet [Link] [Link] and
[Link] packages provide interfaces and classes for writing servlets. All servlets must
implement the Servlet interface, which defines life-cycle methods.

The Life Cycle of a Servlet


Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ). They
are implemented by every servlet and are invoked at specific times by the server. Let us consider a
typical user scenario to understand when these methods are called.
First, when a user enters a Uniform Resource Locator (URL) to a Web browser. The browser then
generates an HTTP request for this URL. This request is then sent to the appropriate server.
Second, this HTTP request is received by the Web server. The server maps this request to a particular
servlet. The servlet is dynamically retrieved and loaded into the address space of the server.
Third, the server invokes the init( ) method of the servlet. This method is invoked only when the
servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may
configure itself.
Fourth, the server invokes the service( ) method of the servlet. This method is called to process the
HTTP request. It is possible for the servlet to read data that has been provided in the HTTP request. It
may also formulate an HTTP response for the client. The servlet remains in the server’s address space
and is available to process any other HTTP requests received from clients. The service( ) method is called
for each HTTP request.
Finally, the server may decide to unload the servlet from its memory. The server calls the destroy( )
method to relinquish any resources such as file handles that are allocated for the servlet. Important
data may be saved to a persistent store. The memory allocated for the servlet and its objects can then
be garbage collected.

The Servlet API


Two packages contain the classes and interfaces that are required to build servlets. These are
[Link] and [Link]. They constitute the Servlet [Link] packages are not part of the
Java core packages. Instead, they are standard extensions. Therefore, they are not included in the Java
Software Development Kit. You must download Tomcat or Glass Fish server to obtain their functionality.

Prepared by: Navin Sharma 1 Unit-7: Servlets and JSP


The [Link] Package
The [Link] package contains a number of interfaces and classes that establish the framework in
which servlets operate.
The following table summarizes the core interfaces that are provided in this package. The most
significant of these is Servlet. All servlets must implement this interface or extend a class that
implements the interface.
The ServletRequest and ServletResponse interfaces are also very important.
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access information about
their environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
SingleThreadModel Indicates that the servlet is thread safe.

The following table summarizes the core classes that are provided in the [Link] package.
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream Provides an input stream for reading requests from a client.
ServletOutputStream Provides an output stream for writing responses to a client.
ServletException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable.

The Servlet Interface


All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy( )
methods that are called by the server during the life cycle of a servlet. The methods defined by Servlet
are shown below:

Prepared by: Navin Sharma 2 Unit-7: Servlets and JSP


The ServletRequest Interface
The ServletRequest interface is implemented by the server. It enables a servlet to obtain information
about a client request. Several of its methods are summarized in Table below.

Prepared by: Navin Sharma 3 Unit-7: Servlets and JSP


Prepared by: Navin Sharma 4 Unit-7: Servlets and JSP
The ServletResponse Interface
The ServletResponse interface is implemented by the server. It enables a servlet to formulate a
response for a client. Several of its methods are summarized in Table below.

Note: For detailed information about [Link] package refer to the following link
[Link]

Reading Servlet Parameters


The ServletRequest class includes methods that allow to read the names and values of parameters that
are included in a client request. We will develop a servlet that illustrates their use. The example contains
two files. A Web page is defined in [Link] and a servlet is defined in [Link]. The
HTML source code for [Link] is shown in the following listing. It defines a table that contains two
labels and two text fields. One of the labels is Employee and the other is Phone. There is also a submit
button. Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet
to process the HTTP POST request.

//[Link]
<html>
<body>
<center>

Prepared by: Navin Sharma 5 Unit-7: Servlets and JSP


<form name="Form1" method="post" action="PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>

//[Link]
import [Link].*;
import [Link].*;
import [Link].*;

public class PostParametersServlet extends GenericServlet {

public void service(ServletRequest request,ServletResponse response)


throws ServletException, IOException {
// Get print writer.
PrintWriter pw = [Link]();
// Get enumeration of parameter names.
Enumeration e = [Link]();
// Display parameter names and values.
while([Link]()) {
String pname = (String)[Link]();
[Link](pname + " = ");
String pvalue = [Link](pname);
[Link](pvalue);
}
[Link]();
}
}

output
e = navin
p = 9841

Prepared by: Navin Sharma 6 Unit-7: Servlets and JSP


The [Link] Package
The [Link] package contains a number of interfaces and classes that are commonly used by
servlet developers. You will see that its functionality makes it easy to build servlets that work with HTTP
requests and responses.
The following table summarizes the core interfaces that are provided in this package:
Interface Description
HttpServletRequest Enables servlets to read data from an HTTP request.
HttpServletResponse Enables servlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound
from a session.
The following table summarizes the core classes that are provided in this package. The most important
of these is HttpServlet. Servlet developers typically extend this class in order to process HTTP requests.
Class Description
Cookie Allows state information to be stored on a client
machine.
HttpServlet Provides methods to handle HTTP requests and
responses.
HttpSessionEvent Encapsulates a session-changed event.
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session
value, or that a session attribute changed.
The HttpServletRequest Interface
The HttpServletRequest interface is implemented by the server. It enables a servlet to obtain
information about a client request. Several of its methods are shown in Table below.

Prepared by: Navin Sharma 7 Unit-7: Servlets and JSP


The HttpServletResponse Interface
The HttpServletResponse interface is implemented by the server. It enables a servlet to formulate an
HTTP response to a client. Several constants are defined. These correspond to the different status codes
that can be assigned to an HTTP response. For example, SC_OK indicates that the HTTP request
succeeded and SC_NOT_FOUND indicates that the requested resource is not available. Several methods
of this interface are summarized in Table below.

Prepared by: Navin Sharma 8 Unit-7: Servlets and JSP


The Cookie Class
The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information.
Cookies are valuable for tracking user activities. For example, assume that a user visits an online store. A
cookie can save the user’s name, address, and other information. The user does not need to enter this
data each time he or she visits the store. A servlet can write a cookie to a user’s machine via the
addCookie( ) method of the HttpServletResponse interface. The data for that cookie is then included in
the header of the HTTP response that is sent to the browser.
The names and values of cookies are stored on the user’s machine. Some of the information that is

Prepared by: Navin Sharma 9 Unit-7: Servlets and JSP


saved for each cookie includes the following:
 The name of the cookie
 The value of the cookie
 The expiration date of the cookie
 The domain and path of the cookie
The expiration date determines when this cookie is deleted from the user’s machine. If an expiration
date is not explicitly assigned to a cookie, it is deleted when the current browser session ends.
Otherwise, the cookie is saved in a file on the user’s machine.
The domain and path of the cookie determine when it is included in the header of an HTTP request. If
the user enters a URL whose domain and path match these values, the cookie is then supplied to the
Web server. Otherwise, it is not.
The methods of the Cookie class are summarized in Table below

The HttpServlet Class


The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive

Prepared by: Navin Sharma 10 Unit-7: Servlets and JSP


and process HTTP requests. The methods of the HttpServlet class are summarized in Table below.

Handling HTTP Requests and Responses


The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A
servlet developer typically overrides one of these methods. These methods are doDelete( ), doGet( ),
doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ).

Handling HTTP GET Requests


Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when a form on
a Web page is submitted.
//[Link]
<html>

Prepared by: Navin Sharma 11 Unit-7: Servlets and JSP


<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Testing GET</title>
</head>
<body>
<form action="testingget" method="get">
<label style="color: green;"> <b>Testing Get:</b></label><br/></br>
First Name: <input type="text" name="firstName" size="20"><br /><br/>
Last Name: <input type="text" name="surname" size="20">
<br /><br />
<input type="submit" value="Submit"></br></br>
</form>
</body>
</html>

//TestingGet
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class TestingGet extends HttpServlet {

private Connection connection;


private Statement statement;

// set up database connection and create SQL statement


public void init( ServletConfig config ) throws ServletException
{
// attempt database connection and create Statement
try
{

connection=[Link]( "jdbc:mysql://localhost:3306/testingget","root","");

// create Statement to query database


statement = [Link]();
} // end try
// for any exception throw an UnavailableException to
// indicate that the servlet is not currently available
catch ( Exception exception )
{
[Link]();

Prepared by: Navin Sharma 12 Unit-7: Servlets and JSP


throw new UnavailableException( [Link]() );
} // end catch
} // end method init

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
try {
String firstName = [Link]("firstName").toString();
String surname = [Link]("surname").toString();
try {
statement = [Link](ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

ResultSet uprs = [Link](


"SELECT * FROM names");

[Link]();
[Link]("firstname",firstName);
[Link]("lastname",surname);
[Link]();
[Link]();
}
catch ( SQLException sqlException )
{
[Link]();
}
try
{

// create Statement for querying database


statement = [Link]();

// query database
ResultSet resultSet = [Link](
"SELECT * from names" );
[Link]("<html>");
[Link]("<head>");
[Link]("</head>");
[Link]("<body>");
[Link]("<p>Welcome " + firstName + " " + surname + "</p>");
[Link]( "<p>People currently in the database:</p>" );
// process query results
ResultSetMetaData metaData = [Link]();
int numberOfColumns = [Link]();
for ( int i = 1; i <= numberOfColumns; i++ )

Prepared by: Navin Sharma 13 Unit-7: Servlets and JSP


[Link]("<label style='color:red'>"+ [Link]( i )+"</label>" );
[Link]("</br>");
while ( [Link]() )
{
for ( int i = 1; i <= numberOfColumns; i++ )
[Link]("<label style='color:blue'>"+ [Link]( i )+"</label>" );
[Link]("</br>");
} // end while
[Link]("</body>");
[Link]("</html>");
} // end try
catch ( SQLException sqlException )
{
[Link]();
} // end catch

}//end try

finally {
[Link]();
}
}
// close SQL statements and database when servlet terminates
public void destroy()
{
// attempt to close statements and database connection
try
{
[Link]();
[Link]();
} // end try
// handle database exceptions by returning error to client
catch( SQLException sqlException )
{
[Link]();
} // end catch
} // end method destroy

}
Handling HTTP POST Requests
Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when a form
on a Web page is submitted.

//[Link]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Testing POST</title>

Prepared by: Navin Sharma 14 Unit-7: Servlets and JSP


</head>
<body>
<form action="testingpost" method="post">
<label style="color: red;"> <b>Testing Post:</b></label><br/></br>
First Name: <input type="text" name="firstName" size="20"><br /><br/>
<input type="submit" value="Submit"><br/><br/>
</form>
</body>
</html>

//TestingPost
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class TestingPost extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
try {
String firstName = [Link]("firstName").toString();
[Link]("<html>");
[Link]("<head>");
[Link]("</head>");
[Link]("<body>");
[Link]("<label style='color:red'>Welcome </label>");
[Link]("<label style='color:green'>"+firstName+"</label>");
[Link]("</body>");
[Link]("</html>");}
finally {
[Link]();
}
}
}

Using Cookies
Now, let’s develop a servlet that illustrates how to use cookies. The servlet is invoked when a form on a
Web page is submitted. The example contains three files as summarized here:
File Description
[Link] Allows a user to specify a value for the cookie
named MyCookie.
[Link] Processes the submission of [Link].
[Link] Displays cookie values.

Prepared by: Navin Sharma 15 Unit-7: Servlets and JSP


//[Link]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Testing Cookies</title>
</head>
<body>
</form>
<form action="addCookie" method="post">
<label style="color: red;"> <b>Testing Cookies<b></label><br/></br>
<b>Enter the value for cookie</b></br>
First Name: <input type="text" name="firstName" size="20"><br /><br/>
Last Name: <input type="text" name="surname" size="20"><br/><br/>
<input type="submit" value="Submit"><br/><br/>
</form>
<label><b>Click below to get Cookies Value</b></label></br>
<a href="getCookie">click here</a> <br/><br/>
</body>
</html>

//[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
try {
// Get parameter from HTTP request.
String data = [Link]("firstName");
String data1 = [Link]("surname");

// Create cookie.
Cookie cookie = new Cookie("FirstCookie", data);
Cookie cookie1 = new Cookie("SecondCookie", data1);

// Add cookie to HTTP response.


[Link](cookie);
[Link](cookie1);
// Write output to browser.
[Link]("<html>");

Prepared by: Navin Sharma 16 Unit-7: Servlets and JSP


[Link]("<head>");
[Link]("<title>Servlet AddCookie</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<B>MyCookie has been set to");
[Link](data);
[Link]("<br/>");
[Link](data1);
[Link]("</body>");
[Link]("</html>");
} finally {
[Link]();
}
}
}

//[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
try {
Cookie[] cookies = [Link]();
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet GetCookie</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<B>");
for(int i = 0; i < [Link]; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
[Link]("name = " + name +
"; value = " + value);
[Link]("</br>");
[Link]("</body>");
[Link]("</html>");
}
}
finally {

Prepared by: Navin Sharma 17 Unit-7: Servlets and JSP


[Link]();
}
}
}

Session Tracking
HTTP is a stateless protocol. Each request is independent of the previous one. However, in some
applications, it is necessary to save state information so that information can be collected from several
interactions between a browser and a server. Sessions provide such a mechanism.

A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is
returned. This object can store a set of bindings that associate names with objects. The setAttribute( ),
getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these
bindings. It is important to note that session state is shared among all the servlets that are associated
with a particular client.

//[Link]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Testing Cookies</title>
</head>
<body>
<label style="color: blue"><b>Testing Session</b></label></br>
<label><b>Click below to get Session Value</b></label></br>
<a href="getSession">click here</a>
</body>
</html>

//[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
try {
// Get the HttpSession object.
HttpSession hs = [Link](true);
// Get writer.
// [Link]("text/html");

Prepared by: Navin Sharma 18 Unit-7: Servlets and JSP


//PrintWriter pw = [Link]();
[Link]("<B>");
// Display date/time of last access.
Date date = (Date)[Link]("date");

// Display current date/time.

[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet GetSession</title>");
[Link]("</head>");
[Link]("<body>");
if(date != null) {
[Link]("Last access: " + date + "<br>");
}
date = new Date();
[Link]("date", date);
[Link]("Current date: " + date);
[Link]("</body>");
[Link]("</html>");
} finally {
[Link]();
}
}
}

JavaServer Pages (JSP)


In the previous chapter, you learned how to generate dynamic Web pages with servlets. You probably
have already noticed in our examples that most of the code in our servlets generated output that
consisted of the HTML elements that composed the response to the client. Only a small portion of the
code dealt with the business logic. Generating responses from servlets requires that Web application
developers be familiar with Java. However, many people involved in Web application development, such
as Web site designers, do not know Java. It is difficult for people who are not Java programmers to
implement, maintain and extend a Web application that consists of primarily of servlets. The solution to
this problem is JavaServer Pages (JSP)an extension of servlet technology that separates the presentation
from the business logic. This lets Java programmers and Web-site designers focus on their
strengthswriting Java code and designing Web pages, respectively.

JavaServer Pages simplify the delivery of dynamic Web content. They enable Web application
programmers to create dynamic content by reusing predefined components and by interacting with
components using server-side scripting. Custom-tag libraries are a powerful feature of JSP that allows
Java developers to hide complex code for database access and other useful services for dynamic Web
pages in custom tags. Web sites use these custom tags like any other Web page element to take
advantage of the more complex functionality hidden by the tag. Thus, Web-page designers who are not
familiar with Java can enhance Web pages with powerful dynamic content and processing capabilities.

The classes and interfaces that are specific to JavaServer Pages programming are located in packages

Prepared by: Navin Sharma 19 Unit-7: Servlets and JSP


[Link] and [Link].

JavaServer Pages Overview


There are four key components to JSPs-directives, actions, scripting elements and tag libraries.
Directives are messages to the JSP container-the server component that executes JSPs-that enable the
programmer to specify page settings, to include content from other resources and to specify custom tag
libraries for use in a JSP. Actions encapsulate functionality in predefined tags that programmers can
embed in a JSP. Actions often are performed based on the information sent to the server as part of a
particular client request. They also can create Java objects for use in JSP scriptlets. Scripting elements
enable programmers to insert Java code that interacts with components in a JSP (and possibly other
Web application components) to perform request processing. Scriptlets, one kind of scripting element,
contain code fragments that describe the action to be performed in response to a user request. Tag
libraries are part of the tag extension mechanism that enables programmers to create custom tags.
Such tags enable Web page designers to manipulate JSP content without prior Java knowledge.

In some ways, JavaServer Pages look like standard XHTML or XML documents. In fact, JSPs normally
include XHTML or XML markup. Such markup is known as fixed-template data or fixed-template text.
Fixed-template data often helps a programmer decide whether to use a servlet or a JSP. Programmers
tend to use JSPs when most of the content sent to the client is fixed-template data and little or none of
the content is generated dynamically with Java code. Programmers typically use servlets when only a
small portion of the content sent to the client is fixed-template data. In fact, some servlets do not
produce content. Rather, they perform a task on behalf of the client, then invoke other servlets or JSPs
to provide a response. Note that in most cases servlet and JSP technologies are interchangeable. As with
servlets, JSPs normally execute as part of a Web server.

When a JSP-enabled server receives the first request for a JSP, the JSP container translates the JSP into a
Java servlet that handles the current request and future requests to the JSP. Literal text in a JSP
becomes string literals in the servlet that represents the translated JSP. Any errors that occur in
compiling the new servlet result in translation-time errors. The JSP container places the Java statements
that implement the JSP's response in method _jspService at translation time. If the new servlet compiles
properly, the JSP container invokes method _jspService to process the request. The JSP may respond
directly or may invoke other Web application components to assist in processing the request. Any errors
that occur during request processing are known as request-time errors.

Overall, the request-response mechanism and the JSP life cycle are the same as those of a servlet. JSPs
can override methods jspInit and jspDestroy (similar to servlet methods init and destroy), which the JSP
container invokes when initializing and terminating a JSP, respectively. JSP programmers can define
these methods using JSP declarations--part of the JSP scripting mechanism.

A Simple JSP Example


JSP expression inserting the date and time into a Web page.
//[Link]
<html>
<head>
<meta http-equiv = "refresh" content = "60" />
<title>A Simple JSP Example</title>
<style type = "text/css">
.big { font-family: helvetica, arial, sans-serif;

Prepared by: Navin Sharma 20 Unit-7: Servlets and JSP


font-weight: bold;
font-size: 2em; }
</style>
</head>
<body>
<p class = "big">Simple JSP Example</p>
<table style = "border: 6px outset;">
<tr>
<td style = "background-color: black;">
<p class = "big" style = "color: cyan;">
<!-- JSP expression to insert date/time -->
<%= new [Link]() %>
</p>
</td>
</tr>
</table>
</body
</html>

output

As you can see, most of [Link] consists of XHTML [Link] cases like this, JSPs are easier to
implement than servlets. In a servlet that performs the same task as this JSP, each line of XHTML
markup typically is a separate Java statement that outputs the string representing the markup as part of
the response to the client. Writing code to output markup can often lead to [Link]'s whhy in such
scenarios JSP is preferred than [Link] key line in the above program is the expression

<%= new [Link]() %>

JSP expressions are delimited by <%= and %>. The preceding expression creates a new instance of class
Date (package [Link]). By default, a Date object is initialized with the current date and time. When the
client requests this JSP, the preceding expression inserts the String representation of the date and time

Prepared by: Navin Sharma 21 Unit-7: Servlets and JSP


in the response to the client. [Note: Because the client of a JSP could be anywhere in the world, the JSP
should return the date in the client locale's format. However, the JSP executes on the server, so the
server's locale determines the String representation of the Date.

We use the XHTML meta element in line 9 to set a refresh interval of 60 seconds for the document. This
causes the browser to request [Link] every 60 seconds. For each request to [Link], the JSP container
reevaluates the expression in line 24, creating a new Date object with the server's current date and
time.

When you first invoke the JSP, you may notice a brief delay as GlassFish Server translates the JSP into a
servlet and invokes the servlet to respond to your request

Implicit Objects
Implicit objects provide access to many servlet capabilities in the context of a JavaServer Page. Implicit
objects have four scopes: application, page, request and session. The JSP container owns objects with
application scope. Any JSP can manipulate such objects. Objects with page scope exist only in the page
that defines them. Each page has its own instances of the page-scope implicit objects. Objects with
request scope exist for the duration of the request. For example, a JSP can partially process a request,
then forward it to a servlet or another JSP for further processing. Request-scope objects go out of scope
when request processing completes with a response to the client. Objects with session scope exist for
the client's entire browsing session. Figure below describes the JSP implicit objects and their scopes.

Prepared by: Navin Sharma 22 Unit-7: Servlets and JSP


fig. JSP implicit objects.

Scripting
JavaServer Pages often present dynamically generated content as part of an XHTML document that is

Prepared by: Navin Sharma 23 Unit-7: Servlets and JSP


sent to the client in response to a request. In some cases, the content is static but is output only if
certain conditions are met during a request (e.g., providing values in a form that submits a request). JSP
programmers can insert Java code and logic in a JSP using scripting.

Scripting Components
The JSP scripting components include scriptlets, comments, expressions, declarations and escape
sequences.

Scriptlets are blocks of code delimited by <% and %>. They contain Java statements that the container
places in method _jspService at translation time.

JSPs support three comment styles: JSP comments, XHTML comments and scripting-language
comments. JSP comments are delimited by <%-- and --%>. These can be placed throughout a JSP, but
not inside scriptlets. XHTML comments are delimited with <!-- and -->. These, too, can be placed
throughout a JSP, but not inside scriptlets. Scripting language comments are currently Java comments,
because Java currently is the only JSP scripting language. Scriptlets can use Java's end-of-line //
comments and traditional comments (delimited by /* and */). JSP comments and scripting-language
comments are ignored and do not appear in the response to a client. When clients view the source code
of a JSP response, they will see only the XHTML comments in the source code. The different comment
styles are useful for separating comments that the user should be able to see from those that document
logic processed on the server.

JSP expressions are delimited by <%= and %> and contain a Java expression that is evaluated when a
client requests the JSP containing the expression. The container converts the result of a JSP expression
to a String object, then outputs the String as part of the response to the client.

Declarations, delimited by <%! and %>, enable a JSP programmer to define variables and methods for
use in a JSP. Variables become instance variables of the servlet class that represents the translated JSP.
Similarly, methods become members of the class that represents the translated JSP. Declarations of
variables and methods in a JSP use Java syntax. Thus, a variable declaration must end with a semicolon,
as in

<%! int counter = 0; %>

Special characters or character sequences that the JSP container normally uses to delimit JSP code can
be included in a JSP as literal characters in scripting elements, fixed template data and attribute values
using escape sequences. Figure below shows the literal character or characters and the corresponding
escape sequences and discusses where to use the escape sequences.

Prepared by: Navin Sharma 24 Unit-7: Servlets and JSP


fig. JSP escape sequences

Scripting Example
//[Link]
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Processing "get" requests with data</title>
</head>
<!-- body section of document -->
<body>
<% // begin scriptlet
String name = [Link]( "firstName" );

if ( name != null )
{
%> <%-- end scriptlet to insert fixed template data --%>

<h1>
Hello <%= name %>, <br />
Welcome to JavaServer Pages!
</h1>

<% // continue scriptlet

} // end if
else {

%> <%-- end scriptlet to insert fixed template data --%>

Prepared by: Navin Sharma 25 Unit-7: Servlets and JSP


<form action = "[Link]" method = "get">
<p>Type your first name and press Submit</p>

<p><input type = "text" name = "firstName" />


<input type = "submit" value = "Submit" />
</p>
</form>

<% // continue scriptlet

} // end else

%> <%-- end scriptlet --%>


</body>
</html>

Output

Standard Actions
Standard actions provide JSP implementors with access to several of the most common tasks performed
in a JSP, such as including content from other resources, forwarding requests to other resources and
interacting with JavaBean software components. JSP containers process actions at request time.
Actions are delimited by <jsp:action> and </jsp:action>, where action is the standard action name. In
cases where nothing appears between the starting and ending tags, the XML empty element syntax <jsp:
action /> can be used. Figure below summarizes the JSP standard actions.

Prepared by: Navin Sharma 26 Unit-7: Servlets and JSP


fig. JSP standard actions
<jsp:include> Action
JavaServer Pages support two include mechanisms-the <jsp:include> action and the include directive.
Action <jsp:include> enables dynamic content to be included in a JavaServer Page at request time. If the
included resource changes between requests, the next request to the JSP containing the <jsp:include>
action includes the resource's new content. On the other hand, the include directive copies the content
into the JSP once, at JSP translation time. If the included resource changes, the new content will not be
reflected in the JSP that used the include directive, unless that JSP is recompiled, which normally would
occur only if a new version of the JSP is installed. Figure below describes the attributes of action
<jsp:include>.

Prepared by: Navin Sharma 27 Unit-7: Servlets and JSP


fig. Action <jsp:include> attributes.

//[Link]
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LN TECH PVT. LTD</title>

<style type = "text/css">


body
{
font-family: tahoma, helvetica, arial, sans-serif;
}

table, tr, td
{
font-size: .9em;
border: 3px groove;
padding: 5px;
background-color: yellowgreen;
}
</style>

</head>
<body>
<table style="width: 1280px; height: 675px">
<tr>
<td style = "width: 215px; text-align: center">
<img src = "LN_Tech_logo.jpg"
width = "140" height = "93"
alt = "LN Tech Logo" />
</td>
<td>
<%-- include [Link] in this JSP --%>
<jsp:include page = "[Link]"

Prepared by: Navin Sharma 28 Unit-7: Servlets and JSP


flush = "true" />
</td>
</tr>
<tr>
<td style = "width: 215px">
<%-- include [Link] in this JSP --%>
<jsp:include page = "[Link]" flush = "true" />
</td>
<td style = "vertical-align: top">
<%-- include [Link] in this JSP --%>
<jsp:include page = "[Link]"
flush = "true" />
</td>
</tr>
</table>
</body>
</html>

//[Link]
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div style = "width: 580px">
<p><b>
LN Tech....a dedicated team of Engineers <br /> Working
in the field of Web<br />
welcomes you to explore our site</b>
</p>
<p>
<a href = "[Link]
<br />Baneshwor<br />Kathmandu, Nepal
</p>
</div>
</body>
</html>

//[Link]
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>

Prepared by: Navin Sharma 29 Unit-7: Servlets and JSP


<p><a href = "[Link]">
<b>Sign up</b>
</a></p>
<p><a href = "[Link]
<b>About us</b>
</a></p>

<p><a href = "[Link]


<b>Services</b>
</a></p>

<p><a href = "[Link]


<b>Our works/Porfolios</b>
</a></p>

<p><a href = "[Link]


<b>Jobs</b>
</a></p>
<p><a href = "[Link]
<b>Home Page</b>
</a></p>

<p>Send questions or comments about this site to


<a href = "[Link]
admin@[Link]
</a><br />
Copyright 2009-2012 by LN Tech Pvt Ltd.
All Rights Reserved.
</p>
</body>
</html>

//[Link]
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Clock Page</title>
</head>
<body>
<table>
<tr>
<td style = "background-color: blanchedalmond;">
<p class = "big" style = "color: black; font-size: 3em;
font-weight: bold;">

<%-- script to determine client local and --%>


<%-- format date accordingly --%>

Prepared by: Navin Sharma 30 Unit-7: Servlets and JSP


<%
// get client locale
[Link] locale = [Link]();

// get DateFormat for client's Locale


[Link] dateFormat =
[Link](
[Link],
[Link], locale );

%> <%-- end script --%>

<%-- output date --%>


<%= [Link]( new [Link]() ) %>
</p>
</td>
</tr>
</table>
</body>
</html>

//[Link]
<!DOCTYPE html>
<html>
<!-- head section of document -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sign up Page</title>
</head>
<!-- body section of document -->
<body>
<% // begin scriptlet

String name = [Link]( "firstName" );

if ( name != null )
{
%> <%-- end scriptlet to insert fixed template data --%>

<h1>
Hello <%= name %>, <br />
Welcome to LN Tech!
</h1>

<% // continue scriptlet

} // end if
else {

Prepared by: Navin Sharma 31 Unit-7: Servlets and JSP


%> <%-- end scriptlet to insert fixed template data --%>

<form action = "[Link]" method = "get">


<p>Type your first name and press Submit</p>

<p><input type = "text" name = "firstName" />


<input type = "submit" value = "Submit" />
</p>
</form>

<% // continue scriptlet

} // end else

%> <%-- end scriptlet --%>


</body>
</body>
</html> <!-- end XHTML document -->

output

Prepared by: Navin Sharma 32 Unit-7: Servlets and JSP


By: Subash Sir

Unit-8 Remote Method Invocation(RMI)

The Remote Method Invocation (RMI) model represents a distributed object application. RMI allows an
object inside a JVM (a client) to invoke a method on an object running on a remote JVM (a server) and
have the results returned to the client.
 Therefore, RMI implies a client and a server.
The server application typically creates an object and makes it accessible remotely.
 Therefore, the object is referred to as a remote object.
 The server registers the object that is available to clients.
One of the ways this can be accomplished is through a naming facility provided as part of the JDK, which
is called the rmiregistry. The server uses the registry to bind an arbitrary name to a
remote object. A client application receives a reference to the object on the server and then invokes
methods on it. The client looks up the name in the registry and obtains a reference to an object that is
able to interface with the remote object. The reference is referred to as a remote object reference.
Most importantly, a method invocation on a remote object has the same syntax as a method invocation
on a local object.

RMI Architecture
The interface that the client and server objects use to interact with each other is provided through
stubs/skeleton, remote reference, and transport layers. Stubs and skeletons are Java objects that act as
proxies to the client and server, respectively.

All the network-related code is placed in the stub and skeleton, so that the client and server will not
have to deal with the network and sockets in their code. The remote reference layer handles the
creation of and management of remote objects. The transport layer is the protocol that sends remote
object requests across the network.
A simple diagram showing the above relationships is shown below.

Client Server

Stub Skeleton

Remote Reference Layer Remote Reference Layer

Transport Layer Transport Layer

Network Connection

Developing a distributed application using RMI involves the following steps:


1. Define a remote interface
2. Implement the remote interface
3. Develop the server
4. Develop a client
5. Generate Stubs and Skeletons, start the RMI registry, server, and client

Prepared by: Navin Kishor Sharma 1 RMI and CORBA


The Remote Interface
The server's job is to accept requests from a client, perform some service, and then send the results
back to the [Link] server must specify an interface that defines the methods available to clients as
a service. This remote interface defines the client view of the remote [Link] remote interface is
always written to extend the [Link] interface. Remote is a "marker" interface that identifies
interfaces whose methods may be invoked from a non-local virtual machine.

//[Link]
import [Link].*;
public interface RemoteInterface extends Remote
{
public int add(int x,int y)throws RemoteException;
}

In the example above, add(int x,int y) is a remote method of the remote interface RemoteInterface. All
methods defined in the remote interface are required to state that they throw a RemoteException. A
RemoteException represents communication-related exceptions that may occur during the execution of
a remote method call.

The Remote Object


An implementation of the RemoteInterface interface is shown below.
//[Link]
import [Link].*;
import [Link].*;
import [Link];
public class ServerImplements extends UnicastRemoteObject implements RemoteInterface
{
public ServerImplements()throws RemoteException
{
super();
}
public int add(int x,int y)
{
return (x+y);
}
}

The implementation is referred to as the remote object. The implementation class extends
UnicastRemoteObject to link into the RMI system. This is not a requirement. A class that does not
extend UnicastRemoteObject may use its exportObject() method to be linked into RMI. When a class
extends UnicastRemoteObject, it must provide a constructor declaring that it may throw a
RemoteException object. When this constructor calls super(), it activates code in UnicastRemoteObject,
which performs the RMI linking and remote object initialization.

Writing the Server


//[Link]
import [Link];
import [Link];

Prepared by: Navin Kishor Sharma 2 RMI and CORBA


public class Server
{
public static void main(String args[])
{
try
{
ServerImplements s=new ServerImplements();
[Link](1099);
[Link]("SERVICE",s);
[Link]("Server Started ");
}
catch(Exception e)
{
[Link]([Link]());
}
}
}

The server creates the remote object, registers it under some arbitrary name, then waits for remote
requests. The [Link] class allows the RMI registry service (provided as part of
the JVM) to be started within the code by calling its createRegistry method.
This could have also been achieved by typing the following at a command prompt: start rmiregistry. The
default port for RMI is 1099. The [Link] class provides two
methods for binding objects to the registry.
[Link]("ArbitraryName", remoteObj); throws an Exception if an object is already bound under
the "ArbitrayName. "
[Link] ("ArbitraryName", remoteObj); binds the object under the "ArbitraryName" if it does
not exist or overwrites the object that is bound.
The example above acts as a server that creates a ServerImplements object and makes it available to
clients by binding it under a name of "SERVICE ".

NOTE: If both the client and the server are running Java SE 5 or higher, no additional work is needed on
the server side. Simply compile the [Link], [Link], and
[Link], and the server can then be started. The reason for this is the introduction in Java
SE 5 of dynamic generation of stub classes. Java SE 5 adds support for the dynamic generation of stub
classes at runtime, eliminating the need to use the RMI stub compiler, rmic, to pre-generate stub classes
for remote objects.
• Note that rmic must still be used to pre-generate stub classes for remote objects that need to support
clients running on earlier versions.

Writing the Client


//[Link]
import [Link].*;
import [Link].*;
public class Client
{
public static void main(String args[])
{

Prepared by: Navin Kishor Sharma 3 RMI and CORBA


try
{
String ip="rmi://[Link]/SERVICE";
RemoteInterface s=
(RemoteInterface)[Link](ip);
[Link]("sum: "+ [Link](1,3));
}
catch(Exception e)
{
[Link]([Link]());
[Link]();
}
}
}

RMI pros and cons


Remote method invocation has significant features that CORBA doesn't possess - most notably the
ability to send new objects (code and data) across a network, and for foreign virtual machines to
seamlessly handle the new object. Remote method invocation has been available since JDK 1.02, and so
many developers are familiar with the way this technology works, and organizations may already have
systems using RMI. Its chief limitation, however, is that it is limited to Java Virtual Machines, and
cannot interface with other languages.

Pros cons
Portable across many platforms Tied only to platforms with Java support
Can introduce new code to foreign JVMs Security threats with remote code execution, and
limitations on functionality enforced by security
restrictions.
Java developers may already have experience with Learning curve for developers that have no RMI
RMI (available since JDK1.02) experience is comparable with CORBA
Existing systems may already use RMI - the cost Can only operate with Java systems - no support
and time to convert to a new technology may be for legacy systems written in C++, Ada, Fortran,
prohibitive Cobol, and others (including future languages).

Common Object Request Broker Architecture(CORBA)

CORBA, or Common Object Request Broker Architecture, is a standard architecture for distributed
object systems. It allows a distributed, heterogeneous collection of objects to interoperate.
The OMG
The Object Management Group (OMG) is responsible for defining CORBA. The OMG comprises over 700
companies and organizations, including almost all the major vendors and developers of distributed
object technology, including platform, database, and application vendors as well as software tool and
corporate developers.
CORBA Architecture
CORBA defines an architecture for distributed objects. The basic CORBA paradigm is that of a request for
services of a distributed object. Everything else defined by the OMG is in terms of this basic paradigm.

Prepared by: Navin Kishor Sharma 4 RMI and CORBA


The services that an object provides are given by its interface. Interfaces are defined in OMG's Interface
Definition Language (IDL). Distributed objects are identified by object references, which are typed by IDL
interfaces.
The figure below graphically depicts a request. A client holds an object reference to a distributed object.
The object reference is typed by an interface. In the figure below the object reference is typed by the
Rabbit interface. The Object Request Broker, or ORB, delivers the request to the object and returns any
results to the client. In the figure, a jump request returns an object reference typed by the
AnotherObject interface.

The ORB
The ORB is the distributed service that implements the request to the remote object. It locates the
remote object on the network, communicates the request to the object, waits for the results and when
available communicates those results back to the client.
The ORB implements location transparency. Exactly the same request mechanism is used by the client
and the CORBA object regardless of where the object is located. It might be in the same process with the
client, down the hall or across the planet. The client cannot tell the difference.
The ORB implements programming language independence for the request. The client issuing the
request can be written in a different programming language from the implementation of the CORBA
object. The ORB does the necessary translation between programming languages. Language bindings are
defined for all popular programming languages.

CORBA as a Standard for Distributed Objects


One of the goals of the CORBA specification is that clients and object implementations are portable. The
CORBA specification defines an application programmer's interface (API) for clients of a distributed
object as well as an API for the implementation of a CORBA object. This means that code written for one
vendor's CORBA product could, with a minimum of effort, be rewritten to work with a different vendor's
product. However, the reality of CORBA products on the market today is that CORBA clients are portable
but object implementations need some rework to port from one CORBA product to another.
CORBA 2.0 added interoperability as a goal in the specification. In particular, CORBA 2.0 defines a
network protocol, called IIOP (Internet Inter-ORB Protocol), that allows clients using a CORBA product
from any vendor to communicate with objects using a CORBA product from any other vendor. IIOP
works across the Internet, or more precisely, across any TCP/IP implementation.
Interoperability is more important in a distributed system than portability. IIOP is used in other systems
that do not even attempt to provide the CORBA API. In particular, IIOP is used as the transport protocol
for a version of Java RMI (so called "RMI over IIOP"). Since EJB is defined in terms of RMI, it too can use
IIOP. Various application servers available on the market use IIOP but do not expose the entire CORBA
API. Because they all use IIOP, programs written to these different API's can interoperate with each
other and with programs written to the CORBA API.

Prepared by: Navin Kishor Sharma 5 RMI and CORBA


CORBA Services
Another important part of the CORBA standard is the definition of a set of distributed services to
support the integration and interoperation of distributed objects. As depicted in the graphic below, the
services, known as CORBA Services or COS, are defined on top of the ORB. That is, they are defined as
standard CORBA objects with IDL interfaces, sometimes referred to as "Object Services."

There are several CORBA services. Below is a brief description of each:


Service Description

Object life cycle Defines how CORBA objects are created, removed, moved, and
copied

Naming Defines how CORBA objects can have friendly symbolic names

Events Decouples the communication between distributed objects

Relationships Provides arbitrary typed n-ary relationships between CORBA objects

Externalization Coordinates the transformation of CORBA objects to and from


external media

Transactions Coordinates atomic access to CORBA objects

Concurrency Control Provides a locking service for CORBA objects in order to ensure
serializable access

Property Supports the association of name-value pairs with CORBA objects

Trader Supports the finding of CORBA objects based on properties


describing the service offered by the object

Query Supports queries on objects

CORBA Products
CORBA is a specification; it is a guide for implementing products. Several vendors provide CORBA
products for various programming languages. The CORBA products that support the Java programming
language include:

Prepared by: Navin Kishor Sharma 6 RMI and CORBA


ORB Description

The Java 2 ORB The Java 2 ORB comes with Sun's Java 2 SDK. It is missing
several features.

VisiBroker for Java A popular Java ORB from Inprise Corporation. VisiBroker is also
embedded in other products. For example, it is the ORB that is
embedded in the Netscape Communicator browser.

OrbixWeb A popular Java ORB from Iona Technologies.

WebSphere A popular application server with an ORB from IBM.

Netscape Communicator Netscape browsers have a version of VisiBroker embedded in


them. Applets can issue request on CORBA objects without
downloading ORB classes into the browser. They are already
there.

Various free or shareware ORBs CORBA implementations for various languages are available for
download on the web from various sources.
CORBA pros and cons
CORBA is gaining strong support from developers, because of its ease of use, functionality, and
portability across language and platform. CORBA is particularly important in large organizations, where
many systems must interact with each other, and legacy systems can't yet be retired. CORBA provides
the connection between one language and platform and another - its only limitation is that a language
must have a CORBA implementation written for it. CORBA also appears to have a performance increase
over RMI, which makes it an attractive option for systems that are accessed by users who require real-
time interaction.
Pros Cons
Services can be written in many different Describing services require the use of an interface
languages, executed on many different definition language (IDL) which must be learned.
platforms, and accessed by any language Implementing or using services require an IDL mapping
with an interface definition language (IDL) to your required language - writing one for a language
mapping that isn't supported would take a large amount of work.
With IDL, the interface is clearly separated IDL to language mapping tools create code stubs based
from implementation, and developers can on the interface - some tools may not integrate new
create different implementations based on changes with existing code.
the same interface.
CORBA supports primitive data types, and a CORBA does not support the transfer of objects, or code.
wide range of data structures, as parameters
CORBA is ideally suited to use with legacy The future is uncertain - if CORBA fails to achieve
systems, and to ensure that applications sufficient adoption by industry, then CORBA
written now will be accessible in the future. implementations become the legacy systems.
CORBA is an easy way to link objects and Some training is still required, and CORBA specifications
systems together. are still in a state of flux.

Prepared by: Navin Kishor Sharma 7 RMI and CORBA

You might also like