You are on page 1of 79

ADVANCED JAVA PROGRAMS

Index
1 Write a java program that connects to a database using JDBC and
does add, delete, modify and retrieve operations. Create Appropriate
GUI using AWT for user interaction.
2) Write a Java program that demonstrates the use of collection classes.
3) Implement the java program’s for server and client to demonstrate
networking in java using socket. (Single server and single client, Single
server and multiple clients).
A) Single Server Single client.
B) Single Server and Multiple client.
4) Write a Java program that demonstrates the use of RMI technology.
5) Write a java program that implements a multi-thread
application that has three threads. First thread generates
random integer every 1 second and if value is even , second
thread computes the square of the number and prints. If the
value is odd, the third thread will print the value of cube of the
number
6) Create a simple java web application using servlet, jsp and
jdbc.
7) Create a Java Web Application which show the login page
with Username, password and
login And register button.
On login button it validate the user name and password
entered by user with database

1
information stored in login info database table if it is correct
then show message login
successful and open home page which will show all the record
of login info table into grid. If
information is incorrect then show message invalid
credentials.
On Register Button show the register page, on this page show
the username, password, date of
Birth field to save this information into login info database
table.
On register page show two button save and cancel.
On save button record should be saved to database table login
info and login page should be
Opened. Cancel it will returns back to login page.
8) Write a java program that Demonstrates java Beans.
9) Write a java program that demonstrates EJB.

2
ADVANCED JAVA PROGRAMS
For Study only
1 Write a java program that connects to a database using JDBC and
does add, delete, modify and retrieve operations. Create Appropriate
GUI using AWT for user interaction.
Step 1: Create a database file (Microsoft Access) open and click Blank
database. And save to your favorite location Ex. C: D: E:
Step 2: After that go to Control Panel
A) Condition 1 if you see like this:

Then click System and Security->Administrative Tools->ODBC


Data Sources

3
B) Condition 2 if you see like this:

Then click Administrative Tools->ODBC Data Sources


Step 3: Then Add data Sources so click the Add Button and select the
Microsoft Access Driver (*.mdb, *.accdb)->Finish.
Step 4: Then add Data Source name and add Microsoft Access file by
clicking the select button. After that close all
Step 5: Then now open the netbeans 8.0.2 and create new project go
to File->New Project->java=java application->Finish.
Step 6: then lookout the left side of IDE there are three tab called
project, Files, Services. Go to the services tab then click Database-
>Driver->JDBC-ODBC Bridge Driver. Click the right button of mouse and
click connect using. Then on JDBC url box enter your Data_Source name
jdbc:odbc:DataSourceName ->Finish.
Step 7: then go to project tab extract your project by clicking the + icon
Go to Source Packages->javaapplication. Right click the package new-
>JPanel Form then add the buttons, label, textfield.

4
Form design

Step 8: double click on button and type the code.


