0% found this document useful (0 votes)
435 views67 pages

Java Unit 3+ 4 Notes IPU

An applet is a Java program that runs in a web browser and has access to the full Java API. Applets differ from standalone applications in that they are embedded in HTML pages and have security restrictions. The lifecycle of an applet involves init, start, stop and destroy methods. A basic 'Hello World' applet is provided as an example.

Uploaded by

Itisha Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
435 views67 pages

Java Unit 3+ 4 Notes IPU

An applet is a Java program that runs in a web browser and has access to the full Java API. Applets differ from standalone applications in that they are embedded in HTML pages and have security restrictions. The lifecycle of an applet involves init, start, stop and destroy methods. A basic 'Hello World' applet is provided as an example.

Uploaded by

Itisha Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 67

UNIT 3

Java – Applet

An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
• An applet is a Java class that extends the java.applet.Applet class.
• A main() method is not invoked on an applet, and an applet class will not define main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.
• Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.

Life Cycle of an Applet

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Four methods in the Applet class gives you the framework on which you build any serious applet

• init − This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
• start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
• stop − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.

A "Hello, World" Applet


Following is a simple applet named HelloWorldApplet.java −
import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {


public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}
These import statements bring the classes into the scope of our applet class −

• java.applet.Applet
• java.awt.Graphics
Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.

The Applet Class

Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the
browser context.
These include methods that do the following −
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
• Get applet parameters
• Get the network location of the HTML file that contains the applet
• Get the network location of the applet class directory
• Print a status message in the browser
• Fetch an image
• Fetch an audio clip
• Play an audio clip
• Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains
information about the applet and controls the applet's execution. The viewer may −

• Request information about the author, version, and copyright of the applet
• Request a description of the parameters the applet recognizes
• Initialize the applet
• Destroy the applet
• Start the applet's execution
• Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint
method.

Invoking an Applet

An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Following is an
example that invokes the "Hello, World" applet −
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Note − You can refer to HTML Applet Tag to understand more about calling applet from
HTML.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and
height are also required to specify the initial size of the panel in which an applet runs. The
applet directive must be closed with an </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding <param> tags
between <applet> and </applet>. The browser ignores text and other tags between the applet
tags.
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that
appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.
The viewer or browser looks for the compiled Java code at the location of the document. To
specify otherwise, use the codebase attribute of the <applet> tag as shown −
<applet codebase = "https://amrood.com/applets" code = "HelloWorldApplet.class"
width = "320" height = "120">
If an applet resides in a package other than the default, the holding package must be specified in
the code attribute using the period character (.) to separate package/class components. For
example −
<applet = "mypackage.subpackage.TestApplet.class"
width = "320" height = "120">

Getting Applet Parameters


The following example demonstrates how to make an applet respond to setup parameters
specified in the document. This applet displays a checkerboard pattern of black and a second
color.
The second color and the size of each square may be specified as parameters to the applet
within the document.
CheckerApplet gets its parameters in the init() method. It may also get its parameters in the
paint() method. However, getting the values and saving the settings once at the start of the
applet, instead of at every refresh, is convenient and efficient.
The applet viewer or browser calls the init() method of each applet it runs. The viewer calls
init() once, immediately after loading the applet. (Applet.init() is implemented to do nothing.)
Override the default implementation to insert custom initialization code.
The Applet.getParameter() method fetches a parameter given the parameter's name (the value of
a parameter is always a string). If the value is numeric or other non-character data, the string
must be parsed.
The following is a skeleton of CheckerApplet.java −
import java.applet.*;
import java.awt.*;

