0% found this document useful (0 votes)
2 views

java

The document provides an introduction to Java, highlighting its key features such as simplicity, object-oriented design, platform independence, security, and robustness. It discusses the concept of applets, their lifecycle, and the Java AWT (Abstract Window Toolkit) for creating graphical user interfaces, including various controls and event handling mechanisms. Additionally, it includes examples of applet code and explains the structure and functionalities of AWT controls.

Uploaded by

Sujeet
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java

The document provides an introduction to Java, highlighting its key features such as simplicity, object-oriented design, platform independence, security, and robustness. It discusses the concept of applets, their lifecycle, and the Java AWT (Abstract Window Toolkit) for creating graphical user interfaces, including various controls and event handling mechanisms. Additionally, it includes examples of applet code and explains the structure and functionalities of AWT controls.

Uploaded by

Sujeet
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Unit-I.

Introduction to Java

 Features of Java
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are
also some excellent features which play an important role in the popularity of
this language. The features of Java are also known as java buzzwords.

A list of most important features of Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10.Multithreaded
11.Distributed
12.Dynamic

 Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

 Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

 Platform Independent
Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.

There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms,
i.e., Write Once and Run Anywhere(WORA).
 Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)


which is used to load Java classes into the Java Virtual Machine dynamically. It
adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
o Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
Java language provides these securities by default. Some security can also be provided
by an application developer explicitly through SSL, JAAS, Cryptography, etc.

 Robust
Robust simply means strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

 Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.

 Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

 High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.

 Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes us
able to access files by calling the methods from any machine on the internet.

 Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.
 Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage


collection).

 Applet in Java
An applet is a special kind of Java program that runs in a Java enabled browser. This is
the first Java program that can run over the network using the browser. Applet is typically
embedded inside a web page and runs in the browser.
In other words, we can say that Applets are small Java applications that can be accessed
on an Internet server, transported over Internet, and can be automatically installed and
run as apart of a web document.
After a user receives an applet, the applet can produce a graphical user interface. It has
limited access to resources so that it can run complex computations without introducing
the risk of viruses or breaching data integrity.
To create an applet, a class must class extends java.applet.Applet class.
An Applet class does not have any main() method. It is viewed using JVM. The JVM can
use either a plug-in of the Web browser or a separate runtime environment to run an
applet application.
JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.
Note: Java Applet is deprecated since Java 9. It means Applet API is no longer considered
important.

Lifecycle of Java Applet


Following are the stages in Applet

1. Applet is initialized.
2. Applet is started
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
A Simple Applet
import java.awt.*;

import java.applet.*;

public class Simple extends Applet

public void paint(Graphics g)

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

}
Every Applet application must import two packages - java.awt and java.applet.
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the
user (either directly or indirectly) through the AWT. The AWT contains support for a
window-based, graphical user interface. java.applet.* imports the applet package, which
contains the class Applet. Every applet that you create must be a subclass of Applet
class.
The class in the program must be declared as public, because it will be accessed by code
that is outside the program.Every Applet application must declare a paint() method. This
method is defined by AWT class and must be overridden by the applet. The paint()
method is called each time when an applet needs to redisplay its output. Another
important thing to notice about applet application is that, execution of an applet does not
begin at main() method. In fact an applet application does not have any main() method.

Advantages of Applets

1. It takes very less response time as it works on the client side.

2. It can be run on any browser which has JVM running in it.

Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods
that load and play audio clips.

An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.

 init() : init() is the first method to be called. This is where variable are initialized.

This method is called only once during the runtime of applet.


 start() : start() method is called after init(). This method is called to restart an

applet after it has been stopped.

 stop() : stop() method is called to suspend thread that does not need to run

when applet is not visible.

 destroy() : destroy() method is called when your applet needs to be removed

completely from memory.

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

Example of an Applet Skeleton


import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public void init()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop()
{
//suspend execution
{
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}

Example of an Applet

import java.applet.*;

import java.awt.*;

public class MyApplet extends Applet

{
int height, width;

public void init()

height = getSize().height;

width = getSize().width;

setName("MyApplet");

public void paint(Graphics g)

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

 Introduction to Java AWT


Controls
Java AWT controls are the controls that are used to design graphical user
interfaces or web applications. To make an effective GUI, Java provides java.awt
package that supports various AWT controls like Label, Button, CheckBox, CheckBox
Group, List, Text Field, Text Area, Choice, Canvas, Image, Scrollbar, Dialog, File Dialog,
etc that creates or draw various components on web and manage the GUI based
application.
Structure of the Java AWT Controls
The structure of the AWT is quite simple and it is used extensively in programs. Every
AWT inherits controls from the Container Class.

Container Class
It represents objects in graphical representation and it is an abstract class in the GUI
interface.

The following are the list of commonly used UI elements in the GUI or commonly known
as Graphical User Interface.

1. Label
A label is a user for placing text inside the container. A label is used only for inputting
text. The label does not imply that the text can be altered or it can be used as a button
which can be further worked upon.

Syntax:

Label n=new Label("Name:",Label.CENTER);

2. Button
This command generates a button in the User Interface. Clicking on the button would
move the command to another page or another web server which is used to show several
other outputs in the user interface page.

Syntax:

a1=new Button("submit");
a2=new Button("cancel");

3. Checkbox
There can be a certain question and the checkbox is used to determine the true or false
nature of the question being asked. If the checkbox is ticked then it means that the said
question is true which if it is unchecked it means that the said question is false. It is
basically a true or false state in Java programming language.

Syntax:

Checkbox checkbox1 = new Checkbox("Hello World");

4. Checkbox Group
As the name implies the checkbox group is a set of checkboxes that are being
used in the programming language. There are many checkboxes that are being
used and hence the group of checkboxes is known as the checkbox group.
Syntax:

CheckboxGroup cb = new CheckboxGroup();


Checkbox checkBox1 = new Checkbox("Hello", cb, true);
checkBox1.setBounds (100,100, 50,50);

5. List
The list gives a scrolling list of items for the user. The scrolling list of items is also
being set by the user. The user sets the scrolling list of items such as Fruits,
Vegetables, some questionnaire or other facts.

Syntax:

List l1=new List(4);


l1.setBounds(100,100, 75,75);

6. Text Field
A text field is used for the editing of a particular line of text which can be used within the
programming concept.

Syntax:

na=new TextField(20);

7. Text Area
A text area is used for the editing of multiple lines of text. The only difference between
the Text field and Text area is that Text Field is used for editing a single line of text
within the user interface while a Text Area is used for editing multiple lines of text.

Syntax:

TextArea area=new TextArea("Welcome to the universe");


area.setBounds(10,30, 300,300);

8. Choice
A choice, as the name implies, shows the various options and the choice that is selected
is shown in the top menu bar of the screen.

Syntax:

Choice c=new Choice();


c.setBounds(100,100, 75,75);
c.add("Subject 1");
c.add("Subject 2");
c.add("Subject 3");
c.add("Subject 4");
c.add("Subject 5");

9. Canvas
In the canvas space, there can be an input being given by the user or the user can draw
something on the Canvas space being given.

Syntax:

f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);

10. Image
There can be a single image or multiple images within a UI. There can be a button being
associated with an image and when it is clicked it can produce some functionality.

Syntax:

Image i=t.getImage("pic2.gif");

11. Scroll Bar


The scroll bar like a normal one is used to scroll or move from a varied range of values.
The user selects one value from those range of values.

Syntax:

Scrollbar s=new Scrollbar();


s.setBounds(100,100, 50,100);

12. Dialog
The dialog is used to take some form of input from the user and produce it in a
sequential manner.

Syntax:
d = new Dialog(f , "Hello World", true);

13. File Dialog


From a file dialog, a user can select a file which he/she wishes to use.

Syntax:

FileDialog(Dialog parent)

 Java GUI Event Handling


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

Components of Event Handling


Event handling has three main components,

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


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified
when an event occurs.

How Events are handled?


A source generates an Event and send it to one or more listeners registered with
the source. Once event is received by the listener, they process the event and
then return. Events are supported by a number of Java packages,
like java.util, java.awt and java.awt.event.

Important Event Classes and Interface


Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu- ActionListener


item is selected, list-item is double clicked
MouseEvent generated when mouse is dragged, MouseListener
moved,clicked,pressed or released and
also when it enters or exit a component

KeyEvent generated when input is received from KeyListener


keyboard

ItemEvent generated when check-box or list item is ItemListener


clicked

TextEvent generated when value of textarea or TextListener


textfield is changed

MouseWheelEven generated when mouse wheel is moved MouseWheelListener


t

WindowEvent generated when window is activated, WindowListener


deactivated, deiconified, iconified, opened
or closed

ComponentEvent generated when component is hidden, ComponentEventListene


moved, resized or set visible r

ContainerEvent generated when component is added or ContainerListener


removed from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or FocusListener


loses keyboard focus

Steps to handle events:


1. Implement appropriate interface in the class.
2. Register the component with the listener.

Example of Event Handling


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

public class Test extends Applet implements KeyListener


{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
HTML code:

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

</applet>

 Multithreading in java with examples


A thread is a light-weight smallest part of a process that can run concurrently
with the other parts(other threads) of the same process. Threads are
independent because they all have separate path of execution that’s the reason
if an exception occurs in one thread, it doesn’t affect the execution of other
threads. All threads of a process share the common memory. The process of
executing multiple threads simultaneously is known as multithreading.

Let’s summarize the discussion in points:.

1. The main purpose of multithreading is to provide simultaneous execution of


two or more parts of a program to maximum utilize the CPU time. A
multithreaded program contains two or more parts that can run concurrently.
Each such part of a program called thread .
2. Threads are lightweight sub-processes, they share the common memory
space. In Multithreaded environment, programs that are benefited from
multithreading, utilize the maximum CPU time so that the idle time can be kept
to minimum.

3. A thread can be in one of the following states:


NEW – A thread that has not yet started is in this state.
RUNNABLE – A thread executing in the Java virtual machine is in this state.
BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.
WAITING – A thread that is waiting indefinitely for another thread to perform a particular
action is in this state.
TIMED_WAITING – A thread that is waiting for another thread to perform an action for up
to a specified waiting time is in this state.
TERMINATED – A thread that has exited is in this state.
A thread can be in only one state at a given point in time.

Creating a thread in Java


There are two ways to create a thread in Java:
1) By extending Thread class.
2) By implementing Runnable interface.

Before we begin with the programs(code) of creating threads, let’s have a look at
these methods of Thread class. We have used few of these methods in the
example below.

 getName(): It is used for Obtaining a thread’s name


 getPriority(): Obtain a thread’s priority
 isAlive(): Determine if a thread is still running
 join(): Wait for a thread to terminate
 run(): Entry point for the thread
 sleep(): suspend a thread for a period of time
 start(): start a thread by calling its run() method

Method 1: Thread creation by extending Thread


class
Example 1:

class MultithreadingDemo extends Thread{


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
Output:
My thread is in running state.

 Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.

We can perform file handling in Java by Java I/O API.

Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with
the console.

1) System.out: standard output stream


2) System.in: standard input stream
3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

System.out.println("simple message");
System.err.println("error message");

Let's see the code to get input from console.

int i=System.in.read();//returns ASCII code of 1st character


System.out.println((char)i);//will print the character

OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:

OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given
below.

OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some
sink.

Swing
Swing is the collection of user interface components for the Java programs. It is
part of Java foundation classes that are referred to as JFC. In simple words, Swing
is the graphical user interface toolkit that is used for developing the windows
based java applications or programs. Swing is the successor of AWT which is
known as Abstract window toolkit API for Java and AWT components are a mainly
heavyweight.

The components are lightweight as compared to AWT components. It provides a


good interface to the user for all the platforms. It is not specifically for one
platform. The components are written in Java and platform independent as well.
The Java foundation classes were first appeared in 1997 and then later on it is
termed as Swing. To use the swing in java, javax. swing package needs to be
used or import. It is also known as Java Swing

 Features of Swing
