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

Sec-A Adv. Java Lab File-2024-2025

Uploaded by

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

Sec-A Adv. Java Lab File-2024-2025

Uploaded by

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

INDEX

S.N Date of Date of Teacher’s


Name of Experiment Remarks
O. Experiment Submission Signature

1. Write a Java program to create an applet


to draw a string “Hello”.

2. Write a Java program to pass parameters


from one applet to another.

3. Write a Java program to create a GUI


based applet to perform arithmetic
operations.
4. Write a Java program to design a
registration form using java swing.

5. Write a Java program to implement event


handling using swing to make a mini
calculator using java swing.
6. Write a JDBC program to read records
from a table in a specific database.
7. Write a JDBC program to
read/write/update records from/to/in a
table in a specific database.
8. Create a JSP page to display Hello.
9. Create a JSP page which receives two
integers from a HTML page and
calculates the sum of them.
10. Design a JSP page to calculate
the area of a circle, square and
rectangle.
11. Write a Java program to design a JSP
page for currency converter.
12. Write a Java program to design a servlet
that takes all the input from webpage and
display the same through servlet.
13. Write a Java program to design a servlet
that add two numbers received from the
web pages and display the same.
14. Write a Java program to create a
connection oriented sender-receiver
application using TCP.
15. Write a Java program to create a
connectionless sender-receiver
application using UDP.
16. Rubrics Evaluation
ADVANCE JAVA Lab 5CS4-24

EXPERIMENT NO. 1
AIM: Write a Java program to create an applet to draw a string “Hello”.
What is Applet?
An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side. An applet is embedded in an HTML page using the APPLET
or OBJECT tag and hosted on a web server.
Applets are used to make the website more dynamic and entertaining.
Important points :

1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.


2. Applets are not stand-alone programs. Instead, they run within either a web browser or
an applet viewer. JDK provides a standard applet viewer tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is
handled with various AWT methods, such as drawString().

Life cycle of an applet :

It is important to understand the order in which the various methods shown in the above image
are called. When an applet begins, the following methods are called, in this sequence:

1. init( )
2. start( )
3. paint( )

When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

Let’s look more closely at these methods.

1. init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.

2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it
has been stopped. Note that init( ) is called once i.e. when the first time an applet is loaded
whereas start( ) is called each time an applet’s HTML document is displayed onscreen. So, if
a user leaves a web page and comes back, the applet resumes execution at start( ).

3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output
must be redrawn. This situation can occur for several reasons. For example, the window
in which the applet is running may be overwritten by another window and then
uncovered. Or the applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever
the applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain
the graphics context, which describes the graphics environment in which the applet is
running. This context is used whenever output to the applet is required.
Note: This is the only method among all the method mention above, which is
parameterized. It’s prototype is
public void paint(Graphics g)
where g is an object reference of class Graphic.

4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is called, the
applet is probably running. You should use stop( ) to suspend threads that don’t need to run
when the applet is not visible. You can restart them when start( ) is called if the user returns to
the page.
5. destroy( ) : The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).
Program:
// A Hello World Applet
// Save file as HelloWorld.java
import java.applet.Applet;
import java.awt.Graphics;
// HelloWorld class extends Applet
public class HelloWorld extends Applet
{ // Overriding paint() method
@Override
public void paint(Graphics g)
{ g.drawString("Hello World", 20, 20);
}}
Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not
begin execution at main( ). In fact, most applets don’t even have a main( ) method. Instead, an
applet begins execution when the name of its class is passed to an applet viewer or to a
network browser.
Running the HelloWorld Applet :
After you enter the source code for HelloWorld.java, compile in the same way that you have
been compiling java programs(using javac command). However, running HelloWorld with the
java command will generate an error because it is not an application.

There are two standard ways in which you can run an applet :

1. Executing the applet within a Java-compatible web browser.


2. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer
executes your applet in a window. This is generally the fastest and easiest way to test
your applet.

Each of these methods is described next.

1. Using java enabled web browser : To execute an applet in a web browser we have to write
a short HTML text file that contains a tag that loads the applet. We can use APPLET or
OBJECT tag for this purpose. Using APPLET, here is the HTML file that executes
HelloWorld :

<applet code="HelloWorld" width=200 height=60>


</applet>

The width and height statements specify the dimensions of the display area used by the applet.
The APPLET tag contains several other options. After you create this html file, you can use it
to execute the applet.

NOTE : Chrome and Firefox no longer supports NPAPI (technology required for Java
applets).

2. Using appletviewer : This is the easiest way to run an applet. To execute HelloWorld with
an applet viewer, you may also execute the HTML file shown earlier. For example, if the
preceding HTML file is saved with
RunHelloWorld.html, then the following command line will run HelloWorld :

appletviewer RunHelloWorld.html
Output:
EXPERIMENT NO. 4

AIM: Write a program to design a registration form using java swing.


Java Swing:
Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA
based Front End/GUI Applications. It is build on top of AWT API and acts as a replacement of
AWT API, since it has almost every control corresponding to AWT controls. Swing
component follows a Model-View-Controller architecture to fulfill the following criterias.
● A single API is to be sufficient to support multiple look and feel.

● API is to be model driven so that the highest level API is not required to have data.

● API is to use the Java Bean model so that Builder Tools and IDE can provide better
services to the developers for use.
MVC Architecture
Swing API architecture follows loosely based MVC architecture in the following manner.
● Model represents component's data.

● View represents visual representation of the component's data.

● Controller takes the input from the user on the view and reflects the changes in
Component's data.
● Swing component has Model as a seperate element, while the View and Controller part
are clubbed in the User Interface elements. Because of which, Swing has a pluggable
look-and-feel architecture.
Swing Features
● Light Weight − Swing components are independent of native Operating System's API
as Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls.
● Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, and table controls.
● Highly Customizable − Swing controls can be customized in a very easy way as visual
apperance is independent of internal representation.
● Pluggable look-and-feel − SWING based GUI Application look and feel can be
changed at run-time, based on available values.
Popular Java Editors
To write your Java programs, you will need a text editor. There are even more sophisticated
IDE available in the market. But for now, you can consider one of the following −
● Notepad − On Windows machine, you can use any simple text editor like Notepad,
TextPad.
● Netbeans − Netbeans is a Java IDE that is open source and free, which can be
downloaded from https://www.netbeans.org/index.html.
● Eclipse − Eclipse is also a Java IDE developed by the Eclipse open source community
and can be downloaded from https://www.eclipse.org