public class CheckerApplet extends Applet {


JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
int squareSize = 50; // initialized to default size
public void init() {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
Here are CheckerApplet's init() and private parseSquareSize() methods −
public void init () {
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);

String colorParam = getParameter ("color");


Color fg = parseColor (colorParam);

setBackground (Color.black);
setForeground (fg);
}

private void parseSquareSize (String param) {


if (param == null) return;
try {
squareSize = Integer.parseInt (param);
} catch (Exception e) {
// Let default value remain
}
}
The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls
the library method Integer.parseInt(), which parses a string and returns an integer.
Integer.parseInt() throws an exception whenever its argument is invalid.
Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad
input.
The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does
a series of string comparisons to match the parameter value to the name of a predefined color.
You need to implement these methods to make this applet work.

Specifying Applet Parameters


The following is an example of an HTML file with a CheckerApplet embedded in it. The
HTML file specifies both parameters to the applet by means of the <param> tag.
<html>
<title>Checkerboard Applet</title>
<hr>
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
<applet code = "CheckerApplet.class" width = "480" height = "320">
<param name = "color" value = "blue">
<param name = "squaresize" value = "30">
</applet>
<hr>
</html>
Note − Parameter names are not case sensitive.

Application Conversion to Applets

It is easy to convert a graphical Java application (that is, an application that uses the AWT and
that you can start with the Java program launcher) into an applet that you can embed in a web
page.
Following are the specific steps for converting an application to an applet.
• Make an HTML page with the appropriate tag to load the applet code.
• Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet
cannot be loaded.
• Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.
• Move any initialization code from the frame window constructor to the init method of
the applet. You don't need to explicitly construct the applet object. The browser
instantiates it for you and calls the init method.
• Remove the call to setSize; for applets, sizing is done with the width and height
parameters in the HTML file.
• Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates
when the browser exits.
• If the application calls setTitle, eliminate the call to the method. Applets cannot have title
bars. (You can, of course, title the web page itself, using the HTML title tag.)
• Don't call setVisible(true). The applet is displayed automatically.

Example program that demonstrates the life cycle of an applet is as follows:


1 import java.awt.*;
2 import java.applet.*;
3 public class MyApplet extends Applet
4 {
5 public void init()
6 {
7 System.out.println("Applet initialized");

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


8 }
9 public void start()
10 {
11 System.out.println("Applet execution started");
12 }
13 public void stop()
14 {
15 System.out.println("Applet execution stopped");
16 }
17 public void paint(Graphics g)
18 {
19 System.out.println("Painting...");
20 }
21 public void destroy()
22 {
23 System.out.println("Applet destroyed");
24 }
25 }

Output of the above applet program when run using appletviewer tool is:
Applet initialized
Applet execution started
Painting…
Painting…
Applet execution stopped
Applet destroyed

Event Handling
Applets inherit a group of event-handling methods from the Container class. The Container
class defines several methods, such as processKeyEvent and processMouseEvent, for handling
particular types of events, and then one catch-all method called processEvent.
In order to react to an event, an applet must override the appropriate event-specific method.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;

public class ExampleEventHandling extends Applet implements MouseListener {


StringBuffer strBuffer;

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


public void init() {
addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}

public void start() {


addItem("starting the applet ");
}

public void stop() {


addItem("stopping the applet ");
}

public void destroy() {


addItem("unloading the applet");
}

void addItem(String word) {


System.out.println(word);
strBuffer.append(word);
repaint();
}

public void paint(Graphics g) {


// Draw a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);

// display the string inside the rectangle.


g.drawString(strBuffer.toString(), 10, 20);
}

public void mouseEntered(MouseEvent event) {


}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
addItem("mouse clicked! ");

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


}
}
Now, let us call this applet as follows −
<html>
<title>Event Handling</title>
<hr>
<applet code = "ExampleEventHandling.class"
width = "300" height = "300">
</applet>
<hr>
</html>
Initially, the applet will display "initializing the applet. Starting the applet." Then once you click
inside the rectangle, "mouse clicked" will be displayed as well.

Displaying Images

An applet can display images of the format GIF, JPEG, BMP, and others. To display an image
within the applet, you use the drawImage() method found in the java.awt.Graphics class.
Following is an example illustrating all the steps to show images −
import java.applet.*;
import java.awt.*;
import java.net.*;

public class ImageDemo extends Applet {


private Image image;
private AppletContext context;

public void init() {


context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null) {
imageURL = "java.jpg";
}
try {
URL url = new URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
} catch (MalformedURLException e) {
e.printStackTrace();
// Display in browser status bar
context.showStatus("Could not load image!");
}
}

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


public void paint(Graphics g) {
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.javalicense.com", 35, 100);
}
}
Now, let us call this applet as follows −
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code = "ImageDemo.class" width = "300" height = "200">
<param name = "image" value = "java.jpg">
</applet>
<hr>
</html>

Playing Audio
An applet can play an audio file represented by the AudioClip interface in the java.applet
package. The AudioClip interface has three methods, including −
• public void play() − Plays the audio clip one time, from the beginning.
• public void loop() − Causes the audio clip to replay continually.
• public void stop() − Stops playing the audio clip.
To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class.
The getAudioClip() method returns immediately, whether or not the URL resolves to an actual
audio file. The audio file is not downloaded until an attempt is made to play the audio clip.
Following is an example illustrating all the steps to play an audio −
import java.applet.*;
import java.awt.*;
import java.net.*;

public class AudioDemo extends Applet {


private AudioClip clip;
private AppletContext context;

public void init() {


context = this.getAppletContext();
String audioURL = this.getParameter("audio");
if(audioURL == null) {

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


audioURL = "default.au";
}
try {
URL url = new URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
} catch (MalformedURLException e) {
e.printStackTrace();
context.showStatus("Could not load audio file!");
}
}

public void start() {


if(clip != null) {
clip.loop();
}
}

public void stop() {


if(clip != null) {
clip.stop();
}
}
}
Now, let us call this applet as follows −
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code = "ImageDemo.class" width = "0" height = "0">
<param name = "audio" value = "test.wav">
</applet>
<hr>
</html>
You can use test.wav on your PC to test the above example.

Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.

Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of
OS.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.

Container

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Window

The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default false.

Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.

1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


5. b.setBounds(30,100,80,30);// setting button position
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300 height
8. setLayout(null);//no layout manager
9. setVisible(true);//now frame will be visible, by default not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. }}

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example
that sets the position of the awt button.

AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
showing Button component on the Frame.

