0% found this document useful (0 votes)
26 views66 pages

AJP Lab Manual (1) - 1

The document outlines a series of experiments for an Advanced Java Programming class, covering topics such as Applet key events, AWT mouse events, GUI applications, JDBC database connections, and RMI applications. Each experiment includes objectives, theoretical background, and practical coding examples to help students understand and implement various Java programming concepts. The document serves as a comprehensive guide for students to develop their skills in Java programming through hands-on practice.

Uploaded by

viheb17939
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views66 pages

AJP Lab Manual (1) - 1

The document outlines a series of experiments for an Advanced Java Programming class, covering topics such as Applet key events, AWT mouse events, GUI applications, JDBC database connections, and RMI applications. Each experiment includes objectives, theoretical background, and practical coding examples to help students understand and implement various Java programming concepts. The document serves as a comprehensive guide for students to develop their skills in Java programming through hands-on practice.

Uploaded by

viheb17939
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 66

List of Experiments

Class:T.E. Sub.: Advanced Java Programming

Gro Sr. Experiment


up
No.
1 Write a program to demonstrate status of key on an Applet window such as
KeyPressed,KeyReleased, KeyUp, KeyDown.
2 Write a program to create a frame using AWT. Implement mouseClicked,
mouseEntered() and mouseExited() events. Frame should become visible when
the mouse enters it.
A
3 Develop a GUI which accepts the information regarding the marks for all the
subjects of a student in the examination. Display the result for a student in a
separate window.
Write a program to insert and retrieve the data from the database using
4
JDBC.
Develop an RMI application which accepts a string or a number and checks that
5 string or number is palindrome or not.
Write a program to demonstrate the use of Inet Address class and its factory
6
methods.
Write program with suitable example to develop your remote interface,
7
implement your RMI server, implement application that create your server, also
B develop security policy file.
Write a database application that uses any JDBC driver.
8
Write a simple JSP page to display a simple message (It may be a simple html
9
page).
C Create a simple calculator application using servlet.
10
Experiment No. 1
Applet

Title:To perform key events on applet window.

Aim:Write a program to demonstrate status of key on an Applet window such as


KeyPressed,KeyReleased, KeyUp, KeyDown.

Theory:

Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.

Advantage of Applet -

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including
Linux, Windows, MacOs etc.

Drawback of Applet -
o Plugin is required at client browser to execute applet.
Hierarchy of Applet –

Lifecycle of Java Applet -


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized.
It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop
or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides


Graphics class object that can be used for drawing oval, rectangle, arc etc.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Java KeyListener Interface -

The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package, and
it has three methods.

Interface declaration -
Following is the declaration for java.awt.event.KeyListener interface:

public interface KeyListener extends EventListener

Methods of KeyListener interface

The signature of 3 methods found in KeyListener interface are given below:


ELO : Student will able to implement various key events on applet window.

Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 2
AWT

Title:AWT window and mouse events.


Aim:Write a program to create a frame using AWT. Implement mouseClicked,
mouseEntered() andmouseExited() events. Frame should become visible when the
mouse enters it.

Theory:

AWT stands for Abstract window toolkit is an Application programming interface


(API) for creating Graphical User Interface (GUI) in Java. It allows Java programmers
to develop window-based applications.

AWT provides various components like button, label, checkbox, etc. used as objects
inside a Java Program. AWT components use the resources of the operating system,
i.e., they are platform-dependent, which means, component's view can be changed
according to the view of the operating system. The classes for AWT are provided by
the Java.awt package for various AWT components.
Java MouseListener Interface -

The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent. The MouseListener interface is found in java.awt.event
package. It has five methods.

Methods of MouseListener interface -

The signature of 5 methods found in MouseListener interface are given below:

public abstract void mouseClicked(MouseEvent e);


public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);

ELO :Student will be able to implement various mouse events on frame using AWT.

Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 3
GUI
Title:Develop GUI application.

Aim:Develop a GUI which accepts the information regarding the marks for all the
subjects of a student in the examination. Display the result for a student in a separate
window.