Every user interface considers the following three main aspects −

● UI Elements − These are the core visual elements the user eventually sees and interacts
with. GWT provides a huge list of widely used and common elements varying from
basic to complex, which we will cover in this tutorial.
● Layouts − They define how UI elements should be organized on the screen and provide
a final look and feel to the GUI (Graphical User Interface).
● Behavior − These are the events which occur when the user interacts with UI elements..

Every SWING controls inherits properties from the following Component class hiearchy.
S.No. Class & Description
Component
1 A Component is the abstract base class for the non menu user-interface controls of
SWING. Component represents an object with graphical representation
Container
2
A Container is a component that can contain other SWING components
JComponent
A JComponent is a base class for all SWING UI components. In order to use a
3
SWING component that inherits from JComponent, the component must be in a
containment hierarchy whose root is a top-level SWING container
SWING UI Elements
Following is the list of commonly used controls while designing GUI using SWING.
S.No. Class & Description
1 JLabel
A JLabel object is a component for placing text in a container.
JButton
2
This class creates a labeled button.
JColorChooser
3 A JColorChooser provides a pane of controls designed to allow a user to
manipulate and select a color.
JCheck Box
4 A JCheckBox is a graphical component that can be in either an on (true) or off
(false) state.
JRadioButton
5 The JRadioButton class is a graphical component that can be in either an on (true)
or off (false) state. in a group.
JList
6
A JList component presents the user with a scrolling list of text items.
JComboBox
7
A JComboBox component presents the user with a to show up menu of choices.
JTextField
8 A JTextField object is a text component that allows for the editing of a single line
of text.
JPasswordField
9
A JPasswordField object is a text component specialized for password entry.
JTextArea
10 A JTextArea object is a text component that allows editing of a multiple lines of
text.
ImageIcon
11 A ImageIcon control is an implementation of the Icon interface that paints Icons
from Images
JScrollbar
12 A Scrollbar control represents a scroll bar component in order to enable the user to
select from range of values.
JOptionPane
13 JOptionPane provides set of standard dialog boxes that prompt users for a value or
informs them of something.
JFileChooser
14 A JFileChooser control represents a dialog window from which the user can select
a file.
JProgressBar
15 As the task progresses towards completion, the progress bar displays the task's
percentage of completion.
JSlider
16 A JSlider lets the user graphically select a value by sliding a knob within a
bounded interval.
17 JSpinner
A JSpinner is a single line input field that lets the user select a number or an object
value from an ordered sequence.
What is an Event?
Change in the state of an object is known as Event, i.e., event describes the change in the state
of the source. Events are generated as a result of user interaction with the graphical user
interface components. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from the list, and scrolling the page are the
activities that causes an event to occur.
Types of Event
The events can be broadly classified into two categories −
● Foreground Events − These events require direct interaction of the user. They are
generated as consequences of a person interacting with the graphical components in the
Graphical User Interface. For example, clicking on a button, moving the mouse,
entering a character through keyboard, selecting an item from list, scrolling the page,
etc.
● Background Events − These events require the interaction of the end user. Operating
system interrupts, hardware or software failure, timer expiration, and operation
completion are some examples of background events.
What is Event Handling?
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has a code which is known as an event handler, that is executed
when an event occurs.
Java uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
The Delegation Event Model has the following key participants.
● Source − The source is an object on which the event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide us with classes
for the source object.
● Listener − It is also known as event handler. The listener is responsible for generating a
response to an event. From the point of view of Java implementation, the listener is also
an object. The listener waits till it receives an event. Once the event is received, the
listener processes the event and then returns.
The benefit of this approach is that the user interface logic is completely separated from the
logic that generates the event. The user interface element is able to delegate the processing of
an event to a separate piece of code.
In this model, the listener needs to be registered with the source object so that the listener can
receive the event notification. This is an efficient way of handling the event because the event
notifications are sent only to those listeners who want to receive them.
Steps Involved in Event Handling
Step 1 − The user clicks the button and the event is generated.
Step 2 − The object of concerned event class is created automatically and information about
the source and the event get populated within the same object.
Step 3 − Event object is forwarded to the method of the registered listener class.
Step 4 − The method is gets executed and returns.

Program:

// 1. Driver Code (Registration.java)


class Registration {
public static void main(String[] args) throws Exception
{
MyFrame f = new MyFrame();
} }