1. import java.awt.*;
2. class First2{
3. First2(){
4. Frame f=new Frame();
5. Button b=new Button("click me");
6. b.setBounds(30,50,80,30);
7. f.add(b);
8. f.setSize(300,300);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. First2 f=new First2();
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
14. }}

Java AWT Button


The button class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed.

AWT Button Class declaration

1. public class Button extends Component implements Accessible

Java AWT Button Example

1. import java.awt.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. Frame f=new Frame("Button Example");
5. Button b=new Button("Click Here");
6. b.setBounds(50,100,80,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }

Output:

Java AWT Label


JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
The object of Label class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly.

AWT Label Class Declaration


1. public class Label extends Component implements Accessible

Java Label Example


1. import java.awt.*;
2. class LabelExample{
3. public static void main(String args[]){
4. Frame f= new Frame("Label Example");
5. Label l1,l2;
6. l1=new Label("First Label.");
7. l1.setBounds(50,100, 100,30);
8. l2=new Label("Second Label.");
9. l2.setBounds(50,150, 100,30);
10. f.add(l1); f.add(l2);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14. }
15. }

Output:

Java AWT TextField


The object of a TextField class is a text component that allows the editing of a single line text. It
inherits TextComponent class.

AWT TextField Class Declaration


1. public class TextField extends TextComponent
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Java AWT TextField Example
1. import java.awt.*;
2. class TextFieldExample{
3. public static void main(String args[]){
4. Frame f= new Frame("TextField Example");
5. TextField t1,t2;
6. t1=new TextField("Welcome to Javatpoint.");
7. t1.setBounds(50,100, 200,30);
8. t2=new TextField("AWT Tutorial");
9. t2.setBounds(50,150, 200,30);
10. f.add(t1); f.add(t2);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14. }
15. }

Output:

Java AWT TextArea


The object of a TextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.

AWT TextArea Class Declaration


1. public class TextArea extends TextComponent

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Java AWT TextArea Example
1. import java.awt.*;
2. public class TextAreaExample
3. {
4. TextAreaExample(){
5. Frame f= new Frame();
6. TextArea area=new TextArea("Welcome to javatpoint");
7. area.setBounds(10,30, 300,300);
8. f.add(area);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. {
15. new TextAreaExample();
16. }
17. }

Output:

Java AWT Checkbox


The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".

AWT Checkbox Class Declaration

1. public class Checkbox extends Component implements ItemSelectable, Accessible


Java AWT Choice
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration


1. public class Choice extends Component implements ItemSelectable, Accessible

Java AWT Choice Example


1. import java.awt.*;
2. public class ChoiceExample
3. {
4. ChoiceExample(){
5. Frame f= new Frame();
6. Choice c=new Choice();
7. c.setBounds(100,100, 75,75);
8. c.add("Item 1");
9. c.add("Item 2");
10. c.add("Item 3");
11. c.add("Item 4");
12. c.add("Item 5");
13. f.add(c);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ChoiceExample();
21. }
22. }

Output:

Java AWT List

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


The object of List class represents a list of text items. By the help of list, user can choose either
one item or multiple items. It inherits Component class.

AWT List class Declaration

1. public class List extends Component implements ItemSelectable, Accessible

Java AWT List Example

1. import java.awt.*;
2. public class ListExample
3. {
4. ListExample(){
5. Frame f= new Frame();
6. List l1=new List(5);
7. l1.setBounds(100,100, 75,75);
8. l1.add("Item 1");
9. l1.add("Item 2");
10. l1.add("Item 3");
11. l1.add("Item 4");
12. l1.add("Item 5");
13. f.add(l1);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }
22. }

Output:

Java AWT List Example with ActionListener


JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
import java.awt.*;
import java.awt.event.*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(500,100);
Button b=new Button("Show");
b.setBounds(200,150,80,30);
final List l1=new List(4, false);
l1.setBounds(100,100, 70,70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
final List l2=new List(4, true);
l2.setBounds(100,200, 70,70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("CodeIgniter");
f.add(l1); f.add(l2); f.add(label); f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+l1.getItem(l1.getSelectedIndex());
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems()){
data += frame + " ";
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample();
} }
Output:
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.

AWT Scrollbar class declaration


1. public class Scrollbar extends Component implements Adjustable, Accessible

Java AWT Scrollbar Example


1. import java.awt.*;
2. class ScrollbarExample{
3. ScrollbarExample(){
4. Frame f= new Frame("Scrollbar Example");
5. Scrollbar s=new Scrollbar();
6. s.setBounds(100,100, 50,100);
7. f.add(s);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. new ScrollbarExample();
14. }
15. }

Output:

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Java AWT Checkbox Example

1. import java.awt.*;
2. public class CheckboxExample
3. {
4. CheckboxExample(){
5. Frame f= new Frame("Checkbox Example");
6. Checkbox checkbox1 = new Checkbox("C++");
7. checkbox1.setBounds(100,100, 50,50);
8. Checkbox checkbox2 = new Checkbox("Java", true);
9. checkbox2.setBounds(100,150, 50,50);
10. f.add(checkbox1);
11. f.add(checkbox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckboxExample();
19. }
20. }

Output:

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Java Layout Managers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is
an interface that is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


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

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.

EXAMPLE OF BORDER LAYOUT CLASS

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

public class Border {


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

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


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

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

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

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The
java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the registration methods.
For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code

We can put the event handling code into one of the following places:
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
14. b.addActionListener(this);//passing current instance
15.
16. //add components and set size, layout and visibility
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
27. }
28. }

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


2) Java event handling by outer class
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new Button("click me");
10. b.setBounds(100,120,80,30);
11. //register listener
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class instance
14. //add components and set size, layout and visibility
15. add(b);add(tf);
16. setSize(300,300);
17. setLayout(null);
18. setVisible(true);
19. }
20. public static void main(String args[]){
21. new AEvent2();
22. }
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
23. }
1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }

