Java 401
Java 401
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).
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.
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.
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.
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.
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.
• 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];
@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:
• 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];
@Override
public void start(Stage primaryStage) {
[Link]("Simple JavaFX App1");
// Create a button
Button clickMeButton = new Button("Click Me");
// Create a layout pane (StackPane in this case) and add the button and label to
it
StackPane root = new StackPane();
[Link]().addAll(clickMeButton, messageLabel);
package application;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
public void start(Stage primaryStage) {
[Link]("Simple JavaFX App1");
// Create a button
Button clickMeButton = new Button("Click Me");
// 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);
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.
@Override
public void start(Stage primaryStage) {
[Link]("BorderPane Example");
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];
@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");
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.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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");
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:
@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)
4. Use setHgap and setVgap to set the horizontal and vertical gaps between
nodes.
Scene and Stage:
@Override
public void start(Stage primaryStage) {
// Create a Label with text
Label label = new Label("Hello, JavaFX!");
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:
Here are some common properties and methods of the Label class:
Properties:
Methods:
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];
@Override
public void start(Stage primaryStage) {
// Create a Label and a TextField
Label label = new Label("Enter your name:");
TextField textField = new TextField();
[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];
@Override
public void start(Stage primaryStage) {
// Create a Button with a label
Button button = new Button("Click Me!");
• 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];
@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");
[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.
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];
@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");
[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".
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];
@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]
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];
@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");
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];
@Override
public void start(Stage primaryStage) {
// Create a Button
Button button = new Button("Hover Me");
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];
@Override
public void start(Stage primaryStage) {
// Create a FileChooser
FileChooser fileChooser = new FileChooser();
• 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];
@Override
public void start(Stage primaryStage) {
// Create a FileChooser
FileChooser fileChooser = new FileChooser();
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.
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:
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.
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.
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.
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].*;
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
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].*;
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.
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.
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.
//[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){ }
}
}
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.
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 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.
Note: For detailed information about [Link] package refer to the following link
[Link]
//[Link]
<html>
<body>
<center>
//[Link]
import [Link].*;
import [Link].*;
import [Link].*;
output
e = navin
p = 9841
//TestingGet
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
connection=[Link]( "jdbc:mysql://localhost:3306/testingget","root","");
[Link]();
[Link]("firstname",firstName);
[Link]("lastname",surname);
[Link]();
[Link]();
}
catch ( SQLException sqlException )
{
[Link]();
}
try
{
// 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++ )
}//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>
//TestingPost
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [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.
//[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// Create cookie.
Cookie cookie = new Cookie("FirstCookie", data);
Cookie cookie1 = new Cookie("SecondCookie", data1);
//[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [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];
[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 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
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.
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
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
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.
Scripting
JavaServer Pages often present dynamically generated content as part of an XHTML document that is
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
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.
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>
} // end if
else {
} // end else
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.
//[Link]
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LN TECH PVT. LTD</title>
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]"
//[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>
//[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;">
//[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
if ( name != null )
{
%> <%-- end scriptlet to insert fixed template data --%>
<h1>
Hello <%= name %>, <br />
Welcome to LN Tech!
</h1>
} // end if
else {
} // end else
output
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
Network Connection
//[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 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.
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.
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).
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.
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.
Object life cycle Defines how CORBA objects are created, removed, moved, and
copied
Naming Defines how CORBA objects can have friendly symbolic names
Concurrency Control Provides a locking service for CORBA objects in order to ensure
serializable access
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:
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.
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.