//2. MyFrame.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame
extends JFrame
implements ActionListener {
// Components of the Form
private Container c;
private JLabel title;
private JLabel name;
private JTextField tname;
private JLabel mno;
private JTextField tmno;
private JLabel gender;
private JRadioButton male;
private JRadioButton female;
private ButtonGroup gengp;
private JLabel dob;
private JComboBox date;
private JComboBox month;
private JComboBox year;
private JLabel add;
private JTextArea tadd;
private JCheckBox term;
private JButton sub;
private JButton reset;
private JTextArea tout;
private JLabel res;
private JTextArea resadd;
private String dates[]
= { "1", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"11", "12", "13", "14", "15",
"16", "17", "18", "19", "20",
"21", "22", "23", "24", "25",
"26", "27", "28", "29", "30",
"31" };
private String months[]
= { "Jan", "feb", "Mar", "Apr",
"May", "Jun", "July", "Aug",
"Sup", "Oct", "Nov", "Dec" };
private String years[]
= { "1995", "1996", "1997", "1998",
"1999", "2000", "2001", "2002",
"2003", "2004", "2005", "2006",
"2007", "2008", "2009", "2010",
"2011", "2012", "2013", "2014",
"2015", "2016", "2017", "2018",
"2019" };

// constructor, to initialize the components


// with default values.
public MyFrame()
{
setTitle("Registration Form");
setBounds(300, 90, 900, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);

c = getContentPane();
c.setLayout(null);

title = new JLabel("Registration Form");


title.setFont(new Font("Arial", Font.PLAIN, 30));
title.setSize(300, 30);
title.setLocation(300, 30);
c.add(title);

name = new JLabel("Name");


name.setFont(new Font("Arial", Font.PLAIN, 20));
name.setSize(100, 20);
name.setLocation(100, 100);
c.add(name);
tname = new JTextField();
tname.setFont(new Font("Arial", Font.PLAIN, 15));
tname.setSize(190, 20);
tname.setLocation(200, 100);
c.add(tname);

mno = new JLabel("Mobile");


mno.setFont(new Font("Arial", Font.PLAIN, 20));
mno.setSize(100, 20);
mno.setLocation(100, 150);
c.add(mno);

tmno = new JTextField();


tmno.setFont(new Font("Arial", Font.PLAIN, 15));
tmno.setSize(150, 20);
tmno.setLocation(200, 150);
c.add(tmno);
gender = new JLabel("Gender");
gender.setFont(new Font("Arial", Font.PLAIN, 20));
gender.setSize(100, 20);
gender.setLocation(100, 200);
c.add(gender);

male = new JRadioButton("Male");


male.setFont(new Font("Arial", Font.PLAIN, 15));
male.setSelected(true);
male.setSize(75, 20);
male.setLocation(200, 200);
c.add(male);

female = new JRadioButton("Female");


female.setFont(new Font("Arial", Font.PLAIN, 15));
female.setSelected(false);
female.setSize(80, 20);
female.setLocation(275, 200);
c.add(female);

gengp = new ButtonGroup();


gengp.add(male);
gengp.add(female);

dob = new JLabel("DOB");


dob.setFont(new Font("Arial", Font.PLAIN, 20));
dob.setSize(100, 20);
dob.setLocation(100, 250);
c.add(dob);

date = new JComboBox(dates);


date.setFont(new Font("Arial", Font.PLAIN, 15));
date.setSize(50, 20);
date.setLocation(200, 250);
c.add(date);

month = new JComboBox(months);


month.setFont(new Font("Arial", Font.PLAIN, 15));
month.setSize(60, 20);
month.setLocation(250, 250);
c.add(month);

year = new JComboBox(years);


year.setFont(new Font("Arial", Font.PLAIN, 15));
year.setSize(60, 20);
year.setLocation(320, 250);
c.add(year);

add = new JLabel("Address");


add.setFont(new Font("Arial", Font.PLAIN, 20));
add.setSize(100, 20);
add.setLocation(100, 300);
c.add(add);

tadd = new JTextArea();


tadd.setFont(new Font("Arial", Font.PLAIN, 15));
tadd.setSize(200, 75);
tadd.setLocation(200, 300);
tadd.setLineWrap(true);
c.add(tadd);

term = new JCheckBox("Accept Terms And Conditions.");


term.setFont(new Font("Arial", Font.PLAIN, 15));
term.setSize(250, 20);
term.setLocation(150, 400);
c.add(term);

sub = new JButton("Submit");


sub.setFont(new Font("Arial", Font.PLAIN, 15));
sub.setSize(100, 20);
sub.setLocation(150, 450);
sub.addActionListener(this);
c.add(sub);

reset = new JButton("Reset");


reset.setFont(new Font("Arial", Font.PLAIN, 15));
reset.setSize(100, 20);
reset.setLocation(270, 450);
reset.addActionListener(this);
c.add(reset);

tout = new JTextArea();


tout.setFont(new Font("Arial", Font.PLAIN, 15));
tout.setSize(300, 400);
tout.setLocation(500, 100);
tout.setLineWrap(true);
tout.setEditable(false);
c.add(tout);

res = new JLabel("");


res.setFont(new Font("Arial", Font.PLAIN, 20));
res.setSize(500, 25);
res.setLocation(100, 500);
c.add(res);

resadd = new JTextArea();


resadd.setFont(new Font("Arial", Font.PLAIN, 15));
resadd.setSize(200, 75);
resadd.setLocation(580, 175);
resadd.setLineWrap(true);
c.add(resadd);

setVisible(true);
}

// method actionPerformed()
// to get the action performed
// by the user and act accordingly
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == sub) {
if (term.isSelected()) {
String data1;
String data
= "Name : "
+ tname.getText() + "\n"
+ "Mobile : "
+ tmno.getText() + "\n";
if (male.isSelected())
data1 = "Gender : Male"
+ "\n";
else
data1 = "Gender : Female"
+ "\n";
String data2
= "DOB : "
+ (String)date.getSelectedItem()
+ "/" + (String)month.getSelectedItem()
+ "/" + (String)year.getSelectedItem()
+ "\n";

String data3 = "Address : " + tadd.getText();


tout.setText(data + data1 + data2 + data3);
tout.setEditable(false);
res.setText("Registration Successfully..");
}
else {
tout.setText("");
resadd.setText("");
res.setText("Please accept the"
+ " terms & conditions..");
}
}

else if (e.getSource() == reset) {


String def = "";
tname.setText(def);
tadd.setText(def);
tmno.setText(def);
res.setText(def);
tout.setText(def);
term.setSelected(false);
date.setSelectedIndex(0);
month.setSelectedIndex(0);
year.setSelectedIndex(0);
resadd.setText(def);
}
}
}

Output:
EXPERIMENT NO. 5

AIM: Write a program to implement event handling using swing to make a mini
calculator using java swing.

PROGRAM:
File: calculator.java

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;

// create a textfield
static JTextField l;

// store oprerator and operands


String s0, s1, s2;

// default constrcutor
calculator()
{
s0 = s1 = s2 = "";
}

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

try {
// set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}

// create a object of class


calculator c = new calculator();

// create a textfield
l = new JTextField(16);

// set the textfield to non editable


l.setEditable(false);

// create number buttons and some operators


JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");

// equals button
beq1 = new JButton("=");
// create operator buttons
ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");

// create . button
be = new JButton(".");

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

// add action listeners


bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);

// add elements to panel


p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);

// set Background of panel


p.setBackground(Color.blue);

// add panel to frame


f.add(p);

f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();

// if the value is a number


if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {

double te;
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
l.setText(s0 + s1 + s2 + "=" + te);
s0 = Double.toString(te);
s1 = s2 = ""; }
else {
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
double te;
// store the value in 1st
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
// convert it to string
s0 = Double.toString(te);
// place the operator
s1 = s;
// make the operand blank
s2 = "";
}
l.setText(s0 + s1 + s2);
}
}
}
Output:
EXPERIMENT NO. 6