The features of the Swing are as follows:

1. Platform Independent: It is platform independent, the swing components


that are used to build the program are not platform specific. It can be used at
any platform and anywhere.

2. Lightweight: Swing components are lightweight which helps in creating the


UI lighter. Swings component allows it to plug into the operating system user
interface framework that includes the mappings for screens or device and other
user interactions like key press and mouse movements.
3. Plugging: It has a powerful component that can be extended to provide the
support for the user interface that helps in good look and feel to the application.
It refers to the highly modular-based architecture that allows it to plug into other
customized implementations and framework for user interfaces. Its components
are imported through a package called java.swing.

4. Manageable: It is easy to manage and configure. Its mechanism and


composition pattern allows changing the settings at run time as well. The
uniform changes can be provided to the user interface without doing any
changes to application code.

5. MVC: They mainly follows the concept of MVC that is Model View Controller.
With the help of this, we can do the changes in one component without
impacting or touching other components. It is known as loosely coupled
architecture as well.

6. Customizable: Swing controls can be easily customized. It can be changed


and the visual appearance of the swing component application is independent of
its internal representation.

Examples of Swing
The component class is mainly used and there are some of the methods that are
frequently used like adding a component in another component (add
(Component a)), setting the size, layout, and visibility of components
accordingly.

Below is the examplee:

import javax.swing.*;
public class Test extends JFrame {
public Test() {
super("Test");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(new JLabel("Test, Application!"));
pack();
setVisible(true);
}
public static void main(final String[] args) {
new Test();
}
}
Difference between Swing and AWT
The difference between Swing and AWT are as follow:

Basic SWING AWT


Comparison

Architecture It follows the Model view controller It doesn’t follow the model view
architecture. architecture.

UI It does support Pluggable look and It doesn’t support pluggable look


feel for UI and feel

Components It has a lot of components to provide It has fewer components as


for UI. compared to Swing.

Independent It is platform Independent. It is platform dependent.

Weight Its components are lightweight Its components are heavyweight.

Speed If components are more used, it can Its speed would be normal if
be slow. components are used more.

Swing Components in Java


Swing components are the basic building blocks of an application. We know that
Swing is a GUI widget toolkit for Java. Every application has some basic
interactive interface for the user. For example, a button, check-box, radio-button,
text-field, etc. These together form the components in Swing.

So, to summarise, Swing components are the interactive elements in


a Java application. We will see various Swing Components in this article and see
a few examples. Note that the examples are simple code snippets. You can use
them in your application and tailor them to suit your application architecture.

Top 13 Components of Swing in Java


Below are the different components of swing in java:

1. ImageIcon
The ImageIcon component creates an icon sized-image from an image residing
at the source URL.
Example:

ImageIcon homeIcon = new ImageIcon(“src/images/home.jpg”);

This returns an icon of a home button. The string parameter is the path at which
the source image is present.

Note: We would be using this image icon in further examples.


2. JButton
JButton class is used to create a push-button on the UI. The button can contain
some display text or image. It generates an event when clicked and double-
clicked. A JButton can be implemented in the application by calling one of its
constructors.

Example:

JButton okBtn = new JButton(“Ok”);


This constructor returns a button with text Ok on it.
JButton homeBtn = new JButton(homeIcon);
It returns a button with a homeIcon on it.
JButton btn2 = new JButton(homeIcon, “Home”);

It returns a button with the home icon and text Home.


3. JLabel
JLabel class is used to render a read-only text label or images on the UI. It does
not generate any event.

Example:

JLabel textLbl = new JLabel(“This is a text label.”);


This constructor returns a label with text.
JLabel imgLabel = new JLabel(homeIcon);
It returns a label with a home icon.

4. JTextField
JTextField renders an editable single-line text box. A user can input non-
formatted text in the box. To initialize the text field, call its constructor and pass
an optional integer parameter to it. This parameter sets the width of the box
measured by the number of columns. It does not limit the number of characters
that can be input in the box.

Example:

JTextField txtBox = new JTextField(20);

It renders a text box of 20 column width.


5. JTextArea
JTextArea class renders a multi-line text box. Similar to the JTextField, a user can
input non-formatted text in the field. The constructor for JTextArea also expects
two integer parameters which define the height and width of the text-area in
columns. It does not restrict the number of characters that the user can input in
the text-area.

Example:

JTextArea txtArea = new JTextArea(“This text is default text for text area.”, 5,
20);

The above code renders a multi-line text-area of height 5 rows and width 20
columns, with default text initialized in the text-area.

6. JPasswordField
JPasswordField is a subclass of JTextField class. It renders a text-box that masks
the user input text with bullet points. This is used for inserting passwords into
the application.

Example:

JPasswordField pwdField = new JPasswordField(15);


var pwdValue = pwdField.getPassword();

It returns a password field of 15 column width. The getPassword method gets the
value entered by the user.

7. JCheckBox
JCheckBox renders a check-box with a label. The check-box has two states –
on/off. When selected, the state is on and a small tick is displayed in the box.

Example:

CheckBox chkBox = new JCheckBox(“Show Help”, true);

It returns a checkbox with the label Show Help. Notice the second parameter in
the constructor. It is a boolean value that indicates the default state of the
check-box. True means the check-box is defaulted to on state.

8. JRadioButton
JRadioButton is used to render a group of radio buttons in the UI. A user can
select one choice from the group.

Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton(“Easy”, true);
JRadioButton rb2 = new JRadioButton(“Medium”);
JRadioButton rb3 = new JRadioButton(“Hard”);
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);

The above code creates a button group and three radio button elements. All
three elements are then added to the group. This ensures that only one option
out of the available options in the group can be selected at a time. The default
selected option is set to Easy.

9. JList
JList component renders a scrollable list of elements. A user can select a value or
multiple values from the list. This select behavior is defined in the code by the
developer.

Example:

DefaultListItem cityList = new DefaultListItem();


cityList.addElement(“Mumbai”):
cityList.addElement(“London”):
cityList.addElement(“New York”):
cityList.addElement(“Sydney”):
cityList.addElement(“Tokyo”):
JList cities = new JList(cityList);
cities.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);

The above code renders a list of cities with 5 items in the list. The selection
restriction is set to SINGLE_SELECTION. If multiple selections is to be allowed, set
the behavior to MULTIPLE_INTERVAL_SELECTION.

10. JComboBox
JComboBox class is used to render a dropdown of the list of options.

Example:

String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo" };


JComboBox cities = new JComboBox(cityList);
cities.setSelectedIndex(3);

The default selected option can be specified through the setSelectedIndex


method. The above code sets Sydney as the default selected option.
11. JFileChooser
JFileChooser class renders a file selection utility. This component lets a user
select a file from the local system.

Example:

JFileChooser fileChooser = new JFileChooser();


JButton fileDialogBtn = new JButton(“Select File”);
fileDialogBtn.AddEventListner(new ActionListner(){
fileChooser.showOpenDialog();
})
var selectedFile = fileChooser.getSelectedFile();

The above code creates a file chooser dialog and attaches it to the button. The
button click would open the file chooser dialog. The selected file is returned
through the getSelectedFile method.

12. JTabbedPane
JTabbedPane is another very useful component that lets the user switch between
tabs in an application. This is a highly useful utility as it lets the user browse
more content without navigating to different pages.

Example:

JTabbedPane tabbedPane = new JTabbedPane();


tabbedPane.addTab(“Tab 1”, new JPanel());
tabbedPane.addTab(“Tab 2”, new JPanel());

The above code creates a two tabbed panel with headings Tab 1 and Tab 2.

13. JSlider
JSlider component displays a slider which the user can drag to change its value.
The constructor takes three arguments – minimum value, maximum value, and
initial value.

Example:

JSlider volumeSlider = new JSlider(0, 100, 50);


var volumeLevel = volumeSlider.getValue();

The above code creates a slider from 0 to 100 with an initial value set to 50. The
value selected by the user is returned by the getValue method.
SWING - Containers
Containers are an integral part of SWING GUI components. A container provides
a space where a component can be located. A Container in AWT is a component
itself and it provides the capability to add a component to itself. Following are
certain noticable points to be considered.
 Sub classes of Container are called as Container. For example, JPanel,
JFrame and JWindow.
 Container can add only a Component to itself.
 A default layout is present in each container which can be overridden
using setLayout method.
SWING Containers
Following is the list of commonly used containers while designed GUI using
SWING.

Sr.No. Container & Description

Panel
1
JPanel is the simplest container. It provides space in which any other
component can be placed, including other panels.

Frame
2
A JFrame is a top-level window with a title and a border.

Window
3
A JWindow object is a top-level window with no borders and no menubar.

 Swing Controls

Swing controls are playing major role in swing applications, every application
will have some components and their corresponding event listener. Swing
controls will inherit the properties from following classes.

 Component
 Container
 JComponent.

 Component: A component is an object having a graphical


representation that can be displayed on the screen and that can
interact with the user. Examples of components are the buttons,
checkboxes, and scrollbars of a typical graphical user interface.
 Container: Container is the component that can handle other
components, following is the syntax to this container.
public class Container
extends Component
 JComponent:JComponents will have special functionalities, every
component has to inherit the properties
from JComponent.

Following are the regularly using controls in Swing,

JLabel
JCheckBox
JComboBox

JProgressBar
JToggleButton
JSlider

 Swing Controls – protected Component() is utilized to create new component.


 Swing Controls – The container will hold another containers.

 JDialog with examples


JDialog is a part Java swing package. The main purpose of the dialog is to add
components to it. JDialog can be customized according to user need .
Constructor of the class are:
1. JDialog() : creates an empty dialog without any title or any specified owner
2. JDialog(Frame o) :creates an empty dialog with a specified frame as its
owner
3. JDialog(Frame o, String s) : creates an empty dialog with a specified
frame as its owner
and a specified title
4. JDialog(Window o) : creates an empty dialog with a specified window as
its owner
5. JDialog(Window o, String t) : creates an empty dialog with a specified
window as its owner and specified title.
6. JDialog(Dialog o) :creates an empty dialog with a specified dialog as its
owner
7. JDialog(Dialog o, String s) : creates an empty dialog with a specified
dialog as its owner and specified title.

Commonly used methods


1. setLayout(LayoutManager m) : sets the layout of the dialog to specified layout
manager
2. setJMenuBar(JMenuBar m) : sets the menubar of the dialog to specified
menubar
3. add(Component c): adds component to the dialog
4. isVisible(boolean b): sets the visibility of the dialog, if value of the boolean is
true then visible else invisible
5. update(Graphics g) : calls the paint(g) function
6. remove(Component c) : removes the component c
7. getGraphics() : returns the graphics context of the component.
8. getLayeredPane() : returns the layered pane for the dialog
9. setContentPane(Container c) :sets the content pane for the dialog
10.setLayeredPane(JLayeredPane l) : set the layered pane for the dialog
11.setRootPane(JRootPane r) : sets the rootPane for the dialog
12.getJMenuBar() : returns the menubar of the component
13.setTransferHandler(TransferHandler n) : Sets the transferHandler
property, which is a mechanism to support transfer of data into this
component.
14.setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls
to add and setLayout are forwarded to the contentPane.
15.setRootPane(JRootPane root) :Sets the rootPane property of the dialog.
16.setGlassPane(Component glass) : Sets the glassPane property of the
dialog.
17.repaint(long time, int x, int y, int width, int height): Repaints the
specified rectangle of this component within time milliseconds.
18.remove(Component c): Removes the specified component from the
dialog.
19.isRootPaneCheckingEnabled() : Returns whether calls to add and
setLayout are forwarded to the contentPane or not .
20.getTransferHandler() : returns the transferHandler property.
21.getRootPane() : Returns the rootPane object for this dialog.
22.getGlassPane() : Returns the glassPane object for this dialog.
23.createRootPane() : Called by the constructor methods to create the
default rootPane.
24.addImpl(Component co, Object c, int i) : Adds the specified child
Component to the dialog.
The following programs will illustrate the use of JDialog
1 .Program to create a simple JDialog