Theory:

GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for
Java applications. It is mainly made of graphical components like buttons, labels,
windows, etc. through which the user can interact with an application. GUI plays an
important role to build easy interfaces for Java applications.

How to Make a GUI in Java with Example –


Step 1) Type following code
importjavax.swing.*;
classgui{
public static void main(String args[])
{ JFrame frame = new JFrame("My First
GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of frame
frame.setVisible(true);
}
}
Step 2) Run the code
Next step, Save, Compile, and Run the code

Step 3) Type following code.


Now let’s Add a Button to our frame.
importjavax.swing.*;
classgui{
public static void main(String args[])
{ JFrame frame = new JFrame("My First
GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);
}
}

Step 4) Execute the code


Next, Execute the code. You will get a big button.

Step 5) Add two buttons


How about adding two buttons? Type the following code into an editor.
importjavax.swing.*;
classgui{
public static void main(String args[])
{ JFrame frame = new JFrame("My First
GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setVisible(true);
}
}
Step 6) Save & Run the program
Next, Save, Compile, and Run the program.

Step 7) Check output


Unexpected output =? Buttons are getting overlapped.

Java Layout Manager -


The Layout manager is used to layout (or arrange) the GUI Java components inside a
container. There are many layout managers, but the most frequently used are –

Java BorderLayout -
A BorderLayout places components in up to five areas: top, bottom, left, right, and
center. It is the default layout manager for every java JFrame

Java FlowLayout -
FlowLayout is the default layout manager for every JPanel. It simply lays out
components in a single row one after the other.
Java GridBagLayout
It is the more sophisticated of all layouts. It aligns components by placing them within
a grid of cells, allowing components to span more than one cell.

Step 8) Create chat frame


How about creating a chat frame like below?
//Usually you will require both swing and awt packages
// even if you are working with just swings.
importjavax.swing.*;
importjava.awt.*;
classgui {
public static void main(String args[]) {

//Creating the Frame


JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

//Creating the MenuBar and adding components


JMenuBarmb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
m1.add(m11);
m1.add(m22);

//Creating the panel at bottom and adding components


JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextFieldtf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label); // Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);

// Text Area at the Center


JTextArea ta = new JTextArea();

//Adding Components to the frame.


frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, mb);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
}
}

In this experiment, we are developing GUI application by using above concepts to


create student information as given in aim.
ELO :Student will be able to develop GUI application to accept student marks
information and display the same.

Conclusion:

--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 4
JDBC

Title:Making JDBC connection.

Aim: Write a program to insert and retrieve the data from the database using JDBC.

Theory:
To establish a connection with MySQL in JDBC, first we have to install MySQL on
our system and we have to add the MySQL connector (it is a .jar file containing the
classes that are the implementation of interfaces provided by Sun Microsystems ) to
our class path variable. After doing this the classes implementing the interfaces
provided by Sun Microsystem are available to our program.

How to add MySql connector to our class path variable: There are two approaches for
adding the MySQL connector to our class path variable. Both are given below.

Adding MySQL connector temporarily -


In this approach, we simply set the classpath variable = path to where our MySQL
connector is stored on our system at the command prompt or console window. This
approach is applicable until we close our console. After closing the console window,
the classpath variable removes the path of MySQL connector.

syntax : c:\> set classpath=path of connector;

For example, the given image is helpful for understanding the syntax
Adding MySQL connector permanently –
Go to My Computer and after right clicking, select the Properties option and click
on that.
System Properties window will open, select Advanced option and the following
window will open.
Select Environment Variable option and the following window will open.
Select the class path variable (left click) and click on Edit button and the following
window will open.
In the System Variable window, go to the end of Variable value option and place a
semicolon, after that add the path of connector followed by semicolon and click on the
ok button.

Creating database in MySQL and granting it all privileges: To perform this we follow
the following steps

 Open MySQL and enter the password after this my mysql> prompt will open
 Create a database with the following command

 Granting a user name, password and all privileges with the following command