AIM: Write a jdbc program to read records from a table in a specific database.
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.
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, 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.
Install Database
The most important thing you will need, of course is an actual running database with a table
that you can query and modify.
Install a database that is most suitable for you. You can have plenty of choices and most
common are −
● MySQL DB − MySQL is an open source database. You can download it from MySQL
Official Site. We recommend downloading the full Windows installation.
In addition, download and install MySQL Administrator as well as MySQL Query
Browser. These are GUI based tools that will make your development much easier.
Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a
convenient directory. For the purpose of this tutorial we will assume that you have
installed the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8.
Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\mysql-
connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar. Your driver version may
vary based on your installation.
Set Database Credential
When we install MySQL database, its administrator ID is set to root and it gives provision to
set a password of your choice.
Using root ID and password you can either create another user ID and password, or you can
use root ID and password for your JDBC application.
There are various database operations like database creation and deletion, which would need
administrator ID and password.
For rest of the JDBC tutorial, we would use MySQL Database with guest as ID and guest123
as password.
If you do not have sufficient privilege to create new users, then you can ask your Database
Administrator (DBA) to create a user ID and password for you.
Creating JDBC Application
There are following six steps involved in building a JDBC application −
● Import the packages − Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
● Open a connection − Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the database.
● Execute a query − Requires using an object of type Statement for building and
submitting an SQL statement to the database.
● Extract data from result set − Requires that you use the appropriate
ResultSet.getXXX() method to retrieve the data from the result set.
● Clean up the environment − Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
Program:
Import java.sql.*;
public class FirstExample
{
//GITS is a databse created in MYSQL DB
static final String DB_URL = "jdbc:mysql://localhost/GITS";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";

public static void main(String[] args) {


// Open a connection
try
{
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);

// Extract data from result set


while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
EXPERIMENT NO. 7

AIM: Write a jdbc program to read/write/update records from/to/in a table in a specific


database.
Program:
import java.sql.*;
public class SecondExample {
static String DB_URL = "jdbc:mysql://localhost/vishal";
static String USER = "root";
static String PASS = "root";
//static String QUERY = "SELECT id, name, age FROM staff";

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


// Open a connection
try
{
//Class.forName("com.mysql.cj.jdbc.Driver");//Registering the JDBC Driver
Driver myDriver = new com.mysql.cj.jdbc.Driver();
DriverManager.registerDriver( myDriver );//Registering the JDBC Driver

Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);


Statement stmt = conn.createStatement();
String QUERY="insert into staff values(1009,'anil',20,'Jodhpur')";
System.out.println("Inserting a record........");
stmt.executeUpdate(QUERY);
System.out.println("Record is successfully inserterd");
QUERY = "SELECT id, name, age, address FROM staff";

ResultSet rs = stmt.executeQuery(QUERY);
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", Address: " + rs.getString("address"));
System.out.print(", Name: " + rs.getString("name")+"\n");

}
QUERY = "UPDATE staff set name='xyz' where id=1004";
stmt.executeUpdate(QUERY);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
EXPERIMENT NO. 8

AIM: Create a JSP page to display Hello.


JSP:
Java Server Pages (JSP) is a server-side programming technology that enables the creation of
dynamic, platform-independent method for building Web-based applications. JSP have access
to the entire family of Java APIs, including the JDBC API to access enterprise databases.
JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database
or registering user preferences, accessing JavaBeans components, passing control between
pages, and sharing information between requests, pages etc.
Why to Learn JSP?
JavaServer Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.
● Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having separate CGI files.
● JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
● JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP,
etc.
● JSP pages can be used in combination with servlets that handle the business logic, the
model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the most
complex and demanding.
Applications of JSP
As mentioned before, JSP is one of the most widely used language over the web. I'm going to
list few of them here:
JSP vs. Active Server Pages (ASP)
The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic
or other MS specific language, so it is more powerful and easier to use. Second, it is portable
to other operating systems and non-Microsoft Web servers.
JSP vs. Pure Servlets
It is more convenient to write (and to modify!) regular HTML than to have plenty of println
statements that generate the HTML.
JSP vs. Server-Side Includes (SSI)
SSI is really only intended for simple inclusions, not for "real" programs that use form data,
make database connections, and the like.
JSP vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with the web
server to perform complex tasks like database access and image processing etc.
JSP vs. Static HTML
Regular HTML, of course, cannot contain dynamic information.
Setting up Web Server: Tomcat
A number of Web Servers that support JavaServer Pages and Servlets development are
available in the market. Some web servers can be downloaded for free and Tomcat is one of
them.
Apache Tomcat is an open source software implementation of the JavaServer Pages and
Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can be
integrated with the Apache Web Server. Here are the steps to set up Tomcat on your machine

● Download the latest version of Tomcat from https://tomcat.apache.org/.

● Once you downloaded the installation, unpack the binary distribution into a convenient
location. For example, in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-
tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable
pointing to these locations.
Tomcat can be started by executing the following commands on the Windows machine −
%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-5.5.29\bin\startup.bat
Tomcat can be started by executing the following commands on the Unix (Solaris, Linux, etc.)
machine −
$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After a successful startup, the default web-applications included with Tomcat will be available
by visiting http://localhost:8080/.
Upon execution, you will receive the following output −

Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet
classes to the compiler.
If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.
set CATALINA = C:\apache-tomcat-5.5.29
set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%

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 - Lifecycle
The key to understanding the low-level functionality of JSP is to understand the simple life
cycle they follow.
A JSP life cycle is defined as the process from its creation till the destruction. This is similar to
a servlet life cycle with an additional step which is required to compile a JSP into servlet.
Paths Followed By JSP
The following are the paths followed by a JSP −

● Compilation
● Initialization
● Execution
● Cleanup

The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four
phases have been described below −
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile
the page. If the page has never been compiled, or if the JSP has been modified since it was last
compiled, the JSP engine compiles the page.
The compilation process involves three steps −

● Parsing the JSP.


● Turning the JSP into a servlet.
● Compiling the servlet.

Elements of JSP
The elements of JSP have been described below −
The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or method
declarations, or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet −
<% code fragment %>
You can write the XML equivalent of the above syntax as follows −
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is
the simple and first example for JSP −
<html>
<head><title>Hello World</title></head>

<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

Program:
<html>
<head>
<title>First JSP Page </title>
</head>
<body bgcolor="pink">
<marquee scrollamount="60">Hello GITS</marquee>
<font color="green">
<center><h1>
<%
out.println("Hello Third Year CSE Students.");
%>
</h1></center>
</font>
</body>
</html>
EXPERIMENT NO. 9

AIM: Create a JSP page which receives two integers from a HTML page and calculates
the sum of them.

Program:
File: addform.html

<html>
<head>
<title>Form for Addition
</title>
<body bgcolor="green">
<h1><center>Form for Arithmetic Addition</center></h1><br><br>
<form action="sum.jsp">
<table border="2" align="center">
<tr>
<td>Enter First Number:</td>
<td><input type="text" name="fnum"></td>
</tr>
<tr>
<td>Enter Second Number:</td>
<td><input type="text" name="snum"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</head>
</html>

File: sum.jsp:

<html>
<body bgcolor="pink">
<h3><center>This JSP page calculates the sum of two integers received from a HTML
page</center></h3>
<%
String str1=request.getParameter("fnum");
String str2=request.getParameter("snum");
int n1=Integer.parseInt(str1);
int n2=Integer.parseInt(str2);
int sum=n1+n2;
%>
<h3><center>
<% out.println("Sum="+sum); %>
</center></h3>
</body>
</html>
EXPERIMENT NO. 10

AIM: Design a JSP page to calculate the area of a circle, square and rectangle.

PROGRAM:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<%@ taglib tagdir="/WEB-INF/tags" prefix="rec" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Invoke tag file to calculate the area of rectangle and circle</title>
</head>
<body>
<rec:Rect sideA="2" sideB="3"/>
<rec:Circle radius="3" />
</body>
</html>
<%@ tag pageEncoding="utf-8" %>
<h4>Calculate the area of the rectangle</h4>
<%@ attribute name="sideA" required="true"%>
<%@ attribute name="sideB" required="true"%>
<%! public String getArea(double a, double b)
{
if(a>0&&b>0){
double area = a*b;
return "<br>Rectangular area: "+ area;
}
else{
return("<br>"+a+", "+b+" cannot form a rectangle");
}
}
%>
<%
Out.print("<br>The two rectangles are: "+sideA+", "+sideB);
double a = Double.parseDouble(sideA);
double b = Double.parseDouble(sideB);
out.println(getArea(a,b));
%>
<%@ tag pageEncoding="utf-8" %>
<h4>Calculate the circular area</h4>
<%@ attribute name="radius" required="true"%>
<%! public String getArea(double r)
{
if(r>0){
double area = Math.PI*r*r;
Return "<br>Circular area: "+ area;
}else{
return "<br>wrong";
}
}
%>
<%
out.print("<br>The radius of the circle is: "+radius);
double r = Double.parseDouble(radius);
out.println(getArea(r));
%>
EXPERIMENT NO. 11

AIM: Write a program to design a JSP page for currency converter.

PROGRAM:

<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

<title>fizaboun/3w lesson</title>
<meta name="description" content="fizaboun/ZaaBI_AlonSo">
<link rel="stylesheet" href="lib/c/styles.css">
<meta property="og:site_name" content="fizaboun/3w lesson"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){$('#swap').click(function(){s1=$
('#to').val();s0=$('#from').val();$('#to').val(s0);$('#from').val(s1); });
});
</script>
</head>
<body>