// java Program to create a simple JDialog


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame implements ActionListener {

// frame
static JFrame f;

// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");

// create a object
solve s = new solve();

// create a panel
JPanel p = new JPanel();

JButton b = new JButton("click");

// add actionlistener to button


b.addActionListener(s);

// add button to panel


p.add(b);

f.add(p);

// set the size of frame


f.setSize(400, 400);

f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("click")) {
// create a dialog Box
JDialog d = new JDialog(f, "dialog Box");

// create a label
JLabel l = new JLabel("this is a dialog box");

d.add(l);

// setsize of dialog
d.setSize(100, 100);

// set visibility of dialog


d.setVisible(true);
}
}
}
25. Output:

Swing Slider
slider is normally constructed by a JSlider component. JSlider is a component
that lets the users select a value by sliding a knob within a specified interval. For
the knob, it always points to the point which matches the integer values within
the interval.
For JSlider , six different constructors can be used:
 JSlider(): creates a horizontal slider ranging from 0 to 100 with the initial value
to be 50.
 JSlider(BoundedRangeModel brm): creates a horizontal slider using the
specified BounedRangeModel.
 JSlider(int orientation): creates a slider using the specified orientation ranging
from 0 to 100, with the initial value to be 50.
 JSlider(int min, int max): creates a slider using the specified min and max
value, with a initial value equals to the average of the min plus the max.
 JSlider(int min, int max, int value): creates a horizontal slider using the
specified min, max and the initial value.
 JSlider(int orientation, int min, int max, int value): very similar to the above
one, with the orientation specified.
 The code above could be summarized in the
code simpleSliderExample.java below:.

simpleSliderExample.java
package javaCodeGeeks;

import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import java.util.Hashtable;

/*
* A simple swing slider example with different constructors
*/

public class simpleSliderExample {

public static void main(String[] args) {


// Create and set up a frame window
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JSlider setting examples");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Set the panel to add buttons


JPanel panel = new JPanel();

// Different settings on the sliders


JSlider slider = new JSlider();
// JSlider slider = new JSlider(JSlider.VERTICAL);
// JSlider slider = new JSlider(-100, 100, 50);
// JSlider slider = new JSlider(JSlider.VERTICAL, -100, 100, 50);

// Set the slider with the DefaultBoundedRangeModel


//DefaultBoundedRangeModel model = new DefaultBoundedRangeModel(20, 0, 1, 100);
//JSlider slider = new JSlider(model);

// Set major or minor ticks for the slider


slider.setMajorTickSpacing(25);
slider.setMinorTickSpacing(10);
slider.setPaintTicks(true);

// Set the labels to be painted on the slider


slider.setPaintLabels(true);

// Add positions label in the slider


Hashtable position = new Hashtable();
position.put(0, new JLabel("0"));
position.put(25, new JLabel("25"));
position.put(50, new JLabel("50"));
position.put(75, new JLabel("75"));
position.put(100, new JLabel("100"));

// Set the label to be drawn


slider.setLabelTable(position);

// Add the slider to the panel


panel.add(slider);

// Set the window to be visible as the default to be false


frame.add(panel);
frame.pack();
frame.setVisible(true);

}
}
 JProgressBar
JProgressBar is a part of Java Swing package. JProgressBar visually displays the
progress of some specified task. JProgressBar shows the percentage of
completion of specified task.The progress bar fills up as the task reaches it
completion. In addition to show the percentage of completion of task, it can also
display some text .
Constructors of JProgressBar :
1. JProgressBar() : creates an progress bar with no text on it;
2. JProgressBar(int orientation) : creates an progress bar with a specified
orientation. if SwingConstants.VERTICAL is passed as argument a vertical
progress bar is created, if SwingConstants.HORIZONTAL is passed as
argument a horizontal progress bar is created.
3. JProgressBar(int min, int max) : creates an progress bar with specified
minimum and maximum value.
4. JProgressBar(int orientation, int min, int max) : creates an progress bar with
specified minimum and maximum value and a specified orientation.if
SwingConstants.VERTICAL is passed as argument a vertical progress bar is
created, if SwingConstants.HORIZONTAL is passed as argument a horizontal
progress bar is created.

Commonly used methods of JProgressBar are :


1. int getMaximum() : returns the progress bar’s maximum value.
2. int getMinimum() : returns the progress bar’s minimum value.
3. String getString() : get the progress bar’s string representation of current value.
4. void setMaximum(int n) : sets the progress bar’s maximum value to the value n.
5. void setMinimum(int n) : sets the progress bar’s minimum value to the value n.
6. void setValue(int n) : set Progress bar’s current value to the value n.
7. void setString(String s) : set the value of the progress String to the String s.

1. Program to create a simple progress bar


filter_none
edit
play_arrow
brightness_4
// Java Program to create a
// simple progress bar
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class progress extends JFrame {

// create a frame
static JFrame f;

static JProgressBar b;

public static void main()


{
// create a frame
f = new JFrame("ProgressBar demo");

// create a panel
JPanel p = new JPanel();

// create a progressbar
b = new JProgressBar();

// set initial value


b.setValue(0);

b.setStringPainted(true);

// add progressbar
p.add(b);

// add panel
f.add(p);

// set the size of the frame


f.setSize(500, 500);
f.setVisible(true);

fill();
}

// function to increase progress


public static void fill()
{
int i = 0;
try {
while (i <= 100) {
// fill the menu bar
b.setValue(i + 10);

// delay the thread


Thread.sleep(1000);
i += 20;
}
}
catch (Exception e) {
}
}
}
OUTPUT :

Java Swing | JTable


The JTable class is a part of Java Swing Package and is generally used to display
or edit two-dimensional data that is having both rows and columns. It is similar to
a spreadsheet. This arranges data in a tabular form.
Constructors in JTable:
1. JTable(): A table is created with empty cells.
2. JTable(int rows, int cols): Creates a table of size rows * cols.
3. JTable(Object[][] data, Object []Column): A table is created with the
specified name where []Column defines the column names.
Functions in JTable:
1. addColumn(TableColumn []column) : adds a column at the end of the
JTable.
2. clearSelection() : Selects all the selected rows and columns.
3. editCellAt(int row, int col) : edits the intersecting cell of the column
number col and row number row programmatically, if the given indices are
valid and the corresponding cell is editable.
4. setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’
for the position row, col in the JTable.

Below is the program to illustrate the various methods of JTable:

filter_none
edit
play_arrow
brightness_4
// Packages to import
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class JTableExamples {


// frame
JFrame f;
// Table
JTable j;

// Constructor
JTableExamples()
{
// Frame initiallization
f = new JFrame();

// Frame Title
f.setTitle("JTable Example");

// Data to be displayed in the JTable


String[][] data = {
{ "Kundan Kumar Jha", "4031", "CSE" },
{ "Anand Jha", "6014", "IT" }
};

// Column Names
String[] columnNames = { "Name", "Roll Number", "Department" };

// Initializing the JTable


j = new JTable(data, columnNames);
j.setBounds(30, 40, 200, 300);

// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
// Frame Size
f.setSize(500, 200);
// Frame Visible = true
f.setVisible(true);
}

// Driver method
public static void main(String[] args)
{
new JTableExamples();
}
}
Output:

Swing: User Interfaces in Java


Swing and user interface packages
Many of the Swing classes representing windows, lists, buttons etc live in
the javax.swing package and subpackages. The names of most Swing classes
start with the letter J: JFrame, JPanel, JButton, JList etc. In general, if you're
looking for the class that represents some visual component in Swing, its name
will start with J.
A few classes also live in the java.awt package and subpackages. AWT stands
for Abstract Window Toolkit and was in some sense the precursor to Swing.
AWT provides a bare-bones way of creating a user interface, based directly on
"native" user interface components of the operating system. Swing actually
builds on AWT, and some AWT classes are still used directly in Swing
programming. For example, many of the classes responsible for laying out user
interface components lie inside the java.awt package, and many classes to do
with handling events live in java.awt.event; the Graphics interface, which
represents a graphics context and is key to rendering graphics inside a window
or component, is also originally part of the AWT package.

Example: a first Swing application


By way of a vary basic example which we will extent on the next page, the following
application displays a window:

import javax.swing.JFrame;

public class MyApp {


public static void main(String[] args) {
// Actually slightly incorrect from a threading point of view
JFrame frame = new JFrame("My Swing app");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

The lines that arguably do most of the work are the ones in bold which construct
the window, specifically an instance of JFrame, and then make it visible. We
mentioned that user interface components are generally represented by classes
inside the javax.swing package with names beginning with J. In this case, a
"window with decorations" is strictly speaking called a frame, and represented by
the JFrame class. So creating a window means creating an instance of JFrame.
We construct one just like most Java objects: by calling its constructor. Note that,
as with many constructors, most allow us to specify some common parameters:
in this case, the title of the window.
The call to set the size of the window is hopefully self-explanatory once you see
it; let us just comment for now that in general, you need to think about the size
(and potentially layout) of all windows/components when you're programming
with Swing. The call to setDefaultCloseOperation() is a shortcut we can use in the
very simple case where we want our application to exit when the window is
closed: Swing will dutifully call System.exit() for us. We'll see later that we can
customise what happens when a window is closed.

Unit-2. Java Database Connectivity

 JDBC connectivity model,


JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language
and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.

 java.sql package
The java.sql package provides the API for accessing and processing data stored
in a data source (usually a relational database) using the Java programming
language. This API includes a framework whereby different drivers can be
installed dynamically to access different data sources. Although the JDBC API is
mainly geared to passing SQL statements to a database, it provides for reading
and writing data from any data source with a tabular format. The reader/writer
facility, available through the javax.sql.RowSet group of interfaces can be
customized to use and update data from a spreadsheet, flat file, or any other
tabular data source.

 What the java.sql Package Contains

The java.sql package contains API for the following:


1. Making a connection with a database via the DriverManager facility

 DriverManager class -- makes a connection with a driver


 SQLPermission class -- provides permission when code running within a Security
Manager, such as an applet, attempts to set up a logging stream through the
DriverManager
 Driver interface -- provides the API for registering and connecting drivers based on
JDBC technology ("JDBC drivers"); generally used only by the DriverManager class
 DriverPropertyInfo class -- provides properties for a JDBC driver; not used by the
general user
2. Sending SQL statements to a database

 Statement -- used to send basic SQL statements


 PreparedStatement -- used to send prepared statements or basic SQL statements
(derived from Statement)
 CallableStatement -- used to call database stored procedures (derived from
PreparedStatement)
 Connection interface -- provides methods for creating statements and managing
connections and their properties
 Savepoint -- provides savepoints in a transaction
3. Retrieving and updating the results of a query

 ResultSet interface
4. Standard mappings for SQL types to classes and interfaces in the Java
programming language

 Array interface -- mapping for SQL ARRAY


 Blob interface -- mapping for SQL BLOB
 Clob interface -- mapping for SQL CLOB
 Date class -- mapping for SQL DATE
 NClob interface -- mapping for SQL NCLOB
 Ref interface -- mapping for SQL REF
 RowId interface -- mapping for SQL ROWID
 Struct interface -- mapping for SQL STRUCT
 SQLXML interface -- mapping for SQL XML
 Time class -- mapping for SQL TIME
 Timestamp class -- mapping for SQL TIMESTAMP
 Types class -- provides constants for SQL types
5. Custom mapping an SQL user-defined type (UDT) to a class in the Java
programming language

1. SQLData interface -- specifies the mapping of a UDT to an instance of this class


2. SQLInput interface -- provides methods for reading UDT attributes from a stream
3. SQLOutput interface -- provides methods for writing UDT attributes back to a
stream
6. Metadata

 DatabaseMetaData interface -- provides information about the database


 ResultSetMetaData interface -- provides information about the columns of a
ResultSet object
 ParameterMetaData interface -- provides information about the parameters to
PreparedStatement commands
7. Exceptions

 SQLException -- thrown by most methods when there is a problem accessing data


and by some methods for other reasons
 SQLWarning -- thrown to indicate a warning
 DataTruncation -- thrown to indicate that data may have been truncated
 BatchUpdateException -- thrown to indicate that not all commands in a batch
update executed successfully
 JDBC Exception
JDBC Exception
The Exception are the set of condition that occurred when an abnormal condition
try to interrupt the normal flow of the code during the execution of program.
Exception Occurred in JDBC Connectivity when a connection object do not find a
suitable driver to connect a url-database.
Understand with Example
The Tutorial illustrates an example from JDBC Exception. In this Tutorial we want
to describe you a code that show an exception in JDBC.For this we have a class
JdbcException.
The first step is to import a package name java.sql include a definition for all
the classes that provides you network interface to communicate between front
end and back end application. The next is to load the driver by calling class. for
name( ) with driver class passed as argument.
Driver.getConnection ( ) : This is used to built connection between url and
database. In case there is an exception in try block, the subsequent catch block
caught and handle the exception, The exception show you no suitable driver is
found.
con.create Statement ( ) : This is used to create a Sql object. An sql object is
used to send and execute the query in backend database.
executeQuery ( ): This is used to return the result set obtained from the
record set of the database. The select statement is used to retrieve the result set
from the database.
In this program code, the exception occurred in try block, therefore the
subsequent catch block show the exception that a suitable driver do not found
using print ln.Once the suitable driver is found the print ln print and display the
element of no,name,id and dob.
rs.getString ( ) -The Result set object call a get String ( ),returns you a record
set into a formatted string element.

JdbcExceptions.java

import java.sql.*;

public class JdbcExceptions {

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

Connection con = null;


Statement st = null;
ResultSet rs = null;

String url = new String();


String db = new String();
String driver = "com.mysql.jdbc.Driver";
String user = new String();
String pass = new String();

Class.forName(driver);

try {
con = DriverManager.getConnection(url + db, user, pass);
} catch (Exception e) {
System.err.println(e);

url = "jdbc:mysql://localhost:3306/";
db = "komal";
user = "root";
pass = "root";

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


con.setAutoCommit(false);
st = con.createStatement();

String sql = "select * from person";


rs = st.executeQuery(sql);

System.out.println("no. \tName \tDob");


while (rs.next()) {
System.out.print(rs.getString("id") + " \t");
System.out.print(rs.getString("cname") + " \t");
System.out.println(rs.getDate("dob"));
}
}
}
}

Output

java.sql.SQLException: No suitable driver


found for
no. Name Dob
1 Girish 1984-06-02
2 komal 1984-10-27