3) Java event handling by anonymous class


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
16. add(b);add(tf);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
23. }
24. }

Event Handling
Event Delegation Model

Defines standard and consistent mechanism to generate and process events.

Concept:

A source generates an event and sends it to one or more listeners. Listener simply waits until it
receives an event. Listener processes events and then returns. User interface element is able to
"delegate" the processing of an event to a separate piece of code. Notifications are sent only to
those listeners that want to receive them.

Old Approach (Java 1.1)

Event was propagated up the containment hierarchy until it was handled by a component.

Event

In the delegation model, an event is an object that describes a state change in a source.

Event Source

A source is an object that generates an event. This occurs when object changes in some way.
Source may generate more than one type of event. A source must register listeners in order for
the listeners to receive notifications about a specific type of event. Each type of event has its own
registration method.

General form:

public void addTypeListener (TypeListener el)

When an event occurs, all registered listeners are notified and receive a copy of the event object.
It is called Multicasting the event. Some sources may allow only one listener to register.

General form:

public void addTypeListener (TypeListener el) throws java.util.TooManyListenersException

To remove Listener

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Public void removeTypeListener (TypeListener el)

Event Listener

A listener is an object that is notified when an event occurs.

• Must have registered with one or more sources to receive notifications about specific
types of events
• Must implement methods to receive and process these notifications

Event Classes

At root of Java event class hierarchy is EventObject, which is in java.util.

EventObject (Object src)

Contains 2 methods:

Object getSource()

String toString()

AWT Event class defined in java.awt package is a subclass of Event Object. It is superclass
(directly or indirectly) of all AWT-based events handled by delegation model. Method getID ()
can be used to determine the type of event.

Main Event Classes in java.awt.event

Event Class Description

ActionEvent Generated when a button is pressed, a list is double-


clicked, or a menu item is selected.

AdjustmentEvent Generated when a scroll bar is manipulated.

ContainerEvent Generated when a component is added to or removed


from a container.

FocusEvent Generated when a component gains or loses keyboard


focus.

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


InputEvent Abstract super class for all component input event
classes.

ItemEvent Generated when a check box or a list item is clicked; also


occurs when a choice selection is made or a checkable
menu is selected or deselected.

KeyEvent Generated when input is received from the keyboard.

MouseEvent Generated when the mouse is dragged, moved, clicked,


pressed, or released; also generated when the mouse
enters or exits a component.

TextEvent Generated when the value of a textarea or textfield is


changed.

WindowEvent Generated when a window os activated, closed,


deactivated, deiconified,iconified, opened, or quit.

Sources of Events

Event Source
Button
Checkbox
Choice
List
Menu Item
Scrollbar
Text Components
Window

Event Listener

Methods in Interfaces:

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


ActionListener

void actionPerformed (ActionEvent ae)

AdjustmentListener

void adjustmentValueChanged (AdjustmentEvent ae)

ComponentListener

void componentResized (ComponentEvent ce)


void componentMoved (ComponentEvent ce)
void componentShown (ComponentEvent ce)
void componentHidden (ComponentEvent ce)

ContainerListener
void componentAdded (ContainerEvent ce)
void componentRemoved (ContainerEvent ce)
FocusListener
void focusGained (FocusEvent fe)

void focusLost (FocusEvent fe)

ItemListener

void itemStateChanged (ItemEvent ie)

KeyListener

void keyPressed (KeyEvent ke)


void keyReleased (KeyEvent ke)
void keyTyped (KeyEvent ke)

MouseListener
void mouseClicked (MouseEvent me)
void mouseEntered (MouseEvent me)
void mouseExited (MouseEvent me)
void mousePressed (MouseEvent me)
void mouseReleased (MouseEvent me)

MouseMotionListener

void mouseDragged (MouseEvent me)


void mouseMoved (MouseEvent me)

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


TextListener

void textChanged (TextEvent te)

WindowListener

void windowActivated (WindowEvent we)


void windowClosed (WindowEvent we)
void windowClosing (WindowEvent we)
void windowDeactivated (WindowEvent we)
void windowDeiconified (WindowEvent we)
void windowIconified (WindowEvent we)
void windowOpened (WindowEvent we)