<%@ page import="java.util.*" %>

<div class="background"></div>

<div id="heading">

<%
String currency = (String)request.getAttribute("currency");
String value = (String)request.getAttribute("value");
String from = (String)request.getAttribute("from");
String to = (String)request.getAttribute("to");

if( currency == null )


{
out.print("Fizaboun live currency converter");
}else{
out.println(""+value);
out.println(""+from);
out.println("equals to "+currency);
out.println(""+to);

%>
</div>

<div id="currencyBox">
<form method="POST" action="CurrencyConverter.do">
<div class="data">
<label for="from">Convert:</label>
<input type="text" name="amount" id="amount" value="1" />
</div>
<div class="data">
<label for="fromCurrency">From Currency:</label>
<select name="from" id="from">
<option selected="" value="EUR">Euro - EUR</option>
<option value="USD">United States Dollars - USD</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="JPY">Japan Yen - JPY</option>
<option value="INR">India Rupees - INR</option>
<option value="NZD">New Zealand Dollars - NZD</option>
<option value="CHF">Switzerland Francs - CHF</option>
<option value="ZAR">South Africa Rand - ZAR</option>
<option value="DZD">Algeria Dinars - DZD</option>
<option value="USD">America (United States) Dollars - USD</option>
<option value="ARS">Argentina Pesos - ARS</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="BHD">Bahrain Dinars - BHD</option>
<option value="BRL">Brazil Reais - BRL</option>
<option value="BGN">Bulgaria Leva - BGN</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="CLP">Chile Pesos - CLP</option>
<option value="CNY">China Yuan Renminbi - CNY</option>
<option value="CNY">RMB (China Yuan Renminbi) - CNY</option>
<option value="COP">Colombia Pesos - COP</option>
<option value="CRC">Costa Rica Colones - CRC</option>
<option value="HRK">Croatia Kuna - HRK</option>
<option value="CZK">Czech Republic Koruny - CZK</option>
<option value="DKK">Denmark Kroner - DKK</option>
<option value="DOP">Dominican Republic Pesos - DOP</option>
<option value="EGP">Egypt Pounds - EGP</option>
<option value="EEK">Estonia Krooni - EEK</option>
<option value="EUR">Euro - EUR</option>
<option value="FJD">Fiji Dollars - FJD</option>
<option value="HKD">Hong Kong Dollars - HKD</option>
<option value="HUF">Hungary Forint - HUF</option>
<option value="ISK">Iceland Kronur - ISK</option>
<option value="INR">India Rupees - INR</option>
<option value="IDR">Indonesia Rupiahs - IDR</option>
<option value="ILS">Israel New Shekels - ILS</option>
<option value="JMD">Jamaica Dollars - JMD</option>
<option value="JPY">Japan Yen - JPY</option>
<option value="JOD">Jordan Dinars - JOD</option>
<option value="KES">Kenya Shillings - KES</option>
<option value="KRW">Korea (South) Won - KRW</option>
<option value="KWD">Kuwait Dinars - KWD</option>
<option value="LBP">Lebanon Pounds - LBP</option>
<option value="MYR">Malaysia Ringgits - MYR</option>
<option value="MUR">Mauritius Rupees - MUR</option>
<option value="MXN">Mexico Pesos - MXN</option>
<option value="MAD">Morocco Dirhams - MAD</option>
<option value="NZD">New Zealand Dollars - NZD</option>
<option value="NOK">Norway Kroner - NOK</option>
<option value="OMR">Oman Rials - OMR</option>
<option value="PKR">Pakistan Rupees - PKR</option>
<option value="PEN">Peru Nuevos Soles - PEN</option>
<option value="PHP">Philippines Pesos - PHP</option>
<option value="PLN">Poland Zlotych - PLN</option>
<option value="QAR">Qatar Riyals - QAR</option>
<option value="RON">Romania New Lei - RON</option>
<option value="RUB">Russia Rubles - RUB</option>
<option value="SAR">Saudi Arabia Riyals - SAR</option>
<option value="SGD">Singapore Dollars - SGD</option>
<option value="SKK">Slovakia Koruny - SKK</option>
<option value="ZAR">South Africa Rand - ZAR</option>
<option value="KRW">South Korea Won - KRW</option>
<option value="LKR">Sri Lanka Rupees - LKR</option>
<option value="SEK">Sweden Kronor - SEK</option>
<option value="CHF">Switzerland Francs - CHF</option>
<option value="TWD">Taiwan New Dollars - TWD</option>
<option value="THB">Thailand Baht - THB</option>
<option value="TTD">Trinidad and Tobago Dollars - TTD</option>
<option value="TND">Tunisia Dinars - TND</option>
<option value="TRY">Turkey Lira - TRY</option>
<option value="AED">United Arab Emirates Dirhams - AED</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="USD">United States Dollars - USD</option>
<option value="VEB">Venezuela Bolivares - VEB</option>
<option value="VND">Vietnam Dong - VND</option>
<option value="ZMK">Zambia Kwacha - ZMK</option>
</select>
</div>

<div class="data">
<label for="to">To Currency:</label>
<select name="to" id="to">
<option value="USD">United States Dollars - USD</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="JPY">Japan Yen - JPY</option>
<option value="INR">India Rupees - INR</option>
<option value="NZD">New Zealand Dollars - NZD</option>
<option value="CHF">Switzerland Francs - CHF</option>
<option value="ZAR">South Africa Rand - ZAR</option>
<option value="DZD">Algeria Dinars - DZD</option>
<option value="USD">America (United States) Dollars - USD</option>
<option value="ARS">Argentina Pesos - ARS</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="BHD">Bahrain Dinars - BHD</option>
<option value="BRL">Brazil Reais - BRL</option>
<option value="BGN">Bulgaria Leva - BGN</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="CLP">Chile Pesos - CLP</option>
<option value="CNY">China Yuan Renminbi - CNY</option>
<option value="CNY">RMB (China Yuan Renminbi) - CNY</option>
<option value="COP">Colombia Pesos - COP</option>
<option value="CRC">Costa Rica Colones - CRC</option>
<option value="HRK">Croatia Kuna - HRK</option>
<option value="CZK">Czech Republic Koruny - CZK</option>
<option value="DKK">Denmark Kroner - DKK</option>
<option value="DOP">Dominican Republic Pesos - DOP</option>
<option value="EGP">Egypt Pounds - EGP</option>
<option value="EEK">Estonia Krooni - EEK</option>
<option value="EUR">Euro - EUR</option>
<option value="FJD">Fiji Dollars - FJD</option>
<option value="HKD">Hong Kong Dollars - HKD</option>
<option value="HUF">Hungary Forint - HUF</option>
<option value="ISK">Iceland Kronur - ISK</option>
<option value="INR">India Rupees - INR</option>
<option value="IDR">Indonesia Rupiahs - IDR</option>
<option value="ILS">Israel New Shekels - ILS</option>
<option value="JMD">Jamaica Dollars - JMD</option>
<option value="JPY">Japan Yen - JPY</option>
<option value="JOD">Jordan Dinars - JOD</option>
<option value="KES">Kenya Shillings - KES</option>
<option value="KRW">Korea (South) Won - KRW</option>
<option value="KWD">Kuwait Dinars - KWD</option>
<option value="LBP">Lebanon Pounds - LBP</option>
<option value="MYR">Malaysia Ringgits - MYR</option>
<option value="MUR">Mauritius Rupees - MUR</option>
<option value="MXN">Mexico Pesos - MXN</option>
<option value="MAD">Morocco Dirhams - MAD</option>
<option value="NZD">New Zealand Dollars - NZD</option>
<option value="NOK">Norway Kroner - NOK</option>
<option value="OMR">Oman Rials - OMR</option>
<option value="PKR">Pakistan Rupees - PKR</option>
<option value="PEN">Peru Nuevos Soles - PEN</option>
<option value="PHP">Philippines Pesos - PHP</option>
<option value="PLN">Poland Zlotych - PLN</option>
<option value="QAR">Qatar Riyals - QAR</option>
<option value="RON">Romania New Lei - RON</option>
<option value="RUB">Russia Rubles - RUB</option>
<option value="SAR">Saudi Arabia Riyals - SAR</option>
<option value="SGD">Singapore Dollars - SGD</option>
<option value="SKK">Slovakia Koruny - SKK</option>
<option value="ZAR">South Africa Rand - ZAR</option>
<option value="KRW">South Korea Won - KRW</option>
<option value="LKR">Sri Lanka Rupees - LKR</option>
<option value="SEK">Sweden Kronor - SEK</option>
<option value="CHF">Switzerland Francs - CHF</option>
<option value="TWD">Taiwan New Dollars - TWD</option>
<option value="THB">Thailand Baht - THB</option>
<option value="TTD">Trinidad and Tobago Dollars - TTD</option>
<option value="TND">Tunisia Dinars - TND</option>
<option value="TRY">Turkey Lira - TRY</option>
<option value="AED">United Arab Emirates Dirhams - AED</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="USD">United States Dollars - USD</option>
<option value="VEB">Venezuela Bolivares - VEB</option>
<option value="VND">Vietnam Dong - VND</option>
<option value="ZMK">Zambia Kwacha - ZMK</option>
</select>
</div>
<div class="data">
<input type="submit" name="submit" id="submit" value="Convert the input">

<input type="button" name="swap" id="swap" value="Swap values">


</div>
</form>
<form method="GET" action="CodeGrabber.zip"><input type="submit" value="Grab
the code!"></form>
<form method="GET" action="ReportGrabber.do"><input type="submit" value="On
line report!"></form>

</div>
</body>
</html>

Output:
EXPERIMENT NO. 12

AIM: Write a program to design a servlet that takes all the input from webpage and
display the same through servlet.

Servlet:
Top of Form
Bottom of Form
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.
Why to Learn Servlet?
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.
● 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.
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.
● 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.
Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.

Servlets Tasks
Servlets perform the following major tasks −
● 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 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.
Setting up Web Server − Tomcat
A number of Web Servers that support servlets are available in the market. Some web servers
are freely downloadable and Tomcat is one of them.
Apache Tomcat is an open source software implementation of the Java Servlet and Java Server
Pages technologies and can act as a standalone server for testing servlets and can be integrated
with the Apache Web Server. Here are the steps to setup Tomcat on your machine −
● Download latest version of Tomcat from https://tomcat.apache.org/.

● Once you downloaded the installation, unpack the binary distribution into a convenient
location. For example in C:\apache-tomcat-8.0.28 on windows, or /usr/local/apache-
tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME environment variable
pointing to these locations.
Tomcat can be started by executing the following commands on windows machine −
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-8.0.28\bin\startup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.)
machine −
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-8.0.28/bin/startup.sh
After startup, the default web applications included with Tomcat will be available by visiting
http://localhost:8080/. If everything is fine then it should display following result −
Setting Up the CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet
classes to the compiler.
If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.
set CATALINA = C:\apache-tomcat-8.0.28
set CLASSPATH = %CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%
Alternatively, on Windows NT/2000/XP, you could go to My Computer −> Properties −>
Advanced −> Environment Variables. Then, you would update the CLASSPATH value and
press the OK button.
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines
into your .cshrc file.
setenv CATALINA = /usr/local/apache-tomcat-8.0.28
setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH
NOTE − Assuming that your development directory is C:\ServletDevel (Windows) or
/usr/ServletDevel (Unix) then you would need to add these directories as well in
CLASSPATH in similar way as you have added above.
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...
}
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.
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.
PROGRAM:
<html>
<head>
<title>File Uploading Form</title>
</head>