 Introduction to Java Database


Connectivity
Using JDBC to connect to a database

The steps for connecting to a database with JDBC are as follows:

1. Install or locate the database you want to access.


2. Include the JDBC library.
3. Ensure the JDBC driver you need is on your classpath.
4. Use the JDBC library to obtain a connection to the database.
5. Use the connection to issue SQL commands.
6. Close the connection when you're finished.

We'll go through these steps together.

Step 1. Download and install SQLite


SQLite is a very compact database. It isn't intended for production use, but is a
great choice for quickly trying things out. SQLite uses a file as its functional
database, without requiring any service or daemon installations.

To get started with this demo, go ahead and download the SQLite sample
database. Unzip the .db file and save it somewhere you won't forget.

This file contains both a functional file-based database and sample schema and
data we can use.

Step 2. Import JDBC Into your Java application


We could do our coding in an IDE, but coding directly in a text editor will better
demonstrate JDBC's simplicity. To begin, you will need to have a compatible JDK
installation for your operating system.

Assuming you have the Java platform developer tools installed, we can start by
creating a simple Java program. In your text editor, paste in the code shown in
Listing 1. Call this file WhatIsJdbc.java.

Listing 1. A simple Java program

class WhatIsJdbc{
public static void main(String args[]){
System.out.println("Hello JavaWorld");
}
}
Now compile the code by entering the command: javac
WhatIsJdbc.java. Compiling will output the WhatIsJdbc.class file.
Execute this file from the command line with the call: java WhatIsJdbc.

Listing 2. JDBC imports


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
Each of these imports provides access to a class that facilitates the
standard Java database connection:

 Connection represents the connection to the database.