Code……. NOTE: type only bold Text other well come automatic
package javaapplication7;
import java.sql.*;
public class NewJFrame extends javax.swing.JFrame {
Connection c;
PreparedStatement state;
ResultSet r;
int i=0;
DriverManager d;

public NewJFrame() {

5
initComponents();
}

/**
* This method is called from within the constructor to initialize the
form.
* WARNING: Do NOT modify this code. The content of this method is
always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jButton1 = new javax.swing.JButton();


jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();

6
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLO
SE);
setTitle("Application");

jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N


jButton1.setText("insert");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

jButton2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N


jButton2.setText("delete");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jButton3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N


jButton3.setText("search");

7
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

jButton4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N


jButton4.setText("update");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});

jTextField1.setFont(new java.awt.Font("Tahoma", 0, 24)); //


NOI18N
jTextField1.setText("jTextField1");

jTextField2.setFont(new java.awt.Font("Tahoma", 0, 24)); //


NOI18N
jTextField2.setText("jTextField2");

jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N

8
jLabel1.setText("Rno");

jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N


jLabel2.setText("Name");

javax.swing.GroupLayout layout = new


javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADIN
G)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(jLabel1,
javax.swing.GroupLayout.PREFERRED_SIZE, 95,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELA
TED))

9
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(37, 37, 37)))

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField2,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)

10
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELA
TED)
.addComponent(jButton2)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELA
TED)
.addComponent(jButton3)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRE
LATED)
.addComponent(jButton4)
.addGap(0, 14, Short.MAX_VALUE))
);
layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADIN
G)
.addGroup(layout.createSequentialGroup()
.addGap(63, 63, 63)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.BASELINE)

11
.addComponent(jLabel1,
javax.swing.GroupLayout.PREFERRED_SIZE, 47,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.LEADING)
.addComponent(jLabel2)
.addComponent(jTextField2,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELA
TED, 99, Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))

12
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent
evt) {
try{
System.out.println("Inserting");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c=DriverManager.getConnection("jdbc:odbc:dsn1","","");
int e1=Integer.parseInt(jTextField1.getText());
state=c.prepareStatement("insert into student values(?,?)");
state.setInt(1,e1);
state.setString(2,jTextField2.getText());
i=state.executeUpdate();
System.out.println(i);
c.commit();
} catch(ClassNotFoundException | SQLException |
NumberFormatException e)
{
System.out.println(e);
}
}

13
private void jButton4ActionPerformed(java.awt.event.ActionEvent
evt) {
try{
System.out.println("updateing");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c=DriverManager.getConnection("jdbc:odbc:dsn1","","");
int e1=Integer.parseInt(jTextField1.getText());
state=c.prepareStatement("update student set Name=? where
Rno=?");
state.setString(1,jTextField2.getText());
state.setInt(2,e1);
i=state.executeUpdate();
System.out.println(i);
c.commit();
} catch (ClassNotFoundException | SQLException |
NumberFormatException e)
{
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent
evt) {
try{
System.out.println("deleteing");

14
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c=DriverManager.getConnection("jdbc:odbc:dsn1","","");
int e1=Integer.parseInt(jTextField1.getText());
state=c.prepareStatement("delete from student where
Rno=?");
state.setInt(1, e1);
i=state.executeUpdate();
System.out.println(i);
c.commit();
} catch(ClassNotFoundException | SQLException |
NumberFormatException e)
{
System.out.println(e);
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent
evt) {
try
{
System.out.println("searching");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c=DriverManager.getConnection("jdbc:odbc:dsn1","","");

15
state=c.prepareStatement("select *from student where
Rno=?");
int e1=Integer.parseInt(jTextField1.getText());
state.setInt(1, e1);
r=state.executeQuery();
while(r.next())
{
jTextField2.setText(r.getString("Name"));
}
}
catch (ClassNotFoundException | SQLException |
NumberFormatException e)
{
System.out.println(e);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel
setting code (optional) ">

16
/* If Nimbus (introduced in Java SE 6) is not available, stay with the
default look and feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.
html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java
.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java
.util.logging.Level.SEVERE, null, ex);

17
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java
.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java
.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;

18
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}

19
2) Write a Java program that demonstrates the use of collection
classes.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
public class Collection_classes {
public static void main(String[] args) {
System.out.println("****Arrays Collection Class****"); //1
int ar[]={10,20,30};
Arrays.sort(ar);
System.out.println("Array Element are:-"+Arrays.toString(ar));
int index=Arrays.binarySearch(ar,20);

20
System.out.println("Index Position of Element 20 is:-"+index);
int[] cp=Arrays.copyOf(ar,3);
System.out.println("Creating Arrays Copy"+Arrays.toString(cp));

System.out.println("****ArrayList collection class****"); //2


ArrayList a=new ArrayList();
a.add("IMCA");
a.add("MCA");
a.add("MBA");
a.add("BCA");
a.add("BBM");
a.add("BBA");
int n= a.size();
System.out.println("Size of Array:->"+n);
System.out.println("Element in Array:-");
Iterator it1=a.iterator();
while(it1.hasNext())
{
System.out.println(it1.next());
}
a.remove("MCA");
System.out.println("Remove Element MCA");

21
System.out.println("Element in Array:-");
Iterator it=a.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
System.out.println("Searching Contain
IMCA:"+a.contains("IMCA"));
System.out.println( "Is ArrayList Empty:->"+a.isEmpty());

System.out.println("****HashMap collection class****"); //3


HashMap hm=new HashMap();
hm.put(100,"Amul");
hm.put(101,"Pihu");
hm.put(102,"Rahul");
int s=hm.size();
System.out.println("Size of Array:->"+s);
Set s1=hm.entrySet();
System.out.println("Elements in HashMap are:-");
Iterator i=s1.iterator();
while(i.hasNext())

22
{
Map.Entry m=(Map.Entry)i.next();
System.out.print(m.getKey());
System.out.println("-"+m.getValue());
}
boolean ck=hm.containsKey(101);
System.out.println("Present Contain Key 101:-"+ck);
boolean cv=hm.containsValue("Priya");
System.out.println("Present Contain Value Priya:-"+cv);
System.out.println("Is HashMap is empty:-"+hm.isEmpty());
hm.clear();
int sizehm=hm.size();
System.out.println("HashMap Size After Clearing Elements-
:"+sizehm);

System.out.print("****Linked List Collection Class****\n");


//4
LinkedList l=new LinkedList();
l.addAll(a);
System.out.println("Size of Linked List:-"+l.size());
System.out.println("Linked List Elements:"+l);
System.out.println("Searching Contain IMRD:"+l.contains("IMRD"));
l.clear();

23
System.out.println("After Clearing Linked List Elements are:-
"+l.size());
System.out.println("Is Linked List is empty:-"+l.isEmpty());

System.out.print("****Linked List HashSet Collection


Class****\n");//5
LinkedHashSet lh=new LinkedHashSet();
lh.addAll(a);
System.out.println("Elements:"+lh);
System.out.println("Searching Contains MCA:"+
lh.contains("MCA"));
lh.clear();
System.out.println("Clearing LinkedList Hashset"+l.size());

System.out.println("****Stack Collection Class****"); //6


Stack st=new Stack();
st.push("A");
st.push("B");
st.push("C");
System.out.println("Stack Elements are:-");
Enumeration e=st.elements();
while(e.hasMoreElements())
{

24
System.out.println(e.nextElement());
}
System.out.println("Last Element of Array is:-"+st.peek());
System.out.println("Deleting Element :-"+st.pop());
int sizes=st.size();
System.out.println("After Deleting Size of Stack:-"+sizes);
st.clear();
System.out.println("Clearing the Stack:-"+st.size());

System.out.println("****Vector Collection Class****"); //7


Vector v=new Vector();
v.add("Raj");
v.add("Anand");
v.add("Rahul");
v.add("Hemant");
System.out.println("Element in Vector:-");
Iterator v1=v.iterator();
while(v1.hasNext())
{
System.out.println(v1.next());
}
v.remove("Rahul");

25
System.out.println("After Removing Element 'Rahul'");
System.out.println("Element in Vector:-");
Iterator v2=v.iterator();
while(v2.hasNext())
{
System.out.println(v2.next());
}
int sizev=v.size();
System.out.println("Size of Elements in Vector :-"+sizev);
System.out.println( "Is Vector Empty:->"+v.isEmpty());
v.clear();
int sizev1=v.size();
System.out.println("Vector Size After Clearing Elements:- "+sizev1);

System.out.println("****HashTable Collection Class"); //8


Hashtable ht=new Hashtable();
ht.put(1,"Kajal");
ht.put(2,"Vaishnavi");
ht.put(3,"Ruchita");
ht.put(4,"Monisa");
Set sht=ht.entrySet();
System.out.println("Elements in HashTable are:-");

26
Iterator hti=sht.iterator();
while(hti.hasNext())
{
Map.Entry m=(Map.Entry)hti.next();
System.out.print(m.getKey());
System.out.println("-"+m.getValue());

}
ht.remove(3);
System.out.println("After Removing Element 'Ruchita'");
Iterator htj=sht.iterator();
while(htj.hasNext())
{
Map.Entry m=(Map.Entry)htj.next();
System.out.print(m.getKey());
System.out.println("-"+m.getValue());
}
boolean b1=ht.containsKey(4);
System.out.println("Present Contain Key 4:-"+b1);
boolean b2=ht.containsValue("priya");
System.out.println("Present Contain Value priya:-"+b2);
ht.clear();

27
int sizeht=ht.size();
System.out.println("HashTable Size After Clearing Elements-
:"+sizeht);

System.out.println("****HashSet Collection Class****"); //9


HashSet hs=new HashSet();
hs.addAll(a);
System.out.println("Element in HashSet Are:-");
Iterator hs1=hs.iterator();
while(hs1.hasNext())
{
System.out.println(hs1.next());
}
hs.remove("BBA");
System.out.println("After Removing Element 'BBA'");
System.out.println("Element in HashSet:-");
Iterator hs2=hs.iterator();
while(hs2.hasNext())
{
System.out.println(hs2.next());
}
int sizehs=hs.size();

28
System.out.println("Size of Elements in HashSet :-"+sizehs);
System.out.println( "Is HashSet Empty:->"+hs.isEmpty());
hs.clear();
System.out.println("HashSet Size After Clearing Elements:-
"+hs.size());
}
}
OUTPUT:

29
30
3) Implement the java program’s for server and client to demonstrate
networking in java using socket. (Single server and single client, Single
server and multiple clients).
A) Single Server and single client.
1)Server
import java.net.*;
import java.io.*;
public class Server {
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());
DataInputStream br=new DataInputStream((System.in));
String str="",str2="";
while(!str.equals("stop"))
{
str=din.readUTF();
System.out.println("Client Says: "+str);
str2=br.readLine();
dout.writeUTF(str2);

31
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
2)Client
import java.net.*;
import java.io.*;
public class Client {
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());
DataInputStream br=new DataInputStream(System.in);
String str="",str2="";
while(!str.equals("stop"))
{
str=br.readLine();

32
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server Says: "+str2);
}
dout.close();
s.close();
}
}
OUTPUT:

Client Side:

hi

Server Says: Hello Client....

stop

Server Says: stop

BUILD SUCCESSFUL (total time: 43 seconds)

Server Side:

Client Says: hi

Hello Client....

Client Says: stop

stop

BUILD SUCCESSFUL (total time: 1 minute 2 seconds)

33
B) Single Server Multiple Clients
A) Server
import java.net.*;
import java.io.*;
public class Server {
public static void main(String args[])throws Exception
{
Socket s=null;
ServerSocket ss2=null;
System.out.println("Server Listening......");
try {
ss2=new ServerSocket(4445);
} catch (IOException e) {
System.out.println("Server Error");
}
while(true)
{
try {
s=ss2.accept();
System.out.println("Connection Established");
ServerThread st=new ServerThread(s);
st.start();

34
} catch (Exception e) {
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread
{
String line=null;
DataInputStream is=null;
PrintWriter os=null;
Socket s1=null;
public ServerThread(Socket s)
{
s1=s;
}
public void run()
{
try {
is=new DataInputStream(s1.getInputStream());
os=new PrintWriter(s1.getOutputStream());
line=is.readLine();

35
while(line.compareTo("Quit")!=0)
{
os.println(line);
os.flush();
System.out.println("Response to Client: "+line);
line=is.readLine();
}
is.close();
os.close();
s1.close();
} catch (Exception e) {
System.out.println("Socket Error close Error");
}
}
}
B) Client
import java.net.*;
import java.io.*;
public class Client {
public static void main(String args[])throws Exception
{
Socket s1=null;

36
String line=null;
DataInputStream br=null;
DataInputStream is=null;
PrintWriter os=null;
try {
s1=new Socket("localhost",4445);
br=new DataInputStream(System.in);
is=new DataInputStream(s1.getInputStream());
os=new PrintWriter(s1.getOutputStream());
} catch (IOException e) {
System.out.println("IO Exception");
}
System.out.println("ENTER DATA TO ECHO SERVER (ENTER Quit TO
END): ");
String response=null;
try {
line=br.readLine();
while(line.compareTo("Quit")!=0)
{
os.println(line);
os.flush();
response=is.readLine();

37
System.out.println("Server Response: "+response);
line=br.readLine();
}
is.close();
os.close();
br.close();
s1.close();
System.out.println("Connection Closed");
} catch (IOException e) {
System.out.println("Socket Read Error");
}
}
}
Output:

Client:

ENTER DATA TO ECHO SERVER (ENTER Quit TO END):

hey

Server Response: hey

Hello

Server Response: Hello

Single Server Multiplae Client

Server Response: Single Server Multiplae Client

Quit

Connection Closed

Server:

38
Server Listening......

Connection Established

Response to Client: hey

Response to Client: Hello

Response to Client: Single Server Multiplae Client

Socket Error close Error

Quit

39
4) Write a Java program that demonstrates the use of RMI
technology.
RMI (Remote Method Invocation)
RMI Program
1) Create the remote interface
import java.rmi.*;
public interface Adder extends Remote{
public int add(int x,int y)throws RemoteException;
}
2) Provide the implementation of the remote interface
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject
implements Adder{
AdderRemote()throws RemoteException
{
super();
}
public int add(int x,int y)
{
return x+y;

40
}
}
3) Create and run the server application
import java.rmi.*;
import java.rmi.registry.*;
public class Server {
public static void main(String[] args)
{
try {
Adder skeleton=new AdderRemote();
Registry registry=LocateRegistry.createRegistry(8888);
registry.rebind("ss",skeleton);
} catch (Exception e) {
System.out.println("Exp in Server "+e);
}
}
}
4) Create and run the client application
import java.rmi.*;
public class Client {

41
public static void main(String[] args)
{
try {
Adder
stub=(Adder)Naming.lookup("rmi://localhost:8888/ss");
System.out.println(stub.add(44,6));
} catch (Exception e) {
System.out.println("Exp is Client "+e);
}
}
Output:
50

42
5) Write a java program that implements a multi-thread
application that has three threads. First thread generates
random integer every 1 second and if value is even , second
thread computes the square of the number and prints. If the
value is odd, the third thread will print the value of cube of
the number
package thread1;
import java.util.Random;
public class Thread1 {
static int i;
static class ThreadDemo1 extends Thread
{
@Override
public void run()
{
try {
for(int j=0;j<5;j++)
{
Random random = new Random();
int r=random.nextInt(10);
System.out.println(r);
i=r;

43
Thread.sleep(500);
}
} catch (Exception e) {
System.out.println("Thread interupted "+e);
}
}
}
static class ThreadDemo2 extends Thread
{
@Override
public void run()
{
try {
for(int j=0;j<5;j++)
{
if(i%2==0)
System.out.println(i*i);
Thread.sleep(500);
}
} catch (Exception e) {

44
System.out.println("Thread Interupted "+e);
}
}
}
static class ThreadDemo3 extends Thread
{
@Override
public void run()
{
try {
for(int j=0;j<5;j++)
{
if(i%2!=0)
System.out.println(i*i*i);
Thread.sleep(500);
}
} catch (Exception e) {
System.out.println("Thread interupted "+e);
}
}

45
}
public static void main(String[] args) {
ThreadDemo1 T1=new ThreadDemo1();
T1.start();
ThreadDemo2 T2=new ThreadDemo2();
T2.start();
ThreadDemo3 T3=new ThreadDemo3();
T3.start();
}
}

46
6) Create a simple java web application using servlet, jsp and
jdbc.
Step 1) create a database using Microsoft access and create dsn(data
source connection) form control panel.
Step 2) open netbeans and go to driver panel and drives then select
JDBC-ODBC Bridge and connect dsn to netbeans
Note: all steps are brief show in 1 page click
Step 3) Then now open the netbeans and create new project go to File-
>New Project->Java Web=Web Application->Name of your project-
>Finish.
Step 4) right click on Source packages and select servlet and click next
then check the box called Add information to deployment
descriptor(web.xml) then click Finish.
Now type code in jsp file
Index.jsp
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>

47
<div>TODO write content</div>
<form action="NewServlet" method="get">
<input type="submit" value="click">
</form>
</body>
</html>
Servlet
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
PrintWriter out=response.getWriter();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
c=DriverManager.getConnection("jdbc:odbc:dsn1","","");
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select *from student");
out.println("Record are as Folllows\n");
while(rs.next())
{

48
out.println(rs.getInt("rno")+" "+"
"+rs.getString("sname"));
}
} catch (IOException | ClassNotFoundException |
SQLException e) {
System.out.println("Exp= "+e);
}
}
Output:
Before

After

49
7) Create a Java Web Application which show the login page
with Username, password and
login And register button.
On login button it validate the user name and password
entered by user with database
information stored in login info database table if it is correct
then show message login
successful and open home page which will show all the record
of login info table into grid. If
information is incorrect then show message invalid
credentials.
On Register Button show the register page, on this page show
the username, password, date of
Birth field to save this information into login info database
table.
On register page show two button save and cancel.
On save button record should be saved to database table login
info and login page should be
Opened. Cancel it will returns back to login page.
Step 1) create a Microsoft access database and
Table name: student
Colum: username,password,dob
Step 2) then go to new project->java web->web application-
>next->next->Finish.

50
Index.jsp
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.Statement"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Login</title>
</head>
<body>
<form action="Home.jsp" method="POST">
<br><br><br><br>
<center>
<h1>Login User</h1>
User Name<input type="text" name="uname"><br><br>
Password <input type="text" name="pass"><br><br>
<input type="Submit" name="submit"
value="Login">&nbsp;&nbsp; &nbsp;
<a href="Registration.jsp"><input type="Button"
value="Register"></a></center>

51
</form>
<%
try
{
String uName,pass,dob;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection co =
DriverManager.getConnection("jdbc:odbc:dsn3","","");
Statement st = co.createStatement();
uName = request.getParameter("uname");
pass = request.getParameter("pass");
dob = request.getParameter("dob");
st.executeUpdate("insert into
student(username,password,dob)
values('"+uName+"','"+pass+"','"+dob+"')");
}
catch (Exception e)
{
System.out.println("Error : "+e);
}
%>
</body>
</html>

52
Home.jsp
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.io.PrintWriter"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Home</title>
</head>
<body>
<%
String uName,pass,dob;
PrintWriter o = response.getWriter();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection co =
DriverManager.getConnection("jdbc:odbc:dsn3","","");
Statement st = co.createStatement();
try

53
{
uName = request.getParameter("uname");
pass = request.getParameter("pass");
dob = request.getParameter("dob");
ResultSet rs = st.executeQuery("Select * from student
where username='"+uName+"' and password='"+pass+"'");
if(rs.next())
{
%><center><h1>Login Success</h1><%
ResultSet rs1 = st.executeQuery("Select *from student");
%><table border='1' cellpadding='5'><%
while(rs1.next())
{%>
<tr>
<td> <%= rs1.getString("username") %> </td>
<td> <%= rs1.getString("password") %> </td>
<td> <%= rs1.getDate("dob") %> </td>
</tr>
<%}%>
</table></center> <%
}
else

54
{
%>Plzz Enter Valid Username & Password<%
}
}
catch (Exception e)
{
System.out.println("Error : "+e);
}
%>
</body>
</html>

55
Registration.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Registration</title>
</head>
<body>
<form action="index.jsp" method="POST">
<br><br><br><br>
<center>
<h1>Register User</h1>
User name <input type="text" name="uname"><br><br>
Password <input type="text" name="pass" ><br><br>
DOB <input type="date" name="dob"><br><br>
<input type="Submit" name="submit"
value="Save">&nbsp;&nbsp; &nbsp;
<a href="index.jsp"><input type="Button"
value="Cancel"></a></center>
</form>
</body>
</html>

56
Output:

57
8) Write a java program that Demonstrates java Beans.
Step 1) File->New Project->Java Web=Web Application->Name of
your project->Finish.
Step 2) Right click on Source Packages->new->java class. Add class
name and package name and finish.
Student.java
on student.java file import the java.io.Serializable
And right click below the class import code and click Add Property on
Name: rno; name: sname;
Type: Integer; type:String
Eg:

58
Name: rno; name: sname;
Type: Integer; type:String
Program:
package packeg;
import java.io.Serializable;
public class beans implements Serializable{
private Integer rno;
private String snam;
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getRno() {
return rno;
}
public void setRno(Integer rno) {
this.rno = rno;
}
}

59
Index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<jsp:useBean id="student" class="packeg.beans">
<jsp:setProperty name="student" property="rno"
value="123"/>
<jsp:setProperty name="student" property="sname"
value="Manoj"/>
</jsp:useBean>
RNO is <jsp:getProperty name="student" property="rno"/>
Name is <jsp:getProperty name="student" property="sname"/>

</body>
</html>
Output:

60
61
9) Write a java program that demonstrates EJB.
Step 1) Open netbeans and
Go to File->New Project->Java EE->Enterprise Application-
>next->next->Server: GlassFish Server->Finish.
Step 2) Create a ejb on the left hand side right click on
EnterpriseApplication-ejb->new->session bean.

Now enter the session bean name and package and check that
local box as show in image below.

62
Now left click below the class Insert code->add business
method. Img.1 img.2

63
Now add method name addition and Return type: Integer

Now Add parameter a,b and click OK

64
Code will come add return (a+b)
Calcbean.java
@Override
public Integer addition(int a, int b) {
return (a+b);
}
Step 3) now right click on EnterpriseApplication1-war->new-
>Servlet.
Give the name of servlet like calcservle and package name
sessionbean.
Next->check that box and finish
Now in the below the class right click insert code and show in
image below:

Image 1 ↑ image 2 ↑ click Ok

65
Now type the code:
In body session
Calcservlet.java
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet calcservlet</title>");
out.println("</head>");
out.println("<body>");
int a=Integer.parseInt(request.getParameter("t1"));
int b=Integer.parseInt(request.getParameter("t2"));
out.println("<h1> SUM= "+calcbean.addition(a,
b)+"</h1>");
out.println("</body>");
out.println("</html>");
}
}

66
Step 4) now create a jsp file show in image:

Give the name calcjsp.


Type this code:
Calcjsp.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Enterprise Application</title>
</head>
<body>

67
<h1>Hello World!</h1>
<form action="calcservlet" method=”POST”>
Enter the 1st number<input type="text" name="t1"/>
Enter the 2nd number<input type="text" name="t2"/>
<input type="submit" value="add"/>
</form>
</body>
</html>
Step 5)
Now right click the EnterpriseApplication1->Deploy.

After process complete

68
Click run

Now on browser in the url bar type your jsp file name like
calcjsp.jsp

Now click enter give input

69
70
Hibernate Program
Step 1) create a database in Microsoft Access.
Table name -> student.
Colum names-> rno , sname
And create DSN in control panel.
Step 2) Open netbeans and go to new project->java web->web
Application->next->next->(select server [Apache Tomcat])-
>next->select (Hibernate)-> select dsn1 -> finish.
Step 3)

This file automatic open after that go to Source


And type this code below.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-
//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-
3.0.dtd">

71
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">sun.jdbc.odbc.Jdbc
OdbcDriver</property>
<property
name="hibernate.connection.url">jdbc:odbc:dsn1</property>
<property
name="hibernate.dialect">org.hibernate.dialect.SQLServerDial
ect</property>
<mapping resource="hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Step 4) go to source packages and right click create folder give
the name (com)
And inside the folder create a java class called student1.

72
And type this code in side the student .java
Code: type only red code other add using getter and setter

73
package com;
public class student {
private int rno;
private String sname;
public int getRno() {
return rno;
}
public void setRno(int rno) {
this.rno = rno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
}

74
Step 5) now right click on <default package> -> new ->
Hibernate mapping Wizard.

Then keep the name default and next-> then select table

75
And type this code:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC


"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-
3.0.dtd">

<hibernate-mapping>
<class name="com.student" table="student">
<id name="rno">
<generator class="increment"/>
</id>
<property name="sname" column="sname"/>
</class>
</hibernate-mapping>

76
Step 6) now go to source packages and right click create folder
give the name (test)
And inside the folder create a java class called studenttest

And type this code


package test;
import com.student;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class studenttest {
public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Transaction transaction=session.beginTransaction();

77
student stud=new student();
stud.setSname("shirpur");
session.save(stud);
transaction.commit();
session.close();
}
}
And Run this file
Output:

78
79

You might also like