<body>
<h3>File Upload:</h3>
Select a file to upload: <br/>
<formaction="UploadServlet"method="post"enctype="multipart/form-data">
<inputtype="file"name="file"size="50"/>
<br/>
<inputtype="submit"value="Upload File"/>
</form>
</body>
</html>

// Import required java libraries


import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

publicclassUploadServletextendsHttpServlet{

privateboolean isMultipart;
privateString filePath;
privateint maxFileSize =50*1024;
privateint maxMemSize =4*1024;
privateFile file ;

publicvoid init(){
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}

publicvoid doPost(HttpServletRequest request,HttpServletResponse response)


throwsServletException, java.io.IOException{

// Check that we have a file upload request


isMultipart =ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriterout= response.getWriter();

if(!isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}

DiskFileItemFactory factory =newDiskFileItemFactory();

// maximum size that will be stored in memory


factory.setSizeThreshold(maxMemSize);

// Location to save data that is larger than maxMemSize.


factory.setRepository(newFile("c:\\temp"));

// Create a new file upload handler


ServletFileUpload upload =newServletFileUpload(factory);

// maximum file size to be uploaded.


upload.setSizeMax( maxFileSize );

try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);

// Process the uploaded file items


Iterator i = fileItems.iterator();

out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while( i.hasNext ()){
FileItemfi=(FileItem)i.next();
if(!fi.isFormField ()){
String fieldName =fi.getFieldName();
String fileName =fi.getName();
String contentType =fi.getContentType();
boolean isInMemory =fi.isInMemory();
long sizeInBytes =fi.getSize();
if( fileName.lastIndexOf("\\")>=0){
file =newFile( filePath + fileName.substring( fileName.lastIndexOf("\\")));
}else{
file =newFile( filePath + fileName.substring(fileName.lastIndexOf("\\")+1))}
fi.write( file );
out.println("Uploaded Filename: "+ fileName +"<br>");}}
out.println("</body>");
out.println("</html>");
}catch(Exception ex){
System.out.println(ex);
}
}
publicvoid doGet(HttpServletRequest request,HttpServletResponse response)
throwsServletException, java.io.IOException{
thrownewServletException("GET method used with "+
getClass().getName()+": POST method required.");
}
}
}