 DriverManager obtains the connection to the database. (Another option
is DataSource, used for connection pooling. )
 SQLException handles SQL errors between the Java application and the database.
 ResultSet and Statement model the data result sets and SQL statements.

We'll see each of these in action shortly.

Step 3. Add the JDBC driver to your classpath


Next, you'll add the SQLite driver to your classpath. A JDBC driver is a class that
implements the JDBC API for a specific database.

Download the SQLite driver from GitHub. Be sure to get the most recent .jar file
and store it somewhere you'll remember.

The next time you execute your Java program, you will pull that .jar file in via the
classpath. There are several ways to set the classpath. Listing 3 shows how to do
it using a command-line switch.

Listing 3. Executing SQLite driver on the Java classpath

java.exe -classpath /path-to-driver/sqlite-jdbc-3.23.1.jar:.


WhatIsJdbc

Step 4. Obtain a database connection


The classpath now has access to the driver. Now, change your simple Java
application file to look like the program in Listing 4.

Listing 4. Using the JDBC Connection class to connect to SQLite

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

class WhatIsJdbc{
public static void main(String[] args) {
Connection conn = null;
try {
String url = "jdbc:sqlite:path-to-db/chinook/chinook.db";
conn = DriverManager.getConnection(url);

System.out.println("Got it!");

} catch (SQLException e) {
throw new Error("Problem", e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
}

Step 5. Query the database


With the live connection object in hand, we can do something useful, like
querying the database. Listing 5 shows how to query SQLite using the
JDBC Connection and Statement objects.

Listing 5. Querying the database with JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

class WhatIsJdbc{
public static void main(String[] args) {
Connection conn = null;
try {
String url = "jdbc:sqlite:path-to-db-file/chinook/chinook.db";
conn = DriverManager.getConnection(url);

Statement stmt = null;


String query = "select * from albums";
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString("title");
System.out.println(name);
}
} catch (SQLException e ) {
throw new Error("Problem", e);
} finally {
if (stmt != null) { stmt.close(); }
}

} catch (SQLException e) {
throw new Error("Problem", e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
}

In Listing 5 we use our Connection object to obtain


a Statement object: conn.createStatement(). We then use this
object to execute an SQL query: stmt.executeQuery(query).

The executeQuery command returns a ResultSet object, which we


then use to iterate over the data with while (rs.next()). In this
example, you should see the album titles we've queried on as
output.

Listing 6. Using JDBC PreparedStatements

String prepState = "insert into albums values (?, ?);";

PreparedStatement prepState =
connection.prepareStatement(sql);

prepState.setString(1, "Uprising");
prepState.setString(2, "Bob Marley and the Wailers ");

int rowsAffected = preparedStatement.executeUpdate();

PreparedStatement replaces Statement's hard-coded values with


question marks (?). Using PreparedStatements optimizes your
code for reuse: a PreparedStatement is compiled only once, and
can then be reused with a variety of parameters. As your code base
grows, you simply insert new values into the statement, instead of
hacking the string object itself.

 Manipulating a Database with JDBC


Java programs communicate with the database and manipulate its data with the
help of the JDBC API. The JDBC driver enables the Java application to connect to a
database. JDBC is almost always used with relational databases, also it can be
used with any other table based data source. We do not have to worry about the
availability of a driver, as major RDBMS (Relational Database Management
System) providers provide them free. Apart from that there are many third-party
JDBC drivers available.

Basic Requirements
Since we shall be going hands on down the line, the basic software requirements for JDBC
programming are as follows.

1.Java SDK
2.RDBMS Package (For example, MySQL, Oracle, PostgreSQL, etc.)
3.IDE (For example, Eclipse, NetBeans, JDeveloper, etc.)
4.JDBC driver (JDBC drivers are database specific, especially, if we use a driver
other than Type1:JDBC-ODBC Bridge. For example, MySQL Connector/J is the
official JDBC driver for MySQL, ojdbc for Oracle and so on...PostgreSQL JDBC
Driver)

Installation is pretty straightforward; if in doubt, refer to the appropriate installation instruction


of the relevant packages during installation.

 Navigation Model
The JavaServer Faces navigation model makes it easy to define page navigation
and to handle any additional processing that is needed to choose the sequence
in which pages are loaded.
In JavaServer Faces technology, navigation is a set of rules for choosing the
next page or view to be displayed after an application action, such as when a
button or link is clicked.
Navigation can be implicit or user-defined. Implicit navigation comes into play
when user-defined navigation rules are not configured in the application
configuration resource files.
When you add a component such as a commandButton to a Facelets page, and
assign another page as the value for its action property, the default navigation
handler will try to match a suitable page within the application implicitly. In the
following example, the default navigation handler will try to locate a page
named response.xhtml within the application and navigate to it:

<h:commandButton value="submit" action="response">

User-defined navigation rules are declared in zero or more application configuration


resource files, such as faces-config.xml, by using a set of XML elements. The default
structure of a navigation rule is as follows:
<navigation-rule>

<description></description

<from-view-id></from-view-id>

<navigation-case>

<from-action></from-action>

<from-outcome></from-outcome>

<if></if>

<to-view-id></to-view-id>

</navigation-case>

</navigation-rule>

User-defined navigation is handled as follows.

 Define the rules in the application configuration resource file.

 Refer to an outcome String from the button or link component's action attribute. This
outcome String is used by the JavaServer Faces implementation to select the navigation
rule.

Here is an example navigation rule:

<navigation-rule>
<from-view-id>/greeting.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/response.xhtml</to-view-id>
</navigation-case>
</navigation-rule>

This rule states that when a command component (such as an h:commandButton or


an h:commandLink) on greeting.xhtml is activated, the application will navigate from
the greeting.xhtml page to the response.xhtml page if the outcome referenced by
the button component's tag is success. Here is an h:commandButton tag
from greeting.xhtml that would specify a logical outcome of success:

 Creating a Simple Web Application Using


a MySQL Database
MySQL is a popular open source database management system commonly used in web
applications due to its speed, flexibility and reliability. MySQL employs SQL, or Structured
Query Language, for accessing and processing data contained in databases.
you have already created a MySQL database named MyNewDatabase, which you have
registered a connection for in the NetBeans IDE. The table data used in that tutorial is
contained in ifpwafcad.sql and is also required.
This SQL file creates two tables, Subject and Counselor, then populates them with sample
data. If needed, save this file to your computer, then open it in the NetBeans IDE and run
it on the MySQL database named MyNewDatabase.
 Planning the Structure
 Creating a New Project
 ± Preparing the Web Interface
 ± Preparing Communication between the Application and Database
 ± Adding Dynamic Logic
 Running the Completed Application
 ± Troubleshooting

you need the following software and resources.


Software or Resource Version Required

NetBeans IDE 7.2, 7.3, 7.4, 8.0, Java EE bundle

Java Development Kit (JDK) version 7 or 8

MySQL database server 5.x

MySQL Connector/J JDBC Driver version 5.x

GlassFish Server Open Source Edition 3.x or 4.x

Notes:
 The Java download bundle of the NetBeans IDE enables you to install the GlassFish
server. You require the GlassFish server to work through this tutorial.
 The MySQL Connector/J JDBC Driver, necessary for communication between Java
platforms and the MySQL database protocol, is included in the NetBeans IDE.
 If you need to compare your project with a working solution, you can download the
sample application.

 Planning the Structure


Simple web applications can be designed using a two-tier architecture, in which a
client communicates directly with a server. In this tutorial, a Java web application
communicates directly with a MySQL database using the Java Database
Connectivity API. Essentially, it is the MySQL Connector/J JDBC Driver that
enables communication between the Java code understood by the application
server (the GlassFish server), and any content in SQL, the language understood
by the database server (MySQL).
The application you build in this tutorial involves the creation of two JSP pages. In
each of these pages you use HTML and CSS to implement a simple interface, and
apply JSTL technology to perform the logic that directly queries the database and
inserts the retrieved data into the two pages. The two database
tables, Subject and Counselor, are contained in the MySQL
database, MyNewDatabase, which you create by completing the Connecting to a
MySQL Database tutorial. Consider the following two-tier scenario.

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

Architecture of an RMI Application


In an RMI application, we write two programs, a server program (resides on
the server) and a client program (resides on the client).
 Inside the server program, a remote object is created and reference of
that object is made available for the client (using the registry).
 The client program requests the remote objects on the server and tries to
invoke its methods.
The following diagram shows the architecture of an RMI application.
Let us now discuss the components of this architecture.
 Transport Layer − This layer connects the client and the server. It manages
the existing connection and also sets up new connections.
 Stub − A stub is a representation (proxy) of the remote object at client. It
resides in the client system; it acts as a gateway for the client program.
 Skeleton − This is the object which resides on the server
side. stub communicates with this skeleton to pass request to the remote
object.
 RRL(Remote Reference Layer) − It is the layer which manages the
references made by the client to the remote object.

 Working of an RMI Application


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

 Distributed objects technology


This technology virtually hides the network from the designer and programmer.
A distributed object is an object which is resident on one computer and for which
methods can be invoked associated with code resident on other computers. A
good distributed objects technology should totally hide the underlying
communication details from the programmer, for example when a programmer
wants to invoke the method to an object called on a server, then
the programmer should produce the code
in the same form as if the object was contained in the computer in which the
code is resident. There should be no references to ports, sockets and server
sockets.
The vast majority of distributed objects schemes involve the generation of 'under
the bonnet’ code which carries out the actual processes of sending messages to
objects and transmitting the data associated with such messages.
Two distributed objects technologies are CORBA, which is a multi-language
technology, and RMI, which is a Java-based technology.
Distributed objects technology works by intercepting calls to distributed objects
and executing system code which carries out the process of locating objects and
sending data and execution instructions. All this is carried out ‘under the bonnet’
with the programmer not being forced to include communication code. The
architecture of a distributed objects system is shown in Figure 2. Here, a number
of objects spread around a collection of computers communicate by invoking
methods, all data transfer being carried out by means of arguments to the
method calls which correspond to the messages.

Figure 2 A distributed objects architecture


The main advantage of using a distributed objects scheme lies in the fact that it
has a 100 per cent fit with object-oriented technology: that classes identified
during the analysis and design phases can be immediately implemented in terms
of classes in some programming language, deposited on some remote computer
which forms a component of a distributed system and reused without any
modification.
The main disadvantage with distributed objects currently being experienced by
developers is that their performance, certainly compared with message passing
technologies, is inferior.

RMI Architecture
In distributed application architecture, it is always a need for communication
between two different applications. In Java-based applications, one application
communicates with another remote/different application running somewhere
else by using a mechanism called RMI architecture.

RMI stands for Remote Method Invocation. It is an API provided by java which
allows an object residing in one JVM (Java Virtual Machine) to access or invoke an
object running on another JVM. The other JVM could be on the same machine or
remote machine. This is an interesting feature because in real time applications
it becomes very easy for Java applications to communicate directly with each
other without any external communication mechanism. Also, it is always a need
for secure communication between applications based on distributed application
architecture.

RMI Design

Before we go into detailed architecture, we will understand the basic design of


RMI architecture.

 RMI API is provided in the package java.rmi. Let’s introduce two terms for
the understanding of RMI design architecture. First is the client; the JVM
that will call remote object and second is server; the JVM that contains the
remote object. So, the client will call the server, in this case on the object
for method invocation.
 The server will then return the reference of the object to the client. The
catch here is both the objects i.e. local and remote will appear as a local
object on the server. There will be no differentiation between the two. The
syntax of the methods of both objects is also the same. Therefore, the
server JVM acts like normal JVM without knowing of any object whether it
is local or remote.
 The same object can be both a server and a client. The remote objects
reference is obtained, and it is used as if it was a local object. The RMI
infrastructure is responsible for finding the remote object, intercepting
method call and processing the remote request remotely. The client
invokes methods on the object only after obtaining a reference to a
remote object.

RMI Architecture
Below is the diagram of RMI architecture in a simple way. On the internet, you
will find various forms of the same architecture, but we have a simple one which
will help to explain it better.
Let’s start by connecting dots from a design perspective with an architecture
diagram.

The client application and server application are the respective JVMs of the client
machine and server machine. In RMI application we write two programs
respectively; the client program which resides on the client and server program
which resides on the server machine.

Unit-3. Java Networking

 Java Servlets: Introduction to Servlets


A servlet is a Java Programming language class that is used to extend the
capabilities of servers that host applications accessed by means of 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. It is also
a web component that is deployed on the server to create a dynamic web page.
In this figure you can see, a client sends a request to the server and the server
generates the response, analyses it and sends the response to the client.

So, before we jump into the depth of Servlets, let’s see the technology that was used
before servlets came into the picture.

Properties of Servlets :
 Servlets work on the server-side.
 Servlets are capable of handling complex requests obtained from web server.
Execution of Servlets :
Execution of Servlets involves six basic steps:
1. The clients send the request to the web server.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of
output.
5. The servlet sends the response back to the web server.
6. The web server sends the response back to the client and the client browser
displays it on the screen.

 CGI vs Servlets
Before servlets, we had CGI i.e. Common Gateway Interface. It is a standard way for
a Web server to pass a user’s request to an application program and receives the
response to forward to the user. When the user requests a Web page, the server
sends back the requested page. However, when a user fills out a form on a Web
page and sends it in, it is processed by an application program. The Web server
typically passes the form information to a small application program. This program
processes the data and sends back a confirmation message. This process of
passing data back and forth between the server and the application is called the
common gateway interface (CGI). It is part of the Web’s Hypertext Transfer Protocol.
But, why did we stopped using it and switched to servlets? Let’s understand this with
the help of the below table:

Basis for Comparison Common Gateway Interface Servlets


Programs are written in the Programs employed using
1. Basic
native OS. Java.
Does not rely on the
2. Platform dependency Platform dependent
platform
Processes are created
Each client request
3. Creation of process depending on the type of
creates its own process.
the client request.
Present in the form of
Compiled to Java
4. Conversion of the script executables (native to the
Bytecode.
server OS).
5. Runs on Separate process JVM
6. Security More vulnerable to attacks. Can resist attacks.
7. Speed Slower Faster
Before running the scripts
8. Processing of script Direct it is translated and
compiled.
9. Portability Cannot be ported Portable

 Servlet Life Cycle


The Servlet life cycle mainly includes the following four stages,
 Loading a Servlet
 Initializing the Servlet
 Request handling
 Destroying the Servlet
1. When the web server (e.g. Apache Tomcat) starts up, the servlet container
deploy and loads all the servlets.
2. The servlet is initialized by calling the init() method. The Servlet.init() method
is called by the Servlet container to indicate that this Servlet instance is
instantiated successfully and is about to put into service.
3. The servlet then calls service() method to process a client’s request. This
method is invoked to inform the Servlet about the client requests.
4. The servlet is terminated by calling the destroy().
5. The destroy() method runs only once during the lifetime of a Servlet and
signals the end of the Servlet instance.

init() and destroy() methods are called only once. Finally, a servlet is garbage
collected by the garbage collector of the JVM. So this concludes the life cycle of a
servlet. Now, let me guide you through the steps of creating java servlets

 Java Servlets: Steps to Create Servlet


1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Add mappings to the web.xml file
5. Start the server and deploy the project
6. Access the servlet
Now, based on the above steps, let’s write a program and understand how a servlet
works.

To run a servlet program, we should have Apache Tomcat Server installed and
configured. Eclipse for Java EE provides in-built Apache Tomcat. Once the server is
configured, you can start with your program. One important point to note – for any
servlet program, you need 3 files – index.html file, Java class file, and web.xml file.
The very first step is to create a Dynamic Web Project and then proceed further.

Now, let’s see how to add 2 numbers using servlets and display the output in the
browser.

First, I will write index.html file


<!DOCTYPE HTML>
<html>
<body>

<form action = "add">


Enter 1st number: <input type="text" name ="num1">
Enter 2nd number: <input type="text" name="num2">
</form>

</body>
</html>

Above program creates a form to enter the numbers for the addition operation.
Without the Java class file, you can’t perform addition on 2 numbers. So let’s now
create a class file.

package edureka;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Add extends HttpServlet{
public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException
{
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k= i+j;
PrintWriter out = res.getWriter();
out.println("Result is"+k);
}
}
After writing the Java class file, the last step is to add mappings to the web.xml file.
 Networking
 Introduction to Java Networking
Java Networking is a notion of connecting two or more computing devices together
to share the resources. Java program communicates over the network at
the application layer. java.net package is useful for all the Java networking classes
and interfaces.

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

 TCP − Transmission Control Protocol allows reliable communication between


two applications. TCP is typically used over the Internet Protocol, which is
referred to as TCP/IP.

 UDP − User Datagram Protocol is a connection-less protocol that allows


packets of data to be transmitted between applications.

Note: Networking in Java is mainly used for sharing the resources and also for
centralized software management.

With this, let’s move further and learn various terminologies used in Networking.

Networking Terminologies
The widely used Java networking terminologies used are as follows:
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

Now let’s get into the details of each of these methods.

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

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

TCP
FTP
Telnet
SMTP
POP etc.
3. Port Number
The port number uniquely identifies different applications. It acts as a communication endpoint
between applications. To communicate between two applications, the port number is used along
with an IP Address.
4. MAC Address
A MAC address is basically a hardware identification number which uniquely identifies each device
on a network. For example, an Ethernet card may have a MAC address of 00:0d:83:b1:c0:8e.
5. Connection-oriented and connection-less protocol
In the connection-oriented protocol, acknowledgment is sent by the receiver. So it is reliable but
slow. The example of a connection-oriented protocol is TCP. But, in the connection-less protocol,
acknowledgment is not sent by the receiver. So it is not reliable but fast. The example of a
connection-less protocol is UDP.
6. Socket
A socket in Java is one endpoint of a two-way communication link between two programs running
on the network. A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent to.
Now that you know various terminologies used in Java Networking, let’s move further and
understand some of the important classes that it supports.
Inet Address
Inet Address is used to encapsulate both the numerical IP address and the domain name for that
address. It can handle both IPv4 and Ipv6 addresses. Below figure depicts the subclasses of Inet
Address class.

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

1. static InetAddress getLocalHost() throws UnknownHostException


2. static InetAddress getByName (String hostname) throws UnknownHostException
3. static InetAddress[ ] getAllByName (String hostname) throws UnknownHostException
Now let’s take a small example to understand the working of Inet Address class.

1 import java.net.*;
2 public class InetAddressExample
3 {
4 public static void main(String[] args) throws UnknownHostException
5 {
6 InetAddress address = InetAddress.getLocalHost(); // returns the system details i.e. Inet Address
7 System.out.println(address);
8 address = InetAddress.getByName("www.facebook.com"); // returns the address of the website
9 System.out.println(address);
10 InetAddress ia[] = InetAddress.getAllByName("www.google.com");
11 for(int i=0; i< ia.length; i++)
12 {
13 System.out.println(ia[i]);
14 }
15 }
16 }

 Client and Server model


o A client and server networking model is a model in which computers such
as servers provide the network services to the other computers such as
clients to perform a user based tasks. This model is known as client-server
networking model.
o The application programs using the client-server model should follow the
given below strategies:
o An application program is known as a client program, running on the local
machine that requests for a service from an application program known as
a server program, running on the remote machine.
o A client program runs only when it requests for a service from the server
while the server program runs all time as it does not know when its service
is required.
o A server provides a service for many clients not just for a single client.
Therefore, we can say that client-server follows the many-to-one
relationship. Many clients can use the service of one server.
o Services are required frequently, and many users have a specific client-
server application program. For example, the client-server application
program allows the user to access the files, send e-mail, and so on. If the
services are more customized, then we should have one generic
application program that allows the user to access the services available
on the remote computer.

 Client
A client is a program that runs on the local machine requesting service from the server. A
client program is a finite program means that the service started by the user and
terminates when the service is completed.

 Server
A server is a program that runs on the remote machine providing services to the clients.
When the client requests for a service, then the server opens the door for the incoming
requests, but it never initiates the service.

A server program is an infinite program means that when it starts, it runs infinitely unless
the problem arises. The server waits for the incoming requests from the clients. When
the request arrives at the server, then it responds to the request.

Advantages of Client-server networks:


o Centralized: Centralized back-up is possible in client-server networks, i.e., all the
data is stored in a server.
o Security: These networks are more secure as all the shared resources are
centrally administered.
o Performance: The use of the dedicated server increases the speed of sharing
resources. This increases the performance of the overall system.
o Scalability: We can increase the number of clients and servers separately, i.e.,
the new element can be added, or we can add a new node in a network at any
time.

Disadvantages of Client-Server network:


o Traffic Congestion is a big problem in Client/Server networks. When a large
number of clients send requests to the same server may cause the problem of
Traffic congestion.
o It does not have a robustness of a network, i.e., when the server is down, then the
client requests cannot be met.
o A client/server network is very decisive. Sometimes, regular computer hardware
does not serve a certain number of clients. In such situations, specific hardware is
required at the server side to complete the work.
o Sometimes the resources exist in the server but may not exist in the client. For
example, If the application is web, then we cannot take the print out directly on
printers without taking out the print view window on the web.

 Java Socket Client Examples (TCP/IP)


TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-
point, stream-based connections between hosts on the Internet. A socket can be
used to connect Java’s I/O system to other programs that may reside either on
the local machine or on any other machine on the Internet.

There are two kinds of TCP sockets in Java. One is for servers, and the other is
for clients. The ServerSocket class is designed to be a "listener," which waits
for clients to connect before doing anything. Thus, ServerSocket is for servers.
The Socket class is for clients. It is designed to connect to server sockets and
initiate protocol exchanges. Because client sockets are the most commonly
used by Java applications, they are examined here.

The creation of a Socket object implicitly establishes a connection between the


client and server. There are no methods or constructors that explicitly expose
the details of establishing that connection. Here are two constructors used to
create client sockets:

Socket defines several instance methods. For example, a Socket can be


examined at any time for the address and port information associated with it, by
use of the following methods:
InetAddress getInetAddress( ) : Returns the InetAddress associated with the
Socket object. It returns null if the socket is not connected.

int getPort( ) : Returns the remote port to which the invoking Socket object is
connected. It returns 0 if the socket is not connected.

int getLocalPort( ) : Returns the local port to which the invoking Socket object is
bound. It returns –1 if the socket is not bound.

You can gain access to the input and output streams associated with
a Socket by use of
the getInputStream( ) and getOuptutStream( ) methods, as shown here.
Each can throw an IOException if the socket has been invalidated by a loss of
connection. These streams are used exactly like the I/O streams described in
Chapter 20 to send and receive data.

InputStream getInputStream( ) throws IOException : Returns the InputStream


associated with the invoking socket.

OutputStream getOutputStream( )throws IOException : Returns the


OutputStream associated with the invoking socket.

Several other methods are available, including connect( ), which allows you to
specify a new connection; isConnected( ), which returns true if the socket is
connected to a server; isBound( ), which returns true if the socket is bound to
an address; and isClosed( ), which returns true if the socket is closed. To close
a socket, call close( ). Closing a socket also closes the I/O streams associated
with the socket. Beginning with JDK 7, Socket also implements AutoCloseable,
which means that you can use a try-with-resources block

 TCP/IP Server Sockets


1. Client Socket API
The Socketclass represents a socket client. You use this class to make connection to a server,
send data to and read data from that server. The following steps are applied for a typical
communication with the server:
1. The client initiates connection to a server specified by hostname/IP address and port
number.
2. Send data to the server using an OutputStream.
3. Read data from the server using an InputStream.
4. Close the connection.
The steps 2 and 3 can be repeated many times depending on the nature of the communication.
Now, let’s study how to use the Socket class to implement these steps.
 Initiate Connection to a Server:
To make a connection to a server, create a new Socket object using one of the
following constructors:
- Socket(InetAddress address, int port)
- Socket(String host, int port)
- Socket(InetAddress address, int port, InetAddress localAddr,
int localPort)
You see, it requires the IP address/hostname of the server and the port number.
With the first two constructors, the system automatically assigns a free port number and
a local address for the client computer. With the third constructor, you can explicitly
specify the address and port number of the client if needed. The first constructor is often
used because of its simplicity.
These constructors can throw the following checked exceptions:
- IOException: if an I/O error occurs when creating the socket.
- UnknownHostException: if the IP address of the host could not be determined.
That means you have to catch (or re-throw) these checked exceptions when creating a
Socket instance. The following line of code demonstrates how to create a client socket
that attempts to connect to google.com at port number 80:
1 Socket socket = new Socket("google.com", 80)

 Send Data to the Server:


To send data to the server, get the OutputStream object from the socket first:
1 OutputStream output = socket.getOutputStream();
Then you can use the write() method on the OutputStream to write an array of byte to be
sent:
1 byte[] data = ….
2 output.write(data);
And you can wrap the OutputStream in a PrintWriter to send data in text format, like this:
1 PrintWriter writer = new PrintWriter(output, true);
2 writer.println(“This is a message sent to the server”);
The argument true indicates that the writer flushes the data after each method call (auto flush).

 Read Data from the Server:


Similarly, you need to obtain an InputStream object from the client socket to read data from
the server:
1 InputStream input = socket.getInputStream();
Then use the read() method on the InputStream to read data as an array of byte, like this:
1 byte[] data =…
2 input.read(data);
You can wrap the InputStream object in an InputStreamReader or BufferedReader to
read data at higher level (character and String). For example, using InputStreamReader:
1 InputStreamReader reader = new InputStreamReader(input);
2 int character = reader.read(); // reads a single character
And using BufferedReader:
1 BufferedReader reader = new BufferedReader(new InputStreamReader(input));
2 String line = reader.readLine(); // reads a line of text
 Close the Connection:
Simply call the close() method on the socket to terminate the connection between the client
and the server:
1 socket.close();
This method also closes the socket’s InputStream and OutputStream, and it can
throw IOException if an I/O error occurs when closing the socket.

The InetAddress Class


The java.net.InetAddress class is Java’s encapsulation of an IP address. It is used
by most of the other networking classes,
including Socket, ServerSocket, URL, DatagramSocket, DatagramPacket, and
more.

public final class InetAddress extends Object implements Serializable

This class represents an Internet address as two fields: hostName (a String)


and address (an int). hostName contains the name of the host; for
example, www.oreilly.com. address contains the 32-bit IP address. These fields
are not public, so you can’t access them directly. It will probably be necessary to
change this representation to a byte array when 16-byte IPv6 addresses come
into use. However, if you always use the InetAddress class to represent
addresses, the changeover should not affect you; the class shields you from the
details of how addresses are implemented.
 Creating New InetAddress Objects
There are no public constructors in the InetAddress class.
However, InetAddress has three static methods that return suitably
initialized InetAddress objects, given a little information. They are:

public static InetAddress InetAddress.getByName(String hostName)

throws UnknownHostException

public static InetAddress[] InetAddress.getAllByName(String hostName)

throws UnknownHostException

public static InetAddress InetAddress.getLocalHost( )

throws UnknownHostException

All three of these may make a connection to the local DNS server to fill out the
information in the InetAddress object.
Datagrams in Java
TCP/IP-style networking provides a serialized, predictable, reliable stream of packet
data. This is not without its cost, however. TCP includes algorithms for dealing with
congestion control on crowded networks, as well as pessimistic expectations about
packet loss. This leads to inefficient way to transport data.
Clients and servers that communicate via a reliable channel, such as a TCP socket,
have a dedicated point-to-point channel between themselves. To communicate, they
establish a connection, transmit the data, and then close the connection. All data
sent over the channel is received in the same order in which it was sent. This is
guaranteed by the channel.
In contrast, applications that communicate via datagrams send and receive
completely independent packets of information. These clients and servers do not
have and do not need a dedicated point-to-point channel. The delivery of datagrams
to their destinations is not guaranteed. Nor is the order of their arrival.

 Datagram
A datagram is an independent, self-contained message sent over the network
whose arrival, arrival time, and content are not guaranteed.
 Datagrams plays a vital role as an alternative.
 Datagrams are bundles of information passed between machines. Once the
datagram has been released to its intended target, there is no assurance
that it will arrive or even that someone will be there to catch it.
 Likewise, when the datagram is received, there is no assurance that it
hasn’t been damaged in transit or that whoever sent it is still there to
receive a response and it is crucial point to note.
Java implements datagrams on top of the UDP (User Datagram Protocol) protocol
by using two classes:
1. DatagramPacket object is the data container.
2. DatagramSocket is the mechanism used to send or receive the
DatagramPackets.

 DatagramSocket Class
DatagramSocket defines four public constructors. They are shown here:
 DatagramSocket( ) throws SocketException : It creates a
DatagramSocket bound to any unused port on the local computer.
 DatagramSocket(int port) throws SocketException : It creates a
DatagramSocket bound to the port specified by port.
 DatagramSocket(int port, InetAddress ipAddress) throws
SocketException : It constructs a DatagramSocket bound to the specified
port and InetAddress.
 DatagramSocket(SocketAddress address) throws
SocketException : It constructs a DatagramSocket bound to the specified
SocketAddress.
SocketAddress is an abstract class that is implemented by the concrete class
InetSocketAddress. InetSocketAddress encapsulates an IP address with a port
number. All can throw a SocketException if an error occurs while creating the
socket. DatagramSocket defines many methods. Two of the most important are
send( ) and receive( ), which are shown here:
 void send(DatagramPacket packet) throws IOException
 void receive(DatagramPacket packet) throws IOException

A Datagram Example

// Java program to illustrate datagrams


import java.net.*;
class WriteServer {

// Specified server port


public static int serverPort = 998;

// Specified client port


public static int clientPort = 999;

public static int buffer_size = 1024;


public static DatagramSocket ds;

// an array of buffer_size
public static byte buffer[] = new byte[buffer_size];

// Function for server


public static void TheServer() throws Exception
{
int pos = 0;
while (true) {
int c = System.in.read();
switch (c) {
case -1:

// -1 is given then server quits and returns


System.out.println("Server Quits.");
return;
case '\r':
break; // loop broken
case '\n':
// send the data to client
ds.send(new DatagramPacket(buffer, pos,

InetAddress.getLocalHost(), clientPort));
pos = 0;
break;
default:
// otherwise put the input in buffer array
buffer[pos++] = (byte)c;
}
}
}

// Function for client


public static void TheClient() throws Exception
{
while (true) {
// first one is array and later is its size
DatagramPacket p = new DatagramPacket(buffer,
buffer.length);

ds.receive(p);

// printing the data which has been sent by the server


System.out.println(new String(p.getData(), 0, p.getLength()));
}
}

// main driver function


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

// if WriteServer 1 passed then this will run the server function


// otherwise client function will run
if (args.length == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
}
else {
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}

 How to create a Network Application using


Java
The following figure displays multiple clients accessing a server.
 Activity : Creating a Server Application

To create a server program using Netbeans IDE, you need to perform the
following steps:

 Select start->All Programs->NetBeans 5.5.1->NetBeans IDE.


The NetBeans IDE 5.5.1 window appears.
 Select File->New Project. The New Project window appears.

Ensure that the General option is selected in the Categories section of


the ChooseProject page.

 Select the Java Application option in the Projects section of the Choose
Project page.
 Click the Next button. The NameandLocation page is displayed.
 Type ServerActivity in the Project Name text box.
 Type <Drive Letter>:\JavaProjects in the Project Location text box.

Replace the text, serveractivity.Main to serveractivity.AppServer in the text box


given next to the Create Main Class check box.

Click the Finish button. The NetBeans IDE 5.5.1 - ServerActivity window is
displayed.

Task 2: Creating a Client Program


To create a client program, you need to perform the following steps:
Right-click the ServerActivity node in the Projects tab, and then select New-
>File/Folder.

The NewFile dialog box appears.

Select the Java Classes option in the Categories section of the Choose File
Type page.

Select the JApplet option in the File Types section of the Choose File
Type page. Click the Next button. The NewJApplet dialog box appears.

Replace the text in the Class Name text box with CustomerApplet.

Select the serveractivity option from the Package combo box.

Click the Finish button. The NetBeans IDE 5.5.1 ServerActivity window is
displayed.

Ensure that the CustomerApplet.java tab is selected.

Task 3: Compiling and Executing the Application


To compile and execute the application using Netbeans IDE, you need to perform the
following steps:

 Right-click the AppServer.java node in the Projects tab, and then


select Compile File to compile the file.
 Right-click the AppServer.java node in the Projects tab, and then select Run
File to execute the file.
 Right-click the CustomerApplet.java node in the Projects tab, and then
select Compile File to compile the file.
 Right-click the CustomerApplet.java node in the Projects tab, and then
select Run File to execute the file.
 Type the customer name in the Customer Login Name text box.
 Type the password in the Password text box.
 Click the Login button to establish a connection with the server program, and
send and receive the customer details.
 Repeat the steps 4 to 7 to open multiple clients and establish a connection with
the server program

Unit-4. Java Beans

 JavaBeans Architecture
JavaBeans is an architecture for both using and building components in Java. This
architecture supports the features of software reuse, component models, and
object orientation. One of the most important features of JavaBeans is that it
does not alter the existing Java language. If you know how to write software in
Java, you know how to use and create Beans. The strengths of Java are built
upon and extended to create the JavaBeans component architecture.

Although Beans are intended to work in a visual application development tool,


they don’t necessarily have a visual representation at run-time (although many
will). What this does mean is that Beans must allow their property values to be
changed through some type of visual interface, and their methods and events
should be exposed so that the development tool can write code capable of
manipulating the component when the application is executed.

Creating a Bean doesn’t require any advanced concepts. So before I go any


further, here is some code that implements a simple Bean:

public class MyBean implements java.io.Serializable


{
protected int theValue;

public MyBean()
{
}

public void setMyValue(int newValue)


{
theValue = newValue;
}

public int getMyValue()


{
return theValue;
}
}

This is a real Bean named MyBean that has state (the variable theValue) that will
automatically be saved and restored by the JavaBeans persistence mechanism,
and it has a property named MyValue that is usable by a visual programming
environment. This Bean doesn’t have any visual representation, but that isn’t a
requirement for a JavaBean component.

 Advantages of Beans

JavaBeans is a portable, platform-independent component model written in the


Java programming language. The JavaBeans architecture was built through a
collaborative industry effort and enables developers to write reusable
components in the Java programming language. Java Bean components are
known as beans. Beans are dynamic in that they can be changed or customized.
Advantages of Java Beans
Software component architecture provides standard mechanisms to deal with
software building blocks. The following list enumerates some of the specific
benefits that Java technology provides for a component developer:

 A Bean obtains all the benefits of Java's "write-once, run-anywhere"


paradigm.
 The properties, events, and methods of a Bean that are exposed to an
application
builder tool can be controlled.
 A Bean may be designed to operate correctly in different locales, which
makes it
useful in global markets.
 Auxiliary software can be provided to help a person configure a Bean. This
software is only needed when the design-time parameters for that
component are being set. It does not need to be included in the run-time
environment.
 The configuration settings of a Bean can be saved in persistent storage
and restored at a later time.

A Bean may register to receive events from other objects and can generate
events that are sent to other objects.

 Java Beans Development Kit


This module explores the JavaBeans Development Kit (BDK) and the tools and
resources it provides for Bean development.
After installing the BDK, you find out what the BeanBox test container is and how
it is used to customize and test Beans in a setting similar to application builder
tools.
Module learning objectives
After completing the module, I will show you the skills and knowledge necessary
to:

1. Customize a Bean at design time with the BeanBox


2. Test a Bean at runtime with the BeanBox

In the next lesson, I will discuss how to install the BDK.

 What do beans provide


But what do beans provide that other classes do not? After all, beans are merely regular Java classes
that follow some simple conventions defined by the JavaBeans specification; beans extend no
particular class, are in no particular package, and use no particular interface. Although it is true that
beans are merely Java classes that are written in a standard format, there are several advantages to
their use. With beans in general, visual manipulation tools and other programs can automatically
discover information about classes that follow this format and can create and manipulate the classes
without the user having to explicitly write any code. In JSP in particular, use of JavaBeans
components provides three advantages over scriptlets and JSP expressions that refer to normal Java
classes.
1. No Java syntax. By using beans, page authors can manipulate Java objects using only XML-
compatible syntax: no parentheses, semicolons, or curly braces. This promotes a stronger separation
between the content and the presentation and is especially useful in large development teams that
have separate Web and Java developers.
2. Simpler object sharing. When you use the JSP bean constructs, you can much more easily share
objects among multiple pages or between requests than if you use the equivalent explicit Java code.
3. Convenient correspondence between request parameters and object properties. The JSP bean
constructs greatly simplify the process of reading request parameters, converting from strings, and
putting the results inside objects.

 Software
As software developers, we are constantly being asked to build applications in less time and with less
money. In addition, these applications are expected to be better and faster than ever before. Object-
oriented techniques and component software environments are in wide use now, in the hope that they
can help us build applications more quickly. Development tools like Microsoft's Visual Studio have
made it easier to build applications faster by taking a building-block approach to software
development. Such tools provide a visual programming model that allows you to include software
components rapidly in your applications. The JavaBeans architecture brings the component
development model to Java, and that is the subject of this course. But before we get started, I want to
spend a little time describing the component model, and follow that with a general overview of
JavaBeans.

Jar files in Java


A JAR (Java Archive) is a package file format typically used to aggregate many
Java class files and associated metadata and resources (text, images, etc.) into
one file to distribute application software or libraries on the Java platform.
In simple words, a JAR file is a file that contains compressed version of .class
files, audio files, image files or directories. We can imagine a .jar files as a zipped
file(.zip) that is created by using WinZip software. Even , WinZip software can be
used to used to extract the contents of a .jar . So you can use them for tasks
such as lossless data compression, archiving, decompression, and archive
unpacking.
Let us see how to create a .jar file and related commands which help us to work
with .jar files

1. Create a JAR file: To create a .jar file , we can use jar cf command in the following
way:
jar cf jarfilename inputfiles
Here, cf represents create the file. For example , assuming our package pack is
available in C:\directory , to convert it into a jar file into the pack.jar , we can give
the command as:
C:\> jar cf pack.jar pack
Now , pack.jar file is created
2. Viewing a JAR file: To view the contents of .jar files, we can use the command as:
jar tf jarfilename
Here , tf represents table view of file contents. For example, to view the contents of
our pack.jar file , we can give the command:
C:/> jar tf pack.jar
Now , the contents of pack.jar are displayed as:

META-INF/
META-INF/MANIFEST.MF
pack/
pack/class1.class
pack/class2.class
..
..
where class1 , class2 etc are the classes in the package pack. The first two entries
represent that there is a manifest file created and added to pack.jar. The third entry
represents the sub-directory with the name pack and the last two represent the
files name in the directory pack.
When we create .jar files , it automatically receives the default manifest file. There
can be only one manifest file in an archive , and it always has the pathname.
META-INF/MANIFEST.MF
This manifest file is useful to specify the information about other files which are
packaged.
3. Extracting a JAR file: To extract the files from a .jar file , we can use:
jar xf jarfilename
Here, xf represents extract files from the jar files. For example , to extract the
contents of our pack.jar file, we can write:
C:\> jar xf pack.jar
This will create the following directories in C:\
META-INF
pack // in this directory , we can see class1.class and class2.class.

4. Updating a JAR File The Jar tool provides a ‘u’ option which you can use to update
the contents of an existing JAR file by modifying its manifest or by adding files. The
basic command for adding files has this format:
jar uf jar-file input-file(s)
here uf represent update jar file. For example , to update the contents of our
pack.jar file, we can write:
C:\>jar uf pack.jar
5. Running a JAR file: In order to run an application packaged as a JAR file (requires
the Main-class manifest header) , following command can be used:
C:\>java -jar pack.jar
 Introspection
Introspection is the automatic process of analyzing a bean's design patterns to
reveal the bean's properties, events, and methods. This process controls the
publishing and discovery of bean operations and properties. This lesson explains
the purpose of introspection, introduces the Introspection API, and gives an
example of introspection code.

Purpose of Introspection

A growing number of Java object repository sites exist on the Internet in answer
to the demand for centralized deployment of applets, classes, and source code in
general. Any developer who has spent time hunting through these sites for
licensable Java code to incorporate into a program has undoubtedly struggled
with issues of how to quickly and cleanly integrate code from one particular
source into an application.

The way in which introspection is implemented provides great advantages,


including:

1. Portability - Everything is done in the Java platform, so you can write


components once, reuse them everywhere. There are no extra
specification files that need to be maintained independently from your
component code. There are no platform-specific issues to contend with.
Your component is not tied to one component model or one proprietary
platform. You get all the advantages of the evolving Java APIs, while
maintaining the portability of your components.
2. Reuse - By following the JavaBeans design conventions, implementing the
appropriate interfaces, and extending the appropriate classes, you provide
your component with reuse potential that possibly exceeds your
expectations.

Introspection API
The JavaBeans API architecture supplies a set of classes and interfaces to provide introspection.

The BeanInfo (in the API reference documentation) interface of the java.beans package defines
a set of methods that allow bean implementors to provide explicit information about their beans. By
specifying BeanInfo for a bean component, a developer can hide methods, specify an icon for the
toolbox, provide descriptive names for properties, define which properties are bound properties, and
much more.

The getBeanInfo(beanName) (in the API reference documentation) of the Introspector (in
the API reference documentation) class can be used by builder tools and other automated
environments to provide detailed information about a bean. The getBeanInfo method relies on the
naming conventions for the bean's properties, events, and methods. A call to getBeanInfo results
in the introspection process analyzing the beanÂ’s classes and superclasses.

The Introspector class provides descriptor classes with information about properties, events, and
methods of a bean. Methods of this class locate any descriptor information that has been explicitly
supplied by the developer through BeanInfo classes. Then the Introspector class applies the
naming conventions to determine what properties the bean has, the events to which it can listen, and
those which it can send.

 Using Bound Properties Java


Using Bound Properties
A Bean that has a bound property generates an event when the property is changed.
The event is of type Property Change Event and is sent to objects that previously ,
registered an interest in receiving such notifications. The Tick Tock Bean is supplied
with the BDK. It generates a property change event every N seconds. N is a property
of the Bean that can be changed via the Properties window of the BDK. The next
example builds an application that uses the Tick’I’ock Bean to autocratically control
the Colors Bean. how this applicant on,appears.

start the BDK and create an instance of the’ Colors Bean in the Bean Box
window. Create an instance of the Tick Tock BFan. The Properties window should
show one property for, this component. It is “Interval” and its initial value is 5. This
represents the number of seconds that’elapse between property change events
generated by the Tick Tock Bean. Change the value to 1.

Using the Bean info Interface


design patterns were used to determine the information that was provided to a
Bean user. This section describes how a developer can use the Bean info
interface to explicitly control this process.
This interface defines several methods, including these:
Propcrt}rqes.criptor[]getl’ropertyfsescriptorsf)
EventSetDescriptor[]getEventSetDescriptors()
MethodDescriptor[ ] getMethodDescriptors( )
They return arrays of objects that provide information about the properties,
events, and methods of a Bean. By implementing these methods, a developer
can designate exactly what is presented to a user.’
Simple Bean info is a class that provides default implementations of the Bean
Info .
interface, including the three methods just shown. You may extend this class and
override one or more of them. The following listing shows how this is done for the
Colors Bean that was’ developed earlier, Colors Bean info is a subclass of Simple
Bean Info. It overrides get Property Description( )in order to designate which
properties are presented to a Bean user. This method creates a Property
Descriptor object for the rectangular property.

Enterprise Java Beans (EJB)


Enterprise Java Beans (EJB) is one of the several Java APIs for standard
manufacture of enterprise software. EJB is a server-side software element that
summarizes business logic of an application. Enterprise Java Beans web repository
yields a runtime domain for web related software elements including computer
reliability, Java Servlet Lifecycle (JSL) management, transaction procedure and
other web services. The EJB enumeration is a subset of the Java EE enumeration.
The EJB enumeration was originally developed by IBM in 1997 and later adopted by
Sun Microsystems in 1999 and enhanced under the Java Community Process.
The EJB enumeration aims to provide a standard way to implement the server-side
business software typically found in enterprise applications. Such machine code
addresses the same types of problems, and solutions to these problems are often
repeatedly re-implemented by programmers. Enterprise Java Beans is assumed to
manage such common concerns as endurance, transactional probity and security in
a standard way that leavs programmers free to focus on the particular parts of the
enterprise software at hand.
To run EJB application we need an application server (EJB Container) such as
Jboss, Glassfish, Weblogic, Websphere etc. It performs:
1. Life cycle management
2. Security
3. Transaction management
4. Object pooling

Types of Enterprise Java Beans


There are three types of EJB:
1. Session Bean: Session bean contains business logic that can be invoked by
local, remote or webservice client. There are two types of session beans: (i) Stateful
session bean and (ii) Stateless session bean.
 (i) Stateful Session bean :
Stateful session bean performs business task with the help of a state. Stateful
session bean can be used to access various method calls by storing the
information in an instance variable. Some of the applications require information
to be stored across separate method calls. In a shopping site, the items chosen
by a customer must be stored as data is an example of stateful session bean.
 (ii) Stateless Session bean :
Stateless session bean implement business logic without having a persistent
storage mechanism, such as a state or database and can used shared data.
Stateless session bean can be used in situations where information is not
required to used across call methods.
2. Message Driven Bean: Like Session Bean, it contains the business logic but it is
invoked by passing message.
3. Entity Bean: It summarizes the state that can be remained in the database. It is
deprecated. Now, it is replaced with JPA (Java Persistent API). There are two types
of entity bean:
 (i) Bean Managed Persistence :
In a bean managed persistence type of entity bean, the programmer has to
write the code for database calls. It persists across multiple sessions and
multiple clients.
 (ii) Container Managed Persistence :
Container managed persistence are enterprise bean that persists across
database. In container managed persistence the container take care of
database calls.
When to use Enterprise Java Beans
1.Application needs Remote Access. In other words, it is distributed.
2.Application needs to be scalable. EJB applications supports load balancing,
clustering and fail-over.
3.Application needs encapsulated business logic. EJB application is
differentiated from demonstration and persistent layer.

Unit-5. Java Server Pages:

Introduction to Java Server Pages


JSP is a server side technology that does all the processing at server. It is used
for creating dynamic web applications, using java as programming language.

Basically, any html file can be converted to JSP file by just changing the file
extension from “.html” to “.jsp”, it would run just fine. What differentiates JSP
from HTML is the ability to use java code inside HTML. In JSP, you can embed
Java code in HTML using JSP tags. for e.g. run the code below, every time you run
this, it would display the current time. That is what makes this code dynamic .
<HTML>
<BODY>
Hello BeginnersBook Readers!
Current time is: <%= new java.util.Date() %>
</BODY>
</HTML>
Your First JSP
Let’s start learning JSP with a simple JSP.

<%-- JSP comment --%>


<HTML>
<HEAD>
<TITLE>MESSAGE</TITLE>
</HEAD>
<BODY>
<%out.print("Hello, Sample JSP code");%>
</BODY>
</HTML>
The above JSP generates the following output:
Hello, Sample JSP code.

JSP – Architecture
The web server needs a JSP engine, i.e, a container to process JSP pages. The
JSP container is responsible for intercepting requests for JSP pages. This tutorial
makes use of Apache which has built-in JSP container to support JSP pages
development.
A JSP container works with the Web server to provide the runtime environment
and other services a JSP needs. It knows how to understand the special
elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web
application.

JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
 As with a normal page, your browser sends an HTTP request to the web
server.
 The web server recognizes that the HTTP request is for a JSP page and
forwards it to a JSP engine. This is done by using the URL or JSP page
which ends with .jsp instead of .html.
 The JSP engine loads the JSP page from disk and converts it into a servlet
content. This conversion is very simple in which all template text is converted
to println( ) statements and all JSP elements are converted to Java code.
This code implements the corresponding dynamic behavior of the page.
 The JSP engine compiles the servlet into an executable class and forwards
the original request to a servlet engine.
 A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML
format. The output is furthur passed on to the web server by the servlet
engine inside an HTTP response.
 The web server forwards the HTTP response to your browser in terms of
static HTML content.
 Finally, the web browser handles the dynamically-generated HTML page
inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −

Typically, the JSP engine checks to see whether a servlet for a JSP file already
exists and whether the modification date on the JSP is older than the servlet. If the
JSP is older than its generated servlet, the JSP container assumes that the JSP
hasn't changed and that the generated servlet still matches the JSP's contents. This
makes the process more efficient than with the other scripting languages (such as
PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having
to be a Java programming wiz. Except for the translation phase, a JSP page is
handled exactly like a regular servlet.

 Jsp Implicit Objects


These objects are created by JSP Engine during translation phase (while translating
JSP to Servlet). They are being created inside service method so we can directly use
them within Scriptlet without initializing and declaring them. There are total 9 implicit
objects available in JSP.
Implicit Objects and their corresponding classes:

out javax.servlet.jsp.JspWriter

request javax.servlet.http.HttpServletRequest

response javax.servlet.http.HttpServletResponse

session javax.servlet.http.HttpSession

application javax.servlet.ServletContext

exception javax.servlet.jsp.JspException

page java.lang.Object

pageContext javax.servlet.jsp.PageContext

config javax.servlet.ServletConfig

1.Out: This is used for writing content to the client (browser). It has several
methods which can be used for properly formatting output message to the
browser and for dealing with the buffer.

2.Request: The main purpose of request implicit object is to get the data on a JSP page
which has been entered by user on the previous JSP page. While dealing with login and
signup forms in JSP we often prompts user to fill in those details, this object is then used
to get those entered details on an another JSP page (action page) for validation and other
purposes.

3.Response: It is basically used for modfying or delaing with the response which is
being sent to the client(browser) after processing the request.
4.Session: It is most frequently used implicit object, which is used for storing the
user’s data to make it available on other JSP pages till the user session is active.
5.Application: This is used for getting application-wide initialization parameters and
to maintain useful data across whole JSP application.
6.Exception: Exception implicit object is used in exception handling for displaying
the error messages. This object is only available to the JSP pages, which has
isErrorPage set to true.
Developing a simple JSP web
application
Setting Up the Project
We are going to start by creating a Dynamic Web Project with a minimal
structure, that is with just required facets.

o Go to the menu bar and select File → New → Other...


o Select Web → Dynamic Web Project in the New Project dialog box
o Click the Next button
o Enter "jspHello" as a project name
o Select Minimal Configuration from the list of possible configurations
o Click the Next button twice to move through the Java window to the Web
Module window
o Select the Generate web.xml check box and click the Finish button.

Figure 5.1. Create New Web Project

The jspHello node should be visible in the upper-left Package Explorer view.
Figure 5.2. New Web Project

5.2. Creating JSP Page


This section outlines how to create, edit and then preview a JSP page.

In our simple application we need to create only one JSP page which displays a "Hello
World!" message.

o Right-click the WebContent folder and select New → JSP.


o Type hello.jsp for a file name and click the Next button.

In the next window you can choose a template for your JSP page and see its preview.

o Select New JSP File (xhtml) template and click the Finish button.
Figure 5.3. Create JSP Page

Our hello.jsp page will now appear in the Project Explorer view.

5.2.1. Editing a JSP Page

To edit the JSP page so that it displays the “Hello World!” message, insert the following line inside
the <body> </body> tags:

<% System.out.println("Hello World!"); %>


Notice that content assist functionality is always available when you are typing:

Figure 5.4. Content Assist in JSP Page

After this line has been added, your hello.jsp page should look like this:
Figure 5.5. Hello.jsp Page Source

This line will actually output "Hello World!" message in the Console. To make the message
displayed in the Browser, just replace this line with the simple Hello World!.

5.2.2. web.xml file

When you are creating web project the wizard creates the web.xml file for you automatically.
The web.xml file editor provided by JBoss Developer Studio is available in two
modes: Tree and Source.
Figure 5.6. Web.xml in Design and Source Mode

Both modes are fully synchronized. To add a mapping to the hello.jsp page in the web.xml file:

o Switch to the Source tab.


o Add the next code into <welcome-file-list> :
<welcome-file>hello.jsp</welcome-file>

If you go back to Tree tab you will see that the changes made in the Source tab are automatically
reflected.

Actually you do not really need to do any configurations right now.

5.2.3. Deploying the project

Writing any scripts and managing the packaging process can be quite a complicated and time
consuming task for even the most trivial web applications. However, JBoss Developer
Studio relieves you of this burden. All you need is to start your JBoss Server and launch your
application in your favorite browser.

You can also create a JAR archive with JBoss Developer Studio's Archive Tools and export it to any
web server.

5.2.3.1. JAR Config

Project archives managing is available through the Project Archives view.

o Select Window → Show view → Other → JBoss Tools → Project archives from the
menu bar
o Select a project in Package Explorer you want to be archived

In the Project Archives view you will see the that the project is now listed:

Figure 5.7. Project Archives


Right-click on the project and select New Archive → JAR.

Figure 5.8. Project Archives

In the New JAR dialog you can see automatically selected default values.

Figure 5.9. New JAR Archive

o Click the Finish button. The .JAR file will appear in Package Explorer and also in Project
Archives view as structure tree:
Figure 5.10. Archive is Created

Figure 5.11. Archive in Package Explorer

Using the Project Archives view you can rebuild the archive:

Figure 5.12. Configure Archive

5.2.3.2. Auto redeploy

When you create a web application and register it on the JBoss Server it is automatically deployed
into the /deploy directory of the server. JBoss Developer Studio's auto-redeploy feature ensures
you do not need to restart the server. Any changes made in the application in exploded format will
trigger a redeployment on the server.

You can also use the "Finger touch" button for a quick restart of the project without restarting the
server:

Figure 5.13. Finger Touch button


The "Finger" touches descriptors dependent on project (that is web.xml for WAR, application.xml
for EAR, jboss-esb.xml in ESB projects).

5.2.4. JSP Page Preview

JBoss Developer Studio comes with JSP design-time preview features. When designing JSP pages
you can easily preview how they will look during runtime. You can even attach your stylesheet to
the Preview.

o Make a little change to hello.jsp page. For example, insert this piece of code:
<%= new java.util.Date() %>

o Click the Save button.


o Switch to Preview page by clicking the Preview tab at the bottom of the page. You will see
how the page will look at runtime.
5.2.5. Launch JSP Project

Now launch the project onto a JBoss server:

o Start a JBoss Server from the Servers view by clicking the Start the server icon ( ).
o Click the Run icon or right-click your project folder and select Run As → Run on Server. If
you have not made any changes in the web.xml file or cleared it out you can launch the
application by right clicking the hello.jsp page and selecting Run on the

Server( ).

You should see the next page in a Browser :

Figure 5.14. Running Project

You might also like