Adapter Class

Provides an empty implementation of all methods in an event listener interface.Useful when u


want to listen and process only some of the events that are handled by one particular event
listener interface.
Define your own class as subclass of this class and provide desired implementation.
Listener Interfaces implemented by Adapter classes
Adapter Class Listener Interface

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

FocusAdapter FocusListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

WindowAdapter WindowListener

Sample Code

import java.awt.*;

import java.awt.event.*;

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


import java.applet.*;

/*

<applet code="AdapterDemo" width=300 height=100>

</applet>

*/public class AdapterDemo extends Applet {

public void init () {

addMouseListener(new MyMouseAdapter (this));

addMouseMotionListener(new MyMouseMotionAdapter (this));

class MyMouseAdapter extends MouseAdapter {

AdapterDemo adapterDemo;

public MyMouseAdapter(AdapterDemo adapterDemo) {

this.adapterDemo = adapterDemo;

// Handle mouse clicked

public void mouseClicked (MouseEvent me) {

adapterDemo.showStatus ("Mouse Clicked");

class MyMouseMotionAdapter extends MouseMotionAdapter {

AdapterDemo adapterDemo;

public MyMouseMotionAdapter (AdapterDemo adapterDemo) {


JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
this. adapterDemo = adapterDemo;

// Handle Mouse Drag

public void mouseDragged (MouseEvent me) {

adapterDemo.showStatus("Mouse Dragged");

Inner Class

Normal Case

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="MousePressedDemo" width=300 height=100>

</applet>

*/

public class MousePressedDemo extends Applet {

public void init () {

addMouseListener(new MyMouseAdapter (this));

class MyMouseAdapter extends MouseAdapter {

MousePressedDemo mousePressedDemo;
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
public MyMouseAdapter (MousePressedDemo mousePressedDemo) {

this.mousePressedDemo = mousePressedDemo;

// Handle mouse clicked

public void mouseClicked (MouseEvent me) {

mousePressedDemo.showStatus ("Mouse Clicked");

Modified Version

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="InnerClassDemo" width=300 height=100>

</applet>

*/

public class InnerClassDemo extends Applet {

public void init () {

addMouseListener(new MyMouseAdapter ());

class MyMouseAdapter extends MouseAdapter {

public void mouseClicked (MouseEvent me) {

showStatus ("Mouse Clicked");


JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
}

Anonymous Inner Classes

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code=" AnonymousInnerClassDemo" width=300 height=100>

</applet>

*/

public class AnonymousInnerClassDemo extends Applet {

public void init () {

addMouseListener(new MyMouseAdapter () {

public void mouseClicked (MouseEvent me) {

showStatus ("Mouse Clicked");

});

Java Swing

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


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

Unlike AWT, Java Swing provides platform-independent and lightweight components.

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

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

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


independent.

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

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

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

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


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

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


UNIT 4

Java - Networking
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.
The java.net package provides support for the two common network protocols −
• TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
• UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.
This chapter gives a good understanding on the following two subjects −
• Socket Programming − This is the most widely used concept in Networking and it has
been explained in very detail.
• URL Processing − This would be covered separately. Click here to learn about URL
Processing in Java language.
Socket Programming
Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket to
a server.
When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and reading from
the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using
sockets −
• The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
• The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.
• After the server is waiting, a client instantiates a Socket object, specifying the server
name and the port number to connect to.
• The constructor of the Socket class attempts to connect the client to the specified server
and the port number. If communication is established, the client now has a Socket object
capable of communicating with the server.
• On the server side, the accept() method returns a reference to a new socket on the server
that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket
has both an OutputStream and an InputStream. The client's OutputStream is connected to the
server's InputStream, and the client's InputStream is connected to the server's OutputStream.
TCP is a two-way communication protocol, hence data can be sent across both streams at the
same time. Following are the useful classes providing complete set of methods to implement
sockets.

ServerSocket Class Methods


The java.net.ServerSocket class is used by server applications to obtain a port and listen for
client requests.
The ServerSocket class has four constructors −

Sr.No. Method & Description

public ServerSocket(int port) throws IOException


1
Attempts to create a server socket bound to the specified port. An
exception occurs if the port is already bound by another application.

public ServerSocket(int port, int backlog) throws IOException


2
Similar to the previous constructor, the backlog parameter specifies how
many incoming clients to store in a wait queue.

public ServerSocket(int port, int backlog, InetAddress address)


throws IOException
3
Similar to the previous constructor, the InetAddress parameter specifies
the local IP address to bind to. The InetAddress is used for servers that
may have multiple IP addresses, allowing the server to specify which of

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


its IP addresses to accept client requests on.

public ServerSocket() throws IOException


4
Creates an unbound server socket. When using this constructor, use the
bind() method when you are ready to bind the server socket.

If the ServerSocket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.
Following are some of the common methods of the ServerSocket class −

Sr.No. Method & Description

public int getLocalPort()


1 Returns the port that the server socket is listening on. This method is
useful if you passed in 0 as the port number in a constructor and let the
server find a port for you.

public Socket accept() throws IOException

2 Waits for an incoming client. This method blocks until either a client
connects to the server on the specified port or the socket times out,
assuming that the time-out value has been set using the setSoTimeout()
method. Otherwise, this method blocks indefinitely.

public void setSoTimeout(int timeout)


3
Sets the time-out value for how long the server socket waits for a client
during the accept().

public void bind(SocketAddress host, int backlog)


4 Binds the socket to the specified server and port in the SocketAddress
object. Use this method if you have instantiated the ServerSocket using
the no-argument constructor.

When the ServerSocket invokes accept(), the method does not return until a client connects.
After a client does connect, the ServerSocket creates a new Socket on an unspecified port and
returns a reference to this new Socket. A TCP connection now exists between the client and the
server, and communication can begin.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Socket Class Methods
The java.net.Socket class represents the socket that both the client and the server use to
communicate with each other. The client obtains a Socket object by instantiating one, whereas
the server obtains a Socket object from the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server −

Sr.No. Method & Description

public Socket(String host, int port) throws UnknownHostException,


IOException.
1
This method attempts to connect to the specified server at the specified
port. If this constructor does not throw an exception, the connection is
successful and the client is connected to the server.

public Socket(InetAddress host, int port) throws IOException


2
This method is identical to the previous constructor, except that the host
is denoted by an InetAddress object.

public Socket(String host, int port, InetAddress localAddress, int


3 localPort) throws IOException.
Connects to the specified host and port, creating a socket on the local
host at the specified address and port.

public Socket(InetAddress host, int port, InetAddress localAddress,


4 int localPort) throws IOException.
This method is identical to the previous constructor, except that the host
is denoted by an InetAddress object instead of a String.

public Socket()
5
Creates an unconnected socket. Use the connect() method to connect this
socket to a server.

When the Socket constructor returns, it does not simply instantiate a Socket object but it
actually attempts to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and the
server have a Socket object, so these methods can be invoked by both the client and the server.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Sr.No. Method & Description

public void connect(SocketAddress host, int timeout) throws


IOException
1
This method connects the socket to the specified host. This method is
needed only when you instantiate the Socket using the no-argument
constructor.

public InetAddress getInetAddress()


2
This method returns the address of the other computer that this socket is
connected to.

3 public int getPort()


Returns the port the socket is bound to on the remote machine.

4 public int getLocalPort()


Returns the port the socket is bound to on the local machine.

5 public SocketAddress getRemoteSocketAddress()


Returns the address of the remote socket.

public InputStream getInputStream() throws IOException


6
Returns the input stream of the socket. The input stream is connected to
the output stream of the remote socket.

public OutputStream getOutputStream() throws IOException


7
Returns the output stream of the socket. The output stream is connected
to the input stream of the remote socket.

public void close() throws IOException


8
Closes the socket, which makes this Socket object no longer capable of
connecting again to any server.

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


InetAddress Class Methods
This class represents an Internet Protocol (IP) address. Here are following usefull methods
which you would need while doing socket programming −

Sr.No. Method & Description

1 static InetAddress getByAddress(byte[] addr)


Returns an InetAddress object given the raw IP address.

2 static InetAddress getByAddress(String host, byte[] addr)


Creates an InetAddress based on the provided host name and IP address.

3 static InetAddress getByName(String host)


Determines the IP address of a host, given the host's name.

4 String getHostAddress()
Returns the IP address string in textual presentation.

5 String getHostName()
Gets the host name for this IP address.

6 static InetAddress InetAddress getLocalHost()


Returns the local host.

7 String toString()
Converts this IP address to a String.

Socket Client Example


The following GreetingClient is a client program that connects to a server by using a socket and
sends a greeting, and then waits for a response.
Example
// File Name GreetingClient.java
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
import java.net.*;
import java.io.*;

public class GreetingClient {

public static void main(String [] args) {


String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);

System.out.println("Just connected to " + client.getRemoteSocketAddress());


OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);

out.writeUTF("Hello from " + client.getLocalSocketAddress());


InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);

System.out.println("Server says " + in.readUTF());


client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Socket Server Example


The following GreetingServer program is an example of a server application that uses the
Socket class to listen for clients on a port number specified by a command-line argument −
Example
// File Name GreetingServer.java
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread {


private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException {


serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();

System.out.println("Just connected to " + server.getRemoteSocketAddress());


DataInputStream in = new DataInputStream(server.getInputStream());

System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
+ "\nGoodbye!");
server.close();

} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}

public static void main(String [] args) {


int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Compile the client and the server and then start the server as follows −
$ java GreetingServer 6066
Waiting for client on port 6066...
Check the client program as follows −
Output
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!

JDBC
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac
OS, and the various versions of UNIX.
What is JDBC?
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.

Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but
in general, JDBC Architecture consists of two layers −
• JDBC API: This provides the application-to-JDBC Manager connection.
• JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −

Common JDBC Components


The JDBC API provides the following interfaces and classes −
• DriverManager: This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication
sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
• Driver: This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager objects,

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


which manages objects of this type. It also abstracts the details associated with working
with Driver objects.
• Connection: This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
• Statement: You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
• ResultSet: These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its
data.
• SQLException: This class handles any errors that occur in a database application.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC
version at the time of writing this tutorial. It offers the main classes for interacting with your
data sources.
The new features in these packages include changes in the following areas −
• Automatic database driver loading.
• Exception handling improvements.
• Enhanced BLOB/CLOB functionality.
• Connection and statement interface enhancements.
• National character set support.
• SQL ROWID access.
• SQL 2003 XML data type support.
• Annotations.
JDBC - SQL Syntax
Structured Query Language (SQL) is a standardized language that allows you to perform
operations on a database, such as creating entries, reading content, updating content, and
deleting entries.
SQL is supported by almost any database you will likely use, and it allows you to write
database code independently of the underlying database.
This chapter gives an overview of SQL, which is a prerequisite to understand JDBC concepts.
After going through this chapter, you will be able to Create, Create, Read, Update, and Delete
(often referred to as CRUD operations) data from a database.
For a detailed understanding on SQL, you can read our MySQL Tutorial.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Create Database
The CREATE DATABASE statement is used for creating a new database. The syntax is −
SQL> CREATE DATABASE DATABASE_NAME;

Example
The following SQL statement creates a Database named EMP −
SQL> CREATE DATABASE EMP;

Drop Database
The DROP DATABASE statement is used for deleting an existing database. The syntax is −
SQL> DROP DATABASE DATABASE_NAME;
Note: To create or drop a database you should have administrator privilege on your database
server. Be careful, deleting a database would loss all the data stored in the database.
Create Table
The CREATE TABLE statement is used for creating a new table. The syntax is −
SQL> CREATE TABLE table_name
(
column_name column_data_type,
column_name column_data_type,
column_name column_data_type
...
);

Example
The following SQL statement creates a table named Employees with four columns −
SQL> CREATE TABLE Employees
(
id INT NOT NULL,
age INT NOT NULL,
first VARCHAR(255),
last VARCHAR(255),
PRIMARY KEY ( id )
);

Drop Table
The DROP TABLE statement is used for deleting an existing table. The syntax is −
SQL> DROP TABLE table_name;
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Example
The following SQL statement deletes a table named Employees −
SQL> DROP TABLE Employees;

INSERT Data
The syntax for INSERT, looks similar to the following, where column1, column2, and so on
represents the new data to appear in the respective columns −
SQL> INSERT INTO table_name VALUES (column1, column2, ...);

Example
The following SQL INSERT statement inserts a new row in the Employees database created
earlier −
SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');

SELECT Data
The SELECT statement is used to retrieve data from a database. The syntax for SELECT is −
SQL> SELECT column_name, column_name, ...
FROM table_name
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as
the BETWEEN and LIKE operators.
Example
The following SQL statement selects the age, first and last columns from the Employees table,
where id column is 100 −
SQL> SELECT first, last, age
FROM Employees
WHERE id = 100;
The following SQL statement selects the age, first and last columns from the Employees table
where first column contains Zara −
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE '%Zara%';

UPDATE Data
The UPDATE statement is used to update data. The syntax for UPDATE is −
SQL> UPDATE table_name
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
SET column_name = value, column_name = value, ...
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as
the BETWEEN and LIKE operators.
Example
The following SQL UPDATE statement changes the age column of the employee whose id is
100 −
SQL> UPDATE Employees SET age=20 WHERE id=100;

DELETE Data
The DELETE statement is used to delete data from tables. The syntax for DELETE is −
SQL> DELETE FROM table_name WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as
the BETWEEN and LIKE operators.
Example
The following SQL DELETE statement deletes the record of the employee whose id is 100 −
SQL> DELETE FROM Employees WHERE id=100;

Servlets
Servlets provide a component-based, platform-independent method for building Webbased
applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial
will teach you how to use Java Servlets to develop your web based applications in simple and
easy steps.

What are Servlets?


Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from
a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
• Performance is significantly better.
• Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.

Applications of Servlet
• Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.
• Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This document can
be sent in a variety of formats, including text (HTML or XML), binary (GIF images),
Excel, etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.

Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java
Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a
standard part of the Java's enterprise edition, an expanded version of the Java class library that
supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of writing this
tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any other Java class. After you install the
servlet packages and add them to your computer's Classpath, you can compile servlets with the
JDK's Java compiler or any other current compiler.

Servlets - Life Cycle

A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet.
• The servlet is initialized by calling the init() method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in detail.
The init() Method
The init method is called only once. It is called only when the servlet is created, and not called
for any user requests afterwards. So, it is used for one-time initializations, just as with the init
method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException {
// Initialization code...
}

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


The service() Method
The service() method is the main method to perform the actual task. The servlet container (i.e.
web server) calls the service() method to handle requests coming from the client( browsers) and
to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method
but you override either doGet() or doPost() depending on what type of request you receive from
the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here
is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and
it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() Method


The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write cookie
lists or hit counts to disk, and perform other such cleanup activities.

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this −
public void destroy() {
// Finalization code...
}

Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet container.
• The servlet container loads the servlet before invoking the service() method.
• Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.

Servlets are Java classes which service HTTP requests and implement
the javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and
is specially designed to handle HTTP requests.

Sample Code
Following is the sample source code structure of a servlet example to show Hello World −
// Import required java libraries
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}
}

Compiling a Servlet
Let us create a file with name HelloWorld.java with the code shown above. Place this file at
C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path location must be
added to CLASSPATH before proceeding further.
Assuming your environment is setup properly, go in ServletDevel directory and compile
HelloWorld.java as follows −
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on your
CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any
other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun Microsystems Java
Software Development Kit (JDK). For this command to work properly, you have to include the
location of the Java SDK that you are using in the PATH environment variable.

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


If everything goes fine, above compilation would produce HelloWorld.class file in the same
directory. Next section would explain how a compiled servlet would be deployed in production.

Servlet Deployment
By default, a servlet application is located at the path <Tomcat-
installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must
be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat installationdirectory>/webapps/ROOT/WE
B-INF/classes and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in web.xml file.
There could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-
installationdirectory>\bin\startup.bat (on Windows) or <Tomcat-
installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally
type http://localhost:8080/HelloWorld in the browser's address box. If everything goes fine,
you would get the following result

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Java program to show servlet example
// Importing required Java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class AdvanceJavaConcepts extends HttpServlet
{
private String output;

// Initializing servelet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}

// Requesting and printing the output


public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(output);
}

public void destroy()


{
System.out.println("Over");
}
}

Steps to create a servlet example


1. Steps to create the servlet using Tomcat server
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the application
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
There are given 6 steps to create a servlet example. These steps are required for all the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

1) Create a directory structures

The directory structure defines that where to put the different types of files so that web
container may get the information and respond to the client.

2) Create a Servlet
There are three ways to create the servlet.

1. By implementing the Servlet interface


2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests s
doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inhe
the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the d
request.

DemoServlet.java

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data
10. //writing html in the stream
11. pw.println("<html><body>");
12. pw.println("Welcome to servlet");
13. pw.println("</body></html>");
14.
15. pw.close();//closing the stream
16. }}

3) Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar
files:

Jar file Server

1) servlet-api.jar Apache Tomcat

2) weblogic.jar Weblogic

3) javaee.jar Glassfish

4) javaee.jar JBoss

Two ways to load the jar file

1. set classpath
2. paste the jar file in JRE/lib/ext folder

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


Put the java file in any folder. After compiling the java file, paste the class file of servlet
in WEB-INF/classes directory.

4) Create the deployment descriptor (web.xml file)

The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.

The web container uses the Parser to get the information from the web.xml file. There are many
xml parsers such as SAX, DOM and Pull.

There are many elements in the web.xml file. Here is given some necessary elements to run the
simple servlet program.

web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>

Description of the elements of web.xml file

There are too many elements in the web.xml file. Here is the illustration of some elements that is
used in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.

5) Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.

One Time Configuration for Apache Tomcat Server

You need to perform 2 tasks:

1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).


2. Change the port number of tomcat (optional). It is required if another server is running on
same port (8080).

1) How to set JAVA_HOME in environment variable?

To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment
variables.

Go to My Computer properties -> Click on advanced tab then environment variables -> Click on
the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk
folder in variable value -> ok -> ok -> ok.

Go to My Computer properties:

Click on advanced system settings tab then environment variables:

Click on the new tab of user variable or system variable:

Write JAVA_HOME in variable name and paste the path of jdk folder in variable value:

There must not be semicolon (;) at the end of the path.

After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin.

Note: There are two types of tomcat available:

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


1. Apache tomcat that needs to extract only (no need to install)
2. Apache tomcat that needs to install

It is the example of apache tomcat that needs to extract only.

Now server is started successfully.

2) How to change port number of apache tomcat

Changing the port number is required if there is another server running on the same system with
same port number.Suppose you have installed oracle, you need to change the port number of
apache tomcat because both have the default port number 8080.

Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change
the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us
replace it by 9999 and save this file.

3) How to deploy the servlet project

Copy the project and paste it in the webapps folder under apache tomcat.

But there are several ways to deploy the project. They are as follows:

o By copying the context(project) folder into the webapps directory


o By copying the war folder into the webapps directory
o By selecting the folder path from the server
o By selecting the war file from the server

Here, we are using the first approach.

You can also create war file, and paste it inside the webapps directory. To do so, you need to use
jar tool to create the war file. Go inside the project directory (before the WEB-INF), then write:

1. projectfolder> jar cvf myproject.war *

Creating war file has an advantage that moving the project from one location to another takes
less time.

4) How to access the Servlet

Open browser and write http://hostname:portno/contextroot/urlpatternofservlet. For example:

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA


1. http://localhost:9999/demo/welcome

JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA

You might also like