Output:
EXPERIMENT NO. 13

AIM: Write a program to design a servlet that add two numbers received from the web
pages and display the same.

PROGRAM:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form="add/addpackage">
Name:<input type="text" name="name" value="" />
Num1:<input type="text" name="num1" value="" />
Num2:<input type="text" name="num2" value="" />
<br>
<input type="submit" value="button" />
</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

WebServlet(name = "HelloServelet", urlPatterns = {"/HelloServelet"})


public class HelloServelet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

String name = request.getParameter("name");


int a = request.getParameter("num1");
int b = request.getParameter("num2");
int sum = 0;
int x,y;

x = Integer.parseInt(a);
y = Integer.parseInt(b);
sum = x + y;

out.println("Hi!" + name + "The sum is" + sum);


out.close();
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign


on the left to edit the code.">

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
processRequest(request, response);
}

public String getServletInfo() {


return "Short description";
}// </editor-fold>
}
Java Socket Programming
Java Socket programming is used for communication between the applications running on
different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.

Here, we are going to make one-way client and server communication. In this application,
client sends a message to the server, server reads the message and prints it. Here, two classes
are being used: Socket and ServerSocket. The Socket class is used to communicate client and
server. Through this class, we can read and write message. The ServerSocket class is used at
server-side. The accept() method of ServerSocket class blocks the console until the client is
connected. After the successful connection of client, it returns the instance of Socket at server-
side.

