Sec-A Adv. Java Lab File-2024-2025
Sec-A Adv. Java Lab File-2024-2025
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 :
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( )
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. 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 :
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
● 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.
● 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
● 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:
//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" };
c = getContentPane();
c.setLayout(null);
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";
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;
// 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 textfield
l = new JTextField(16);
// 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();
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
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.
● Java Applets
● Java Servlets
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
● 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 −
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:
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>
<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");
%>
</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">
</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 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 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");
}
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;
}
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
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;
x = Integer.parseInt(a);
y = Integer.parseInt(b);
sum = x + y;
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.
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.
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
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.
Method Description
void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.
void connect(InetAddress It connects the socket to a remote address for the socket.
address, int port)
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.
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.
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.
10) void setPort(int iport) It sets the port number on the remote host to which the
datagram is being sent.
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");
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