Now our MySQL database is ready for creating a connection with JDBC.
1. import java.sql.*;
2. public class MySQLdatabase {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con =
DriverManager.getConnection("jd
bc:mysql://localhost/sqldatabase", "amit", "amitabh");
7. Statement s = con.createStatement();
8. s.execute("create table student ( stud_id
intege r,stud_name varchar(20),stud_address
varchar(30) )"); // cre
ate a table
9. s.execute("insert into student
values(001,'ARman
','Delhi')"); // insert first row into the table
10. s.execute("insert into student
values(002,' Robert','Canada')"); // insert second row
into the table
11. s.execute("insert into student
values(003,'
Ahuja','Karnal')"); // insert third row into the table
12. ResultSet rs = s.executeQuery("select *
fro m student");
13. if (rs != null) // if rs == null, then
ther
e is no record in ResultSet to show
14. while (rs.next()) // By this line
we wi ll step through our data row-by-row
15. {
16. System.out.println("
");
17. System.out.println("Id of the
student:
" + rs.getString(1));
18. System.out.println("Name of student:
"
+ rs.getString(2));
19. System.out.println("Address of
student:
" + rs.getString(3));
20. System.out.println("
");
21. }
22. s.close(); // close the Statement to
let th e database know we're done with it
23. con.close(); // close the Connection to
let
the database know we're done with it
24. } catch (SQLException err) {
25. System.out.println("ERROR: " + err);
26. } catch (Exception err) {
27. System.out.println("ERROR: " + err);
28. }
29. }
30. }

After executing this program we can see the following output on the console

After executing this program we can see our table in MySQL as


ELO: Student will be able to make JDBC connection with MySQL database.

Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 5
RMI
Title: Develop RMI application.

Aim: Develop an RMI application which accepts a string or a number and checks that string or
number is palindrome or not.

Theory:
RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one
system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.
Architecture of an RMI Application -
In an RMI application, we write two programs, a server program (resides on the server) and a client
program (resides on the client).
 Inside the server program, a remote object is created and reference of that object is made
available for the client (using the registry).
 The client program requests the remote objects on the server and tries to invoke its methods.
The following diagram shows the architecture of an RMI application.
Let us now discuss the components of this architecture.
 Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.
 Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client
system; it acts as a gateway for the client program.
 Skeleton − This is the object which resides on the server side. stub communicates with this
skeleton to pass request to the remote object.
 RRL(Remote Reference Layer) − It is the layer which manages the references made by the
client to the remote object.
Working of an RMI Application
The following points summarize how an RMI application works −
 When the client makes a call to the remote object, it is received by the stub which eventually
passes this request to the RRL.
 When the client-side RRL receives the request, it invokes a method called invoke() of the
object remoteRef. It passes the request to the RRL on the server side.
 The RRL on the server side passes the request to the Skeleton (proxy on the server) which
finally invokes the required object on the server.
 The result is passed all the way back to the
client. Marshalling and Unmarshalling -
Whenever a client invokes a method that accepts parameters on a remote object, the parameters are
bundled into a message before being sent over the network. These parameters may be of primitive
type or objects. In case of primitive type, the parameters are put together and a header is attached to
it. In case the parameters are objects, then they are serialized. This process is known as marshalling.
At the server side, the packed parameters are unbundled and then the required method is invoked.
This process is known as unmarshalling.
RMI Registry -
RMI registry is a namespace on which all server objects are placed. Each time the server creates an
object, it registers this object with the RMIregistry (using bind() or reBind() methods). These are
registered using a unique name known as bind name.
To invoke a remote object, the client needs a reference of that object. At that time, the client fetches
the object from the registry using its bind name (using lookup() method).
The following illustration explains the entire process –
Goals of RMI -
Following are the goals of RMI −

 To minimize the complexity of the application.


 To preserve type safety.
 Distributed garbage collection.
 Minimize the difference between working with local and remote objects.

Algorithm –

Server side -

Step 1: Start
Step 2: Define the class rmiserver
Step 3: Create the object twox in try
Step 4: Register the object twox
Step 5: Display the exception in catch
Step 6: Stop
Algorithm –

Client side -
Step 1: Start
Step 2: Define the class rmiclient
Step 3: Initialize the string s1 in try
Step 4: Create and Initialize the object onex
Step 5: Assign the value to m by calling the method palin
Step 6: Check whether the string is palindrome or not
Step 7: Display whether the string is palindrome or not
Step 8: Display the exception in catch
Step 9: Stop

Program -

one.java

importjava.rmi.*;

interface one extends Remote

publicintpalin(String a) throws RemoteException;

two.java

importjava.rmi.*;
importjava.lang.*;
importjava.rmi.server.*;
public class two extends UnicastRemoteObject implements one
{
public two() throws RemoteException { }
publicintpalin(String a) throws RemoteException
{
System.out.println("Hello");

StringBufferstr = new StringBuffer(a);

String str1 = str.toString();

System.out.println("Print : " + str1.toString());


StringBuffer str2 = str.reverse();

System.out.println("Print : " + str2.toString());


int b = str1.compareTo(str2.toString());
System.out.println("Print : " + b);
if (b ==
0) return
1; else
return 0;
}
}

rmiserver.java

import java.io.*;
importjava.rmi.*;
import java.net.*;
public class rmiserver
{
public static void main(String args[]) throws Exception
{
try
{
twotwox = new two();
Naming.bind("palin", twox);
System.out.println("Object registered");
}
catch(Exception e)
{
System.out.println("Exception" + e);
}
}
}

rmiclient.java

import java.io.*;
import java.rmi.*;
import java.net.*;
public class rmiclient
{
public static void main(String args[]) throws Exception
{
try
{
String s1 = "rmi://localhost/palin";
one onex = (one)Naming.lookup(s1);
int m = onex.palin("madam");
System.out.println("Print : " + m);
if (m == 1)
{
System.out.println("The given string is a Palindrome");
}
else
{
System.out.println("The given string is not a Palindrome");
}
}
catch (Exception e)
{
System.out.println("Exception" + e);
}
}
}

Output –

Server side -
Client side –

ELO :Student will be able to check whether given string is palindrome or not using RMI.

Conclusion:

--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 6
Inet Address class

Title:Use of Inet Address class and its factory methods.

Aim:Write a program to demonstrate the use of Inet Address class and its factory methods.

Theory:

Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to
get the IP of any host name for example www.javatpoint.com, www.google.com,
www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress
represents the IP address with its corresponding host name. There are two types of addresses:
Unicast and Multicast. The Unicast is an identifier for a single interface whereas Multicast is an
identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name
resolutions.
IP Address -

o An IP address helps to identify a specific resource on the network using a numerical


representation.

o Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual
bridge among the destination and the source.

There are two versions of IP address: -

1. IPv4

IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the
ARAPNET in 1983. It is a widely used IP version to differentiate devices on network using an
addressing scheme. A 32-bit addressing scheme is used to store 2 32 addresses that is more than 4
million addresses.

Features of IPv4:

o It is a connectionless protocol.

o It utilizes less memory and the addresses can be remembered easily with the class based
addressing scheme.
o It also offers video conferencing and libraries.

2. IPv6

IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet addresses. It
provides solutions for the problems present in IPv4. It provides 128-bit address space that can be
used to form a network of 340 undecillion unique IP addresses. IPv6 is also identified with a name
IPng (Internet Protocol next generation).

Features of IPv6:

o It has a stateful and stateless both configurations.

o It provides support for quality of service (QoS).

o It has a hierarchical addressing and routing infrastructure.

TCP/IP Protocol

o TCP/IP is a communication protocol model used connect devices over a network via internet.

o TCP/IP helps in the process of addressing, transmitting, routing and receiving the data
packets over the internet.

o The two main protocols used in this communication model are:

1. TCP i.e. Transmission Control Protocol. TCP provides the way to create a
communication channel across the network. It also helps in transmission of packets at
sender end as well as receiver end.

2. IP i.e. Internet Protocol. IP provides the address to the nodes connected on the
internet. It uses a gateway computer to check whether the IP address is correct and the
message is forwarded correctly or not.
InetAddress – Factory Methods :

o The InetAddress class is used to encapsulate both, the numerical IP address and the
domain name for that address. The InetAddress class has no visible constructors. The
InetAddress class has the inability to create objects directly, hence factory methods are
used for the purpose. Factory Methods are static methods in a class that return an object of
that class.
o There are 5 factory methods available in InetAddress class –

Methods –

staticInetAddressgetLocalHost() throws UnknownHostException - This method returns the instance of


InetAddress containing the local hostname and address.

public static InetAddressgetByName( String host ) throws UnknownHostException - This method


returns the instance of InetAddress containing LocalHost IP and name.

staticInetAddress[] getAllByName( String hostName ) throws UnknownHostException - This method


returns the array of the instance of InetAddress class which contains IP addresses.

staticInetAddressgetByAddress( byte IPAddress[] ) throws UnknownHostException -This method returns


an InetAddress object created from the raw IP address.

StaticInetAddressgetByAddress( String hostName, byte IPAddress[])throws


UnknownHostException - This method creates and returns an InetAddress based on the provided
hostname and IP address.

Program –

import java.io.*;
import java.net.*;
importjava.util.*;
class GFG {
public static void main(String[] args)
throwsUnknownHostException
{
// To get and print InetAddress of Local Host
InetAddress address1 = InetAddress.getLocalHost();
System.out.println("InetAddress of Local Host : "
+ address1);

// To get and print InetAddress of Named Host


InetAddress address2
= InetAddress.getByName("45.22.30.39");
System.out.println("InetAddress of Named Host : "
+ address2);

// To get and print ALL InetAddresses of Named Host


InetAddressaddress3[]
= InetAddress.getAllByName("172.19.25.29");
for (int i = 0; i < address3.length; i++) {
System.out.println(
"ALL InetAddresses of Named Host : "
+ address3[i]);
}

// To get and print InetAddresses of


// Host with specified IP Address
byteIPAddress[] = { 125, 0, 0, 1 };
InetAddress address4
= InetAddress.getByAddress(IPAddress);
System.out.println(
"InetAddresses of Host with specified IP Address : "
+ address4);

// To get and print InetAddresses of Host


// with specified IP Address and hostname
byte[] IPAddress2
= { 105, 22, (byte)223, (byte)186 };
InetAddress address5 =
InetAddress.getByAddress( "gfg.com",
IPAddress2);
System.out.println(
"InetAddresses of Host with specified IP Address and hostname : "
+ address5);
}
}

Output –

InetAddress of Local Host :localhost/127.0.0.1


InetAddress of Named Host : /45.22.30.39
ALL InetAddresses of Named Host : /172.19.25.29
InetAddresses of Host with specified IP Address : /125.0.0.1
InetAddresses of Host with specified IP Address and hostname : gfg.com/105.22.223.186

ELO : Student will be able to implement factory methods of Inet address class.

Conclusion:

--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 7
RMI Server
Title:Develop remote interface and implement RMI server.

Aim:Write program with suitable example to develop your remote interface, implement your RMI
server, implement application that create your server, also develop security policy file.

Theory:
To write an RMI Java application, you would have to follow the steps given below −

 Define the remote interface


 Develop the implementation class (remote object)
 Develop the server program
 Develop the client program
 Compile the application
 Execute the application
Defining the Remote Interface -
A remote interface provides the description of all the methods of a particular remote object. The
client communicates with this remote interface.
To create a remote interface −
 Create an interface that extends the predefined interface Remote which belongs to the
package.
 Declare all the business methods that can be invoked by the client in this interface.
 Since there is a chance of network issues during remote calls, an exception
named RemoteException may occur; throw it.
Following is an example of a remote interface. Here we have defined an interface with the
name Hello and it has a method called printMsg().
importjava.rmi.Remote;
importjava.rmi.RemoteException;

// Creating Remote interface for our application


publicinterfaceHelloextendsRemote{ voidprintMsg()thr
owsRemoteException;
}
Developing the Implementation Class (Remote Object) -
We need to implement the remote interface created in the earlier step. (We can write an
implementation class separately or we can directly make the server program implement this
interface.)
To develop an implementation class −

 Implement the interface created in the previous step.


 Provide implementation to all the abstract methods of the remote interface.
Following is an implementation class. Here, we have created a class named ImplExample and
implemented the interface Hello created in the previous step and provided body for this method
which prints a message.
// Implementing the remote interface
publicclassImplExampleimplementsHello{

// Implementing the interface method


publicvoidprintMsg(){
System.out.println("This is an example RMI program");
}
}
Developing the Server Program
An RMI server program should implement the remote interface or extend the implementation class.
Here, we should create a remote object and bind it to the RMIregistry.
To develop a server program −
 Create a client class from where you want invoke the remote object.
 Create a remote object by instantiating the implementation class as shown below.
 Export the remote object using the method exportObject() of the class
named UnicastRemoteObject which belongs to the package java.rmi.server.
 Get the RMI registry using the getRegistry() method of the LocateRegistry class which
belongs to the package java.rmi.registry.
 Bind the remote object created to the registry using the bind() method of the class
named Registry. To this method, pass a string representing the bind name and the object
exported, as parameters.

Following is an example of an RMI server program. -


importjava.rmi.registry.Registry;
importjava.rmi.registry.LocateRegistry;
importjava.rmi.RemoteException;
importjava.rmi.server.UnicastRemoteObject;

publicclassServerextendsImplExample{ pu
blicServer(){}
publicstaticvoid main(Stringargs[]){
try{
// Instantiating the implementation class
ImplExampleobj=newImplExample();

// Exporting the object of implementation class


// (here we are exporting the remote object to the stub)
Hello stub =(Hello)UnicastRemoteObject.exportObject(obj,0);

// Binding the remote object (stub) in the registry


Registryregistry=LocateRegistry.getRegistry();

registry.bind("Hello", stub);
System.err.println("Server ready");
}catch(Exception e){
System.err.println("Server exception: "+e.toString());
e.printStackTrace();
}
}
}
Developing the Client Program
Write a client program in it, fetch the remote object and invoke the required method using this
object.
To develop a client program −
 Create a client class from where your intended to invoke the remote object.
 Get the RMI registry using the getRegistry() method of the LocateRegistry class which
belongs to the package java.rmi.registry.
 Fetch the object from the registry using the method lookup() of the class Registry which
belongs to the package java.rmi.registry.
To this method, you need to pass a string value representing the bind name as a parameter.
This will return you the remote object.
 The lookup() returns an object of type remote, down cast it to the type Hello.
 Finally invoke the required method using the obtained remote object.
Following is an example of an RMI client program.
importjava.rmi.registry.LocateRegistry;
importjava.rmi.registry.Registry;

publicclassClient{ privateClient(){}
publicstaticvoid main(String[]args){ try{
// Getting the registry
Registryregistry=LocateRegistry.getRegistry(null);

// Looking up the registry for the remote object Hello


stub =(Hello)registry.lookup("Hello");

// Calling the remote method using the obtained object


stub.printMsg();

// System.out.println("Remote method invoked");


}catch(Exception e){
System.err.println("Client exception: "+e.toString());
e.printStackTrace();
}
}
}
Compiling the Application
To compile the application −

 Compile the Remote interface.


 Compile the implementation class.
 Compile the server program.
 Compile the client
program. Or,
Open the folder where you have stored all the programs and compile all the Java files as shown
below.

javac *.java
Executing the Application
Step 1 − Start the rmi registry using the following command.
startrmiregistry

This will start an rmi registry on a separate window as shown below.

Step 2 − Run the server class file as shown below.


Java Server
Step 3 − Run the client class file as shown below.
java Client

Verification − As soon you start the client, you would see the following output in the server.
ELO:Student will be able to demonstrate concept of remote interface, and create a RMI server
along with security file in java.

Conclusion:

--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 8
Database application

Title:Making database application.


Aim: Write a database application that uses any JDBC driver.
Theory:
To establish a connection with MySQL in JDBC, first we have to install MySQL on our system and
we have to add the MySQL connector (it is a .jar file containing the classes that are the
implementation of interfaces provided by Sun Microsystems ) to our class path variable. After doing
this the classes implementing the interfaces provided by Sun Microsystem are available to our
program.

How to add MySql connector to our class path variable: There are two approaches for adding the
MySQL connector to our class path variable. Both are given below.

Adding MySQL connector temporarily -


In this approach, we simply set the classpath variable = path to where our MySQL connector is
stored on our system at the command prompt or console window. This approach is applicable until
we close our console. After closing the console window, the classpath variable removes the path of
MySQL connector.

syntax : c:\> set classpath=path of connector;

For example, the given image is helpful for understanding the syntax

Adding MySQL connector permanently –


Go to My Computer and after right clicking, select the Properties option and click on that.
System Properties window will open, select Advanced option and the following window will open.
Select Environment Variable option and the following window will open.
Select the class path variable (left click) and click on Edit button and the following window will
open.
In the System Variable window, go to the end of Variable value option and place a semicolon, after
that add the path of connector followed by semicolon and click on the ok button.

Creating database in MySQL and granting it all privileges: To perform this we follow the following
steps

 Open MySQL and enter the password after this my mysql> prompt will open

 Create a database with the following command


 Granting a user name, password and all privileges with the following command

Now our MySQL database is ready for creating a connection with JDBC.

31 import
.
32 java.sql.*;
public class
.
33 MySQLdatabase
public static{ void main(String[]
.
34 args)
try{
.
35 { Class.forName("com.mysql.jdbc.Driver
.
36 ");
Connection con =
. n("jdbc:mysql://localhost/sqldatabase",
DriverManager.getConnectio "amit",
"amitabh");
37 Statement s =
.
38 con.createStatement();
s.execute("create table student (
. nteger,stud_namestud_id i
varchar(20),stud_address varchar(30)
)"); /
39 / create a tables.execute("insert into student
. values(001,'
40 ARman','Delhi')"); // insert firstinto
s.execute("insert row student
into the table
. Robert','Canada')");
values(002,'
// insert second row into the
41 table s.execute("insert into student
. Ahuja','Karnal')");
values(003,'
// insert third row into the
table
42. ResultSet rs = s.executeQuery("select *
fro
m student");
43. if (rs != null) // if rs == null, then
ther e is no record in ResultSet to show
44. while (rs.next()) // By this line we
wi
ll step through our data row-by-row
45. {
46. System.out.println("
");
47. System.out.println("Id of the
student:
" + rs.getString(1));
48. System.out.println("Name of student:
"
+ rs.getString(2));
49. System.out.println("Address of
student: " + rs.getString(3));
50. System.out.println("
");
51. }
52. s.close(); // close the Statement to
let th e database know we're done with it
53. con.close(); // close the Connection to
let
the database know we're done with it
54. } catch (SQLException err) {
55. System.out.println("ERROR: " + err);
56. } catch (Exception err) {
57. System.out.println("ERROR: " + err);
58. }
59. }
60. }

After executing this program we can see the following output on the console
After executing this program we can see our table in MySQL as

ELO: Student will be able to write database application that uses JDBC driver.

Conclusion:
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 9
JSP

Title:Writing JSP page.

Aim:Write a simple JSP page to display a simple message (It may be a simple html page).

Theory:

JSP technology is used to create web application just like Servlet technology. It can be thought of as
an extension to Servlet because it provides more functionality than servlet such as expression
language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet
because we can separate designing and development. It provides some additional features such as
Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet -

There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation logic.
In Servlet technology, we mix our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code needs
to be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page -

The JSP pages follow these phases:

o Translation of JSP Page

o Compilation of JSP Page

o Classloading (the classloader loads class file)

o Instantiation (Object of the Generated Servlet is created).

o Initialization ( the container invokes jspInit() method).

o Request processing ( the container invokes _jspService() method).

o Destroy ( the container invokes jspDestroy() method).


As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator.
The JSP translator is a part of the web server which is responsible for translating the JSP page into
Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file.
Moreover, all the processes that happen in Servlet are performed on JSP later like initialization,
committing response to the browser and destroy.

Creating a simple JSP Page -

To create the first JSP page, write some HTML code as given below, and save it by .jsp extension.
We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory
in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the JSP
page.

1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>

It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

o Start the server

o Put the JSP file in a folder and deploy on the server

o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,


http://localhost:8888/myapplication/index.jsp
Do I need to follow the directory structure to run a simple JSP?

No, there is no need of directory structure if you don't have class files or TLD files. For example, put
JSP files in a folder directly and deploy that folder. It will be running fine. However, if you are using
Bean class, Servlet or TLD file, the directory structure is required.

The Directory structure of JSP -

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB- INF
folder or in any directory.

ELO :Student will be able to create JSP page to display a simple message.
Conclusion:

--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
Experiment No. 10
Calculator Application
Title: Implementation of calculator using servlet.
Aim: Create a simple calculator application using servlet.

Theory:
Servlet technology is used to create a web application (resides at server side and generates a dynamic
web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was common as a server-side programming language.
However, there were many disadvantages to this technology. There are many interfaces and classes
in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse,
etc.

What is servlet –

o Servlet is a technology which is used to create a web application.

o Servlet is an API that provides many interfaces and classes including documentation.

o Servlet is an interface that must be implemented for creating any Servlet.

o Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.

o Servlet is a web component that is deployed on the server to create a dynamic web page.
Calculator App

Enter First Number


Enter Second Number
Select an Operation

ADDTION SUBSTRACTION MULTIPLY DIVIDE

Program –

Step 1: Create a new project


Step 2: Select java web → web Application
--> index.html
<html>
<head>
<title>Calculator App</title>
</head>
<body>

<form action="CalculatorServlet" method="post" >

Enter First Number <input type="text" name="txtN1" ><br> Enter Second Number <input
type="text" name="txtN2" ><br> Select an Operation
<input type="radio" name="opr" value="+">ADDTION
<input type="radio" name="opr" value="*">MULTIPLY <input type="radio" name="opr"
value="/">DIVIDE
<input type="radio" name="opr" value="-">Substraction
<br><input type="reset">
<input type="submit" value="Calculate" >
</form>
</body>
</html
Step 3: Add a new Servlet to source package
-Name the servlet and package
-Check “Add information to deployment descriptor” to add servlet into web.xml But preferably use
annotation.

CalculatorServlet.java

Program-

packagemypack;

importjava.io.IOException;

importjava.io.PrintWriter;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

public class CalculatorServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException { response.setContentType("text/html;charset=UTF-8);


PrintWriter out = response.getWriter();

out.println("<html><head><title>Servlet CalculatorServlet</title></head><body>");
double n1 = Double.parseDouble(request.getParameter("txtN1"));
double n2 = Double.parseDouble(request.getParameter("txtN2"));
double result =0;

String opr=request.getParameter("opr");
if(opr.equals("+")) result=n1+n2;
if(opr.equals("-")) result=n1-n2;
if(opr.equals("*")) result=n1*n2;
if(opr.equals("/")) result=n1/n2;

out.println("<h1> Result = "+result);


out.println("</body></html>");
}

Output:

Enter First Number


Enter Second Number
Select an Operation ADDTION SUBSTRACTION MULTIPLY DIVIDE
Reset Calculate
ELO: Student will able to design a calculator using servlet.

Conclusion:

--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------

You might also like