Socket class:
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.
Important methods
Method Description

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

ServerSocket class:
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method Description

1) public Socket accept() returns the socket and establish a connection between server
and client.

2) public synchronized void closes the server socket.


close()
Example of Java Socket Programming
Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we
are using 6666 port number for the communication between the client and server. You may
also choose any other port number. The accept() method waits for the client. If clients
connects with the given port number, it returns an instance of Socket.
1. ServerSocket ss=new ServerSocket(6666);
2. Socket s=ss.accept();//establishes connection and waits for the client

Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need
to pass the IP address or hostname of the Server and a port number. Here, we are using
"localhost" because our server is running on same system.
Socket s=new Socket("localhost",6666);
Let's see a simple of Java socket programming where client sends a text and server receives
and prints it.
EXPERIMENT NO. 14

AIM: Write a Java program to create a connection oriented sender-receiver application


using TCP.

PROGRAM:
File: MyServer.java

import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}

File: MyClient.java
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}
}

Output:
Java DatagramSocket and
DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming using the UDP instead of TCP.
Datagram:
Datagrams are collection of information sent from one device to another device via the
established network. When the datagram is sent to the targeted device, there is no assurance
that it will reach to the target device safely and completely. It may get damaged or lost in
between. Likewise, the receiving device also never know if the datagram received is damaged
or not. The UDP protocol is used to implement the datagrams in Java.
Java DatagramSocket class:
Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets. It is a mechanism used for transmitting datagram packets over network.`
A datagram is basically an information but there is no guarantee of its content, arrival or
arrival time.
Commonly used Constructors of DatagramSocket class:
o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it
with the available Port Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and
binds it with the given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address.

Java DatagramSocket Class:

Method Description

void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.

void close() It closes the datagram socket.

void connect(InetAddress It connects the socket to a remote address for the socket.
address, int port)

void disconnect() It disconnects the socket.

boolean getBroadcast() It tests if SO_BROADCAST is enabled.

DatagramChannel It returns the unique DatagramChannel object associated with


getChannel() the datagram socket.

InetAddress getInetAddress() It returns the address to where the socket is connected.

InetAddress getLocalAddress() It gets the local address to which the socket is connected.

int getLocalPort() It returns the port number on the local host to which the socket
is bound.

SocketAddress It returns the address of the endpoint the socket is bound to.
getLocalSocketAddress()

int getPort() It returns the port number to which the socket is connected.

int getReceiverBufferSize() It gets the value of the SO_RCVBUF option for this
DatagramSocket that is the buffer size used by the platform for
input on the DatagramSocket.

boolean isClosed() It returns the status of socket i.e. closed or not.

boolean isConnected() It returns the connection state of the socket.

void send(DatagramPacket p) It sends the datagram packet from the socket.

void receive(DatagramPacket It receives the datagram packet from the socket.


p)

Java DatagramPacket Class:


Java DatagramPacket is a message that can be sent or received. It is a data container. If you
send multiple packet, it may arrive in any order. Additionally, packet delivery is not
guaranteed.
Commonly used Constructors of DatagramPacket class:
o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This
constructor is used to receive the packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a
datagram packet. This constructor is used to send the packets.

Java DatagramPacket Class Methods:


Method Description

1) InetAddress getAddress() It returns the IP address of the machine to which the


datagram is being sent or from which the datagram was
received.

2) byte[] getData() It returns the data buffer.

3) int getLength() It returns the length of the data to be sent or the length
of the data received.

4) int getOffset() It returns the offset of the data to be sent or the offset
of the data received.

5) int getPort() It returns the port number on the remote host to which
the datagram is being sent or from which the datagram
was received.

6) SocketAddress getSocketAddress() It gets the SocketAddress (IP address + port number)


of the remote host that the packet is being sent to or is
coming from.

7) void setAddress(InetAddress iaddr) It sets the IP address of the machine to which the
datagram is being sent.

8) void setData(byte[] buff) It sets the data buffer for the packet.

9) void setLength(int length) It sets the length of the packet.

10) void setPort(int iport) It sets the port number on the remote host to which the
datagram is being sent.

11) void It sets the SocketAddress (IP address + port number) of


setSocketAddress(SocketAddress the remote host to which the datagram is being sent.
addr)
EXPERIMENT NO. 15

AIM: Write a Java program to create a connectionless sender-receiver application using


UDP.

PROGRAM:
File: DSender.java

import java.net.*;
public class Dsender
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}
File: DReceiver.java

import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}

Output:
RUBRICS EVALUATION

Performance Scale 1 Scale 2 Scale 3 Scale 4 Score


Criteria (0-25%) (26-50%) (51-75%) (76- (Numerical)
100%)

Understandability Unable to Able to Able to Able to


understand understand understand understand the
Ability to analyse the the problem the problem
Problem and problem. partially and problem completely
Identify solution unable to completely and able to
identify the but unable to provide
solution identify the alternative
solution solution too.
Logic Program Program logic is Program logic Program logic
logic is on the right track is mostly is correct,
Ability to specify incorrect but has several correct, but with no
Conditions & control errors may contain known
flow that are an occasional boundary
appropriate for the boundary errors, and no
error or redundant or
problem domain.
redundant or contradictory
contradictory conditions.
condition.
Debugging Unable to Unable to debug Able to Able to
Ability to execute /debug execute several errors. execute execute
program program with program
several completely
warnings.
Correctness Program Program Program Program
Ability to code formulae does not approaches produces produces
and algorithms that produce correct answers correct correct answers
reliably produce correct correct or appropriate answers or or appropriate
answers or appropriate answers or results for most appropriate results for all
results. appropriate inputs, but can results for inputs tested.
results for contain most inputs.
most inputs. miscalculations
in some cases.
Completeness Unable to Unable to Able to Able to explain
Ability to demonstrate explain the explain the code explain code code and the
and deliver on time. code.and the and the code and the program was
code was submission was program was delivered on
overdue. late. delivered time.
within
the due date.
TOTAL

You might also like