0% found this document useful (0 votes)
453 views

4th Sem JAVA Record 2009

This document contains code snippets from a Java and J2EE laboratory course. The snippets demonstrate various Java concepts including constructor and method overloading, inner classes, inheritance, exception handling, interfaces, threads, and applets. The snippets are accompanied by sample outputs showing the behavior and results of running the code examples.

Uploaded by

Mach Macher
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
453 views

4th Sem JAVA Record 2009

This document contains code snippets from a Java and J2EE laboratory course. The snippets demonstrate various Java concepts including constructor and method overloading, inner classes, inheritance, exception handling, interfaces, threads, and applets. The snippets are accompanied by sample outputs showing the behavior and results of running the code examples.

Uploaded by

Mach Macher
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 62

07MCA46: Java and J2EE Laboratory

1a. JAVA Program to demonstrate Constructor Overloading and Method Overloading.

class Cons
{
int a,b;
Cons()
{
a=1;
b=1;
}
Cons(int i)
{
a=i;
b=i;
}
Cons(int x, int y)
{
a=x;
b=y;
}
void disp()
{
System.out.println("\n\n No arguments Passed ");
System.out.println("\n Value of a : " +a);
System.out.println("\n Value of b : " +b);
}
void disp(int m)
{
System.out.println("\n\n Arument Passed : " +m);
System.out.println("\n Value of a : " +a);
System.out.println("\n Value of b : " +b);
}
}

class P1a
{
public static void main(String args[])
{
Cons c1=new Cons();
Cons c2=new Cons(5);
Cons c3=new Cons(10,20);
c1.disp();
c2.disp(4);
c3.disp();
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

No arguments Passed

Value of a : 1

Value of b : 1

Arument Passed : 4

Value of a : 5

Value of b : 5

No arguments Passed

Value of a : 10

Value of b : 20

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

1b. JAVA Program to implement Inner class and demonstrate its Access Protections.

class Outer
{
int outer_x=100;
void test()
{
Inner i1=new Inner();
i1.display();
}
int y=10;
class Inner
{
// int y=5;
void display()
{
System.out.println("Display : outer_x = " +outer_x);
}
}
void showy()
{
System.out.println("Value of Y : " +y);
}
}

class P1b
{
public static void main(String args[])
{
Outer o=new Outer();
o.test();
}
}

OUTPUT:

Display : outer_x = 100

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

2a. JAVA Program to implement Inheritance.

class Sup
{
int i,j;
Sup(int a,int b)
{
i=a;
j=b;
}
void displayij()
{
System.out.println("\n Value of i : " +i);
System.out.println("\n Value of j : " +j);
}
}

class Sub extends Sup


{
int k;
Sub(int a,int b,int c)
{
super(a,b);
k=c;
}
void displayk()
{
System.out.println("\n Value of k : " +k);
}
void sum()
{
System.out.println("\n Sum of i,j and k : " +(i+j+k));
}
}

class P2a
{
public static void main(String args[])
{
Sub sbob=new Sub(10,20,30);
Sup spob=new Sup(15,25);
System.out.println("\n Contents of Super Class Object : ");
spob.displayij();
System.out.println("\n Contents of Sub Class Object : ");
sbob.displayij();
sbob.displayk();
System.out.println("\n After adding Sub Class Object : " );
sbob.sum();
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Contents of Super Class Object :

Value of i : 15

Value of j : 25

Contents of Sub Class Object :

Value of i : 10

Value of j : 20

Value of k : 30

After adding Sub Class Object :

Sum of i,j and k : 60

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

2b. JAVA Program to implement Exception Handling.

class P2b
{
public static void main(String args[])
{
try
{
int a=args.length;
int b=10/a;
System.out.println("Length : " +a);
try
{
if(a==1)
a=a/(a-a);
if(a==2)
{
int c[]={1};
c[2]=10;
}
try
{
int s;
if(a>2)
s=30/a;
}
finally
{
System.out.println("No Exception");
System.out.println(a+ " Command-line Arguments ");
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out-of-Bound : " +e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0 : " +e);
}
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

C:\jdk1.3\>javac P2b.java

C:\jdk1.3\>java P2b
Divide by 0 : java.lang.ArithmeticException: / by zero

C:\jdk1.3\>java P2b a
Length : 1
Divide by 0 : java.lang.ArithmeticException: / by zero

C:\jdk1.3\>java P2b a b
Length : 2
Array Index Out-of-Bound : java.lang.ArrayIndexOutOfBoundsException

C:\jdk1.3\>java P2b a b c
Length : 3
No Exception
3 Command-line Arguments

C:\jdk1.3\>java P2b a b c d
Length : 4
No Exception
4 Command-line Arguments

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

3a. JAVA Program to create an Interface and implement it in a class.

interface Interf
{
void comput(int x, int y);
}

class Add implements Interf


{
public void comput(int x, int y)
{
System.out.println("Sum : " +(x+y));
}
}

class Mul implements Interf


{
public void comput(int x, int y)
{
System.out.println("Product : " +(x*y));
}
}

class P3a
{
public static void main(String args[])
{
Add a_obj=new Add();
Mul m_obj=new Mul();
Interf i;
i=a_obj;
i.comput(10,20);
i=m_obj;
i.comput(4,5);
}
}

OUTPUT:

Sum : 30
Product : 20
Press any key to continue . . .

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

3b. JAVA Program to create a class (extending Thread) and use methods Thread class to
change name, priority of the current Thread and display the same.

class Five extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("5 X " +i+ " = " +5*i);
if(i==5)
yield();
}
System.out.println("Out of class 5 ");
}
}

class Seven extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("7 X " +i+ " = " +7*i);
if(i==3)
stop();
}
System.out.println("Out of class 7");
}
}

class Nine extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("9 X " +i+ " = " +9*i);
try
{
sleep(1000);
}
catch(Exception e) { }
}
System.out.println("Out of class 9");
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

class P3b
{
public static void main(String args[])
{
Five f=new Five();
Seven s=new Seven();
Nine n=new Nine();
n.setName("My");
n.setPriority(10);
System.out.println("Thread " +n.getName()+ " has a priority of " +n.getPriority());
f.setPriority(1);
f.start();
s.start();
n.start();
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Thread My has a priority of 10


7X1=7
9X1=9
7 X 2 = 14
5X1=5
7 X 3 = 21
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Out of class 5
9 X 2 = 18
9 X 3 = 27
9 X 4 = 36
9 X 5 = 45
9 X 6 = 54
9 X 7 = 63
9 X 8 = 72
9 X 9 = 81
9 X 10 = 90
Out of class 9

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

4a. JAVA Program to create a Scrolling Text using JAVA Applets.

import java.awt.*;
import java.applet.*;

/*
<applet code="P4a" width=400 height=200>
<param name=message value="BMS COLLEGE OF ENGINEERING">
</applet>
*/

public class P4a extends Applet implements Runnable


{
String msg;
Thread t=null;
int state;
boolean stopFlag;

public void init()


{
setBackground(Color.cyan);
setForeground(Color.blue);
}

public void start()


{
msg=getParameter("message");
if(msg==null)
msg="Message not found";
msg=" "+msg;
t=new Thread(this);
stopFlag=false;
t.start();
}

public void run()


{
char ch;
for( ; ; )
{
try
{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
if(stopFlag)
break;
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

catch(InterruptedException e) { }
}
}

public void stop()


{
stopFlag=true;
t=null;
}

public void paint(Graphics g)


{
g.drawString(msg,100,100);
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

4b. JAVA Program to pass parameters to Applets and display the same.

import java.awt.*;
import java.applet.*;

/*
<applet code="P4b" width=400 height=200>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/

public class P4b extends Applet


{
String fontName;
int fontSize;
float leading;
boolean active;

public void start()


{
String param;
fontName=getParameter("fontName");
if(fontName==null)
fontName="Not Found";
param=getParameter("fontSize");
try
{
if(param!=null)
fontSize=Integer.parseInt(param);
else
fontSize=0;
}
catch(NumberFormatException e)
{
fontSize=-1;
}
param=getParameter("leading");
try
{
if(param!=null)
leading=Float.valueOf(param).floatValue();
else
leading=0;
}
catch(NumberFormatException e)
{
leading=0;
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

param=getParameter("accountEnabled");
if(param!=null)
active=Boolean.valueOf(param).booleanValue();
}
public void paint(Graphics g)
{
g.drawString("Font Name : " +fontName,100,40);
g.drawString("Font Size : " +fontSize,100,80);
g.drawString("Leading : " +leading,100,120);
g.drawString("Account Active : " +active,100,160);
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

5. Write a JAVA Program to insert data into Student DATA BASE and retrieve info base
on particular queries (Using JDBC Design Front end using Swings).

lab5.java

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

class Inpscr extends JFrame implements ActionListener


{
private Toolkit toolkit;

JLabel head = new JLabel("STUDENT DETAIL ");


JLabel label1 = new JLabel("Student id ");
JLabel label2 = new JLabel("Name ");
JLabel label3 = new JLabel("Address ");
JLabel label4 = new JLabel("Dob ");
JLabel label5 = new JLabel("Sex ");
JLabel label6 = new JLabel("Phone no ");

JTextField text1 = new JTextField();


JTextField text2 = new JTextField();
JTextField text3 = new JTextField();
JTextField text4 = new JTextField();
JTextField text5 = new JTextField();
JTextField text6 = new JTextField();

JButton next = new JButton("NEXT");


JButton close = new JButton("CLOSE");
JButton save = new JButton("SAVE");
JButton reset = new JButton("RESET");
JButton ok = new JButton("OK");
JButton del = new JButton("Delete");
JButton updat = new JButton("Update");
JButton click = new JButton("Click");
JPanel panel = new JPanel();

//static String userid="system", password = "jitu";


static String url = "jdbc:odbc:Girish";
static Connection con = null;
static Statement smnt,smnt1;
static ResultSet rs,rs1;
String id,sid,nam,ad,se,ph,db;

Inpscr()
{
setTitle("Data Base Connectivity");
setSize(300, 300);
toolkit = getToolkit();
Dimension size = toolkit.getScreenSize();

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

setLocation((size.width - getWidth())/2, (size.height - getHeight())/2);


setDefaultCloseOperation(EXIT_ON_CLOSE);

getContentPane().add(panel);
panel.setLayout(null);

head.setBounds(100, 5, 150, 20);


label1.setBounds(20, 40, 80, 20);
text1.setBounds(100, 40, 80, 20);
panel.add(head);
panel.add(label1);
panel.add(text1);
panel.add(close);
close.addActionListener(this);
}

public void setfields()


{
label2.setBounds(20, 70, 80, 20);
text2.setBounds(100, 70, 80, 20);
label3.setBounds(20, 100, 80, 20);
text3.setBounds(100, 100, 80, 20);
label4.setBounds(20, 130, 80, 20);
text4.setBounds(100, 130, 80, 20);
label5.setBounds(20, 160, 80, 20);
text5.setBounds(100, 160, 80, 20);
label6.setBounds(20, 190, 80, 20);
text6.setBounds(100, 190, 80, 20);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel.add(label5);
panel.add(label6);
panel.add(text2);
panel.add(text3);
panel.add(text4);
panel.add(text5);
panel.add(text6);
}
public boolean showspec()
{
String s;
try {
s=text1.getText();
String creat="select * from emp1" +" " + "where s_id="+s;
smnt=con.createStatement();
rs = smnt.executeQuery(creat);
if(rs.next())
{
setfields();
showRecord(rs);
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

else
{
JOptionPane.showMessageDialog(null,"Record Not Found");
return false;
}
}
catch(Exception ee)
{
System.out.println("Error" +ee);}
return true;
}
}
public void Display()
{
try {
String creat="select * from emp1";
smnt=con.createStatement();
rs = smnt.executeQuery(creat);
rs.next();
}
catch(Exception ee)
{System.out.println("Error" +ee);}
showRecord(rs) ;
}
public void showRecord(ResultSet rs)
{
String str;
try {
//text1.setText(Integer.toString(rs.getInt(1)));
text1.setText(rs.getString(1));
text2.setText(rs.getString(2));
text3.setText(rs.getString(3));
str=rs.getString(4);
text4.setText(str.substring(0,10));
text5.setText(rs.getString(5));
text6.setText(rs.getString(6));
text1.setEditable(false);
text2.setEditable(false);
text3.setEditable(false);
text4.setEditable(false);
text5.setEditable(false);
text6.setEditable(false);
}
catch(Exception ee) {}
}
public void setcomp()
{
next.setBounds(60, 240, 80, 20);
close.setBounds(150, 240, 80, 20);
panel.add(next);
next.addActionListener(this);
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

public void setcomp1()


{
save.setBounds(10, 240, 80, 20);
reset.setBounds(110, 240, 80, 20);
close.setBounds(200, 240, 80, 20);
panel.add(save);
save.addActionListener(this);
panel.add(reset);
reset.addActionListener(this);
}
public void setcomp2()
{
ok.setBounds(60, 240, 80, 20);
close.setBounds(150, 240, 80, 20);
panel.add(ok);
ok.addActionListener(this);
}
public void setcomp3()
{
del.setBounds(60, 240, 80, 20);
close.setBounds(150, 240, 80, 20);
panel.add(del);
del.addActionListener(this);
}
public void setcomp4()
{
click.setVisible(false);
updat.setBounds(60, 240, 80, 20);
close.setBounds(150, 240, 80, 20);
panel.add(updat);
updat.addActionListener(this);
}
public void setcomp5()
{
click.setBounds(60, 240, 80, 20);
panel.add(click);
click.addActionListener(this);
}
public void actionPerformed(ActionEvent ee)
{
if(ee.getSource() == next) {
try {
rs.next();
showRecord(rs);
}
catch(Exception e) {}
}
if(ee.getSource() == ok) {
try {
showspec();
}
catch(Exception e) {}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

if(ee.getSource() == close) {
try {
setVisible(false);
smnt.close();
con.close();
}
catch(Exception e) {}
}
if(ee.getSource() == save) {
getval();
Setquery();
}
if(ee.getSource() == reset) {
Reset();
}
if(ee.getSource() == del) {
del_rec();
}
if(ee.getSource() == updat) {
getval();
Setupdat();
}
if(ee.getSource() == click) {
updat_rec();
}

}
public void updat_rec()
{
//String sid;
sid=text1.getText();
if(showspec())
{
text1.setEditable(true);
text2.setEditable(true);
text3.setEditable(true);
text4.setEditable(true);
text5.setEditable(true);
text6.setEditable(true);
setcomp4();
getval();
}
/*try {
del = "delete from emp1 where s_id="+id;
smnt1=con.createStatement();
rs1= smnt1.executeQuery(del);
}
catch(Exception ex)
{}*/
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

public void Setupdat()


{
String d;
d=db.substring(5,10)+"-"+db.substring(0,4);
try {
String creat="update emp1 set
s_id='"+id+"',name='"+nam+"',adr='"+ad+"',dob='"+d+"',sex='"+se+"',phone='"+ph+"' where
s_id='"+sid+"'";
smnt=con.createStatement();
rs = smnt.executeQuery(creat);
}
catch(Exception ex)
{System.out.println(ex); }

}
public void del_rec()
{
String del,ser;
id=text1.getText();
try {
del = "delete from emp1 where s_id="+id;
ser = "select * from emp1 where s_id="+id;
smnt1=con.createStatement();
rs1= smnt1.executeQuery(ser);
if((rs1.next()))
{
JOptionPane.showMessageDialog(null,"Record deleted");
smnt=con.createStatement();
rs = smnt.executeQuery(del);
}
else
{
JOptionPane.showMessageDialog(null,"Record Not Found");
}
}
catch(Exception ex) {}
}
public void Reset()
{
text1.setText("");
text2.setText("");
text3.setText("");
text4.setText("");
text5.setText("");
text6.setText("");
}
public void getval()
{
id=text1.getText();
nam=text2.getText();
ad=text3.getText();
db=text4.getText();

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

se=text5.getText();
ph=text6.getText();
System.out.println(nam);
System.out.println(se);
}
public void Setquery()
{
String creat;
try {
creat = "insert into emp1(s_id,name,adr,dob,sex,phone)" + "values(?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(creat);
ps.setString(1, id);
ps.setString(2, nam);
ps.setString(3, ad);
ps.setString(4, db);
ps.setString(5, se);
ps.setString(6, ph);
ps.executeUpdate();
}
catch(Exception ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
public void connect()
{
Connection con = getOracleJDBCConnection();
if(con!= null)
{
System.out.println("Got Connection.");
}
else
{
System.out.println("Could not Get Connection");
}
}
public static Connection getOracleJDBCConnection()
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(java.lang.ClassNotFoundException e) { }
try {
con = DriverManager.getConnection(url);
}
catch(SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
}
return con;
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

class Windowscr extends JFrame implements ActionListener


{
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
JMenu insert = new JMenu("Insert");
JMenu view = new JMenu("View");
JMenu update = new JMenu("Update");
JMenuItem fileclose = new JMenuItem("Close");
JMenuItem insertrec = new JMenuItem("Record");
JMenuItem viewinfo = new JMenuItem("Specific Record");
JMenuItem viewallinfo = new JMenuItem("All record");
JMenuItem delete = new JMenuItem("Delete Record");
JMenuItem modify = new JMenuItem("Modify record");
Windowscr()
{
setTitle("STUDENT DATABASE");
file.setMnemonic(KeyEvent.VK_F);
insert.setMnemonic(KeyEvent.VK_I);
view.setMnemonic(KeyEvent.VK_V);
fileclose.setMnemonic(KeyEvent.VK_C);
insertrec.setMnemonic(KeyEvent.VK_R);
viewinfo.setMnemonic(KeyEvent.VK_S);
viewallinfo.setMnemonic(KeyEvent.VK_A);
update.setMnemonic(KeyEvent.VK_U);
delete.setMnemonic(KeyEvent.VK_D);
modify.setMnemonic(KeyEvent.VK_M);
file.add(fileclose);
insert.add(insertrec);
view.add(viewinfo);
view.add(viewallinfo);
update.add(delete);
update.add(modify);
menu.add(file);
menu.add(insert);
menu.add(view);
menu.add(update);
setJMenuBar(menu);
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
fileclose.addActionListener(this);
insertrec.addActionListener(this);
viewinfo.addActionListener(this);
viewallinfo.addActionListener(this);
delete.addActionListener(this);
modify.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == fileclose) {
System.exit(0);
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

if(e.getSource() == insertrec) {
Inpscr i = new Inpscr();
i.setfields();
i.setcomp1();
i.connect();
i.setVisible(true);
}
if(e.getSource() == viewallinfo) {
Inpscr i1 = new Inpscr();
i1.setfields();
i1.setcomp();
i1.connect();
i1.setVisible(true);
i1.Display();
}
if(e.getSource() == viewinfo) {
Inpscr i2 = new Inpscr();
i2.setcomp2();
i2.connect();
i2.setVisible(true);
}
if(e.getSource() == delete ) {
Inpscr i3 = new Inpscr();
i3.setcomp3();
i3.connect();
i3.setVisible(true);
}
if(e.getSource() == modify) {
Inpscr i4 = new Inpscr();
i4.setcomp5();
i4.connect();
i4.setVisible(true);
}
}

}
public class lab5
{

public static void main(String arg[])


{
{
Windowscr w = new Windowscr();
w.setVisible(true);
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

6. Write a JAVA Program to implement Client Server (Client requests a file,Server


responds to client with contents of that file which is then display on the screen by Client
– Socket Programming).

Client.java

import java.io.*;
import java.net.*;

public class Client


{
public static void main(String args[]) throws IOException
{
Socket cs = new Socket("127.0.0.1",8090);

BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream()));


BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the file name : ");


String fname=stdin.readLine();
byte buf[]=fname.getBytes();

OutputStream out=cs.getOutputStream();
out.write(buf);

String str;
while((str=in.readLine())!=null)
{
System.out.println(str);
}
cs.close();
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

Server.java

import java.io.*;
import java.net.*;

public class Server


{
public static void main(String args[]) throws IOException
{
byte buf[]=new byte[20];

ServerSocket ss = new ServerSocket(8090);


Socket cs = ss.accept();
System.out.println("Server is running........");

InputStream in=cs.getInputStream();
in.read(buf);

String fname = new String(buf);


BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(cs.getOutputStream(),true);

File f = new File(fname);


if(f.exists())
{
BufferedReader fr= new BufferedReader(new FileReader(fname));
String line;

while((line=fr.readLine())!=null)
{
out.println(line);
}
fr.close();
}
ss.close(); cs.close();
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

C:\>javac Server.java

C:\>javac Client.java

C:\>java Server
Server is running........

C:\>java Client
Enter the file name : color.html

<html>
<body>
<center>
<form name="form1" action="http://localhost:8090/servlet/Color">
<B>color:</B>
<input type=text name="color" />
<br><br>
<input type=submit value="submit">
</form>
</body>
</html>

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

7. Write a JAVA Program to implement a simple Client Server Application using RMI.

AddServerIntf.java

import java.rmi.*;
public interface AddServerIntf extends Remote
{
double add(double d1 , double d2) throws RemoteException ;
}

AddServerImpl.java

import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf
{
public AddServerImpl() throws RemoteException { }
public double add(double d1, double d2) throws RemoteException
{
return d1 + d2;
}
}

AddClient.java

import java.rmi.*;
public class AddClient
{
public static void main(String args[] )
{
try {
String serverURL = "rmi://" + args[0] + "/AddServer";
AddServerIntf addServerIntf=(AddServerIntf)Naming.lookup(serverURL);

System.out.println("First no. x : " +args[1]);


double d1 = Double.valueOf(args[1]).doubleValue();

System.out.println("Second no. y : " +args[2]);


double d2 = Double.valueOf(args[2]).doubleValue();

System.out.println("Result of d1 + d2 : " + addServerIntf.add(d1 , d2));


}
catch(Exception e)
{
System.out.println("ERROR ! " + e);
}
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

AddServer.java

import java.net.*;
import java.rmi.*;

public class AddServer


{
public static void main(String args[])
{
try
{
AddServerImpl addServerImpl = new AddServerImpl();
Naming.rebind("AddServer" , addServerImpl);
}
catch(Exception e)
{
System.out.println("ERROR ! " + e);
}
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

C:\>javac AddServerIntf.java

C:\>javac AddServerImpl.java

C:\>javac AddServer.java

C:\>javac AddClient.java

C:\>rmic AddServerImpl

C:\>start rmiregistry

C:\>java AddServer

C:\>java AddClient 127.0.0.1 5 6

First no. x : 5

Second no. y : 6

Result of d1 + d2 : 11.0

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

8. Write a JAVA Servlet Program to implement a dynamic HTML using Servlet (user
name and password should be accepted using HTML and displayed using a Servlet).

Lab8.html

<html>
<head>
<title>Lab8</title>
</head>
<body>
<h2> User details</h2>
<form method="post" action="http://localhost:8090/servlet/lab8" >
<hr />
<h3> Enter user name::</h3>
<input type="text" name="uname" /><br /><br />
<h3>Enter Password::</h3>
<input type="password" name="uadd" /><br /><br />
<input type="submit" value="Display" />
<input type="reset" value="Clear" />
</form>
</body>
</html>

lab8.java

import java.lang.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class lab8 extends HttpServlet


{
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
PrintWriter out=res.getWriter();
String unam=req.getParameter("uname");
String uaa=req.getParameter("uadd");
out.println("<HTML><BODY>");
out.println("<h1> USER INFORMATION</h1><hr />");
out.println("User name:: "+unam+"<br>");
out.println("Password:: "+uaa+"<br>");
out.println("</BODY></HTML>");
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Procedure to Excecute:
1. Compile lab8.java
2. Copy lab8.class file to C:\JSDK2.0\examples\
3. Run servletrunner with –p option and 8090 port number
4. Open lab8.html file
5. Enter user name and password and click Display

C:\>javac lab8.java

C:\>servletrunner -p 8090
servletrunner starting with settings:
port = 8090
backlog = 50
max handlers = 100
timeout = 5000
servlet dir = .\examples
document dir = .\examples
servlet propfile = .\examples\servlet.properties

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

C:\>servletrunner -p 8090
servletrunner starting with settings:
port = 8090
backlog = 50
max handlers = 100
timeout = 5000
servlet dir = .\examples
document dir = .\examples
servlet propfile = .\examples\servlet.properties
lab8: init

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

9. Write a JAVA Servlet Program to Download a file and display it on the screen (A link
has to be provided in HTML, when the link is clicked corresponding file has to be
displayed on Screen).

Download.html

<html>
<body bgcolor="ff99ff">
<center><br />
<form action="down">
<h2>FILE DOWNING </h2>
<h6>( Image and C source code )</h6>
<hr><br />
Image
<input type=hidden value="Ganesha.jpg" name="id">
<input type="submit" value="Download" /><br /><br />
</form>
<form action="down">
C Code for BFS search
<input type=hidden value="bfs.txt" name="id">
<input type="submit" value="Download" />
</form>
</center>
</body>
</html>

web.xml

<web-app>
<servlet>
<servlet-name>down</servlet-name>
<servlet-class>DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>down</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
</web-app>

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

DownloadServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DownloadServlet extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException,ServletException
{
String fileName=req.getParameter("id");
String path=null;
if(fileName.equals("Ganesha.jpg"))
path="C:\\Ganesha.jpg";
else if(fileName.equals("bfs.txt"))
path="C:\\bfs.txt";
res.setContentType("application/octet-stream");
res.setHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
OutputStream oStream = res.getOutputStream();
FileInputStream file=new FileInputStream(path);
int i=0;
while((i=file.read())!=-1){
oStream.write(i);}
file.close();
oStream.close();
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

10a. Write a JAVA Servlet Program to implement RequestDispatcher object (use include()
and forward() methods).

web.xml

<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

login.jsp

<html>
<head><title>Login Page</title></head>
<body bgcolor="#aabbcc">
<center>
<h1>Login Page</h1>
<h2>Welcome to Java</h2>
<br><br><br><br>
<marquee><u>Enter Valid User ID and Password for login</u></marquee>
<h2>
<%
Object o=session.getAttribute("MSG");
if(o!=null)
{
String msg=o.toString();
out.println(msg);
}
%>
</h2>
<form action="login" method="post">
<table border="2">
<tr><td>User ID</td>
<td><input type="text" name="uname"/>
</td>
</tr>
<tr><td>Password</td>
<td><input type="password" name="pword"/>
</td>
</tr>
<tr><td colspan="2" align="center" >
<input type="submit" value="Login"/>
</td>
</tr></table></form></center>
</body>
</html>

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

LoginServlet.jsp

<html><head></head><body>
<%
<%@import java.io.*;%>
<%@import javax.servlet.*;%>
<%@import javax.servlet.http.*;%>
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException,ServletException
{
String un = req.getParameter("uname");
String pw = req.getParameter("pword");
System.out.println("User id =" +un);
System.out.println("Password =" +pw);
RequestDispatcher rd = null;
HttpSession ses= req.getSession();
if(un.equals("java") && pw.equals("lab10a"))
{
ses.setAttribute("UN",un);
rd = req.getRequestDispatcher("/lab10a/register.jsp");
rd.forward(req,res);
}
else
{
String msg ="in valid user id and password";
ses.setAttribute("MSG",msg);
rd = req.getRequestDispatcher("/lab10a/login.jsp");
rd.include(req,res);
}
}
}
%>
</body>
</html>

register.jsp

<html>
<head><title>Login Page</title></head>
<body bgcolor="#aabbcc">
<center>
<h1>Login Page</h1>
<h2>Welcome to Java</h2>
<br><br><br><br>
<marquee><u>THIS IS doPost() METHOD EXAMPLE</u></marquee>
<br><br>

<h2>
<font color="red">

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

<%
Object o=session.getAttribute("UN");
if(o!=null)
{
String un=o.toString();
//out.println(un);
}
%>

<h1>WELCOME TO MY PROJECT--------</h1>
<br><br><br>
</font>
</h2>
</center>
</body>
</html>

LoginServlet.java

//package com;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException,ServletException
{
String un = req.getParameter("uname");
String pw = req.getParameter("pword");
System.out.println("user id is=" +un);
System.out.println("user password is =" +pw);
RequestDispatcher rd = null;
HttpSession ses= req.getSession();
if(un.equals("java")&& pw.equals("lab10a"))
{
ses.setAttribute("UN",un);
rd = req.getRequestDispatcher("/register.jsp");
rd.forward(req,res);
}
else
{
String msg ="Invalid user id and password";
ses.setAttribute("MSG",msg);
rd = req.getRequestDispatcher("/login.jsp");
rd.include(req,res);
}
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

10b. Write a JAVA Servlet Program to implement and demonstrate Get() and Post()
methods(Using HTTP Servlet Class).

web.xml

<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

login.jsp

<html>
<head>
</head>
<body bgcolor="#aabbcc">
<center>
<H1>Login Page</H1>
<H2><u>Welcome to Java</u></H2>
<br><br><br><br>
<marquee>This site is hundred persent safe</marquee>
<h2>
<font color="red">
<%
Object o = session.getAttribute("MSG");
if(o!=null)
{
String msg= o.toString();
out.println(msg);
}
%>
</font>
</h2>
<form action ="login" method="get">
<table border="2" >
<tr><td>User name</td>
<td><input type="text" name="uname"/>
</tr>
<tr><td>Password</td>
<td><input type="password" name="pword"/>
</tr>
<tr><td colspan="2" align="center">
<input type="submit" value="Login"/>
</td></tr></table>
</form></center>
</body></html>

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

register.jsp

<html>
<head>
</head>
<body bgcolor="#aabbcc">
<center>
<H1>Login Page</H1>
<hr><br><br><br><br>
<h2><marquee><u>WELCOME</u></marquee></h2>
<br><br><br>
<h2>
<font color="red">
<%
Object o = session.getAttribute("UN");
if(o!=null)
{
String un= o.toString();
//out.println(un);
}
%>
Your are an Authorized User.............
<br>
<br>
<br>
<br>
</font>
</h2>
</form>
<br>
<br>
<br>
<br>
<marquee behaviour ="slide" direction="right" width="1000" bgcolor="pink">
<h4>YOU ARE WELCOME TO THIS PAGE</h4>
</marquee>
</center>
</body>
</html>

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

LoginServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
String un = req.getParameter("uname");
String pw = req.getParameter("pword");

System.out.println("User id is====="+un);
System.out.println("Password is====="+pw);

RequestDispatcher rd = null;
HttpSession ses = req.getSession();

if(un.equals("java")&&pw.equals("lab10b"))
{
ses.setAttribute("UN",un);
rd = req.getRequestDispatcher("/register.jsp");
rd.forward(req,res);
}

else
{
String msg="Invalied user id and password";
ses.setAttribute("MSG",msg);
rd=req.getRequestDispatcher("/login.jsp");
rd.forward(req,res);
}
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

11. Write a JAVA Servlet Program to implement sendRedirect() method(using HTTP


Servlet Class).

lab11.html

<html>
<head>
<title>New Page 1</title>
</head>
<body bacgroundColor="cyay">
<center>
<h1>USER NAME AND PASSWORD </h1>
<h6>( Accept and Display the Name and Password )</h6><hr><br />
<form method="POST" action="http://localhost:8090/servlet/SendRedirectServlet">
<p>User Name:<input type="text" name="username" size="20"></p>
<p>Password: <input type="password" name="pasword" size="20"></p>
<input type="submit" value="Submit" name="B1"></p>
</form>
</body>
</html>

SendRedirectServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SendRedirectServlet extends HttpServlet{


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String pasword = request.getParameter("pasword");
if(name.equals("Girish") && pasword.equals("java")){
response.sendRedirect("http://localhost:8090/servlet/ValidUserServlet");
}
else{
pw.println("You are not a Valid User");
}
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

ValidUserServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ValidUserServlet extends HttpServlet{


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("<html><head><title>Home Page</title></head>");
pw.println("<body");
pw.println("<h1><center> HOME PAGE </center></h1><hr><br />");
pw.println("<center>Welcome to the world of servlet <certer><br />");
pw.println("<center>How are you!</center>");
pw.println("</body>");
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

12. Write a JAVA Servlet Program to implement sessions (Using HTTP Session Interface).

ShowSession.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;

public class ShowSession extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Searching the Web";
String heading;
Integer accessCount = new Integer(0);;
if (session.isNew()) {
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
Integer oldAccessCount =
// Use getAttribute, not getValue, in version
// 2.2 of servlet API.
(Integer)session.getValue("accessCount");
if (oldAccessCount != null) {
accessCount =
new Integer(oldAccessCount.intValue() + 1);
}
}
// Use putAttribute in version 2.2 of servlet API.
session.putValue("accessCount", accessCount);

out.println("<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + heading + "</H1><HR>\n" +
"<H2>Information on Your Session:</H2>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Info Type<TH>Value\n" +
"<TR>\n" +
" <TD>ID\n" +
" <TD>" + session.getId() + "\n" +
"<TR>\n" +
" <TD>Creation Time\n" +
" <TD>" + new Date(session.getCreationTime()) + "\n" +
"<TR>\n" +
" <TD>Time of Last Access\n" +
" <TD>" + new Date(session.getLastAccessedTime()) + "\n" +
"<TR>\n" +

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

" <TD>Number of Previous Accesses\n" +


" <TD>" + accessCount + "\n" +
"</TABLE>\n" +
"</BODY></HTML>");

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

13a. Write a JAVA JSP Program to print 10 even and 10 odd number.

OddEven.jsp

<html>
<head>
<title>Odd Even</title>
</head>
<body bgcolor="#DDAAEE">
<center>
<h2><b><u>Ten Odd and Ten Even numbers</u></b></h2>
<table border="1" aling="center" bgcolor="#FFEEAA" cellpadding=6 cellspacing=6>
<th>Odd No.</th><th>Even No.</th>

<%! int i; int d; %>

<%
for(i=1;i<=100;i++)
{
d = i%2;
if(d!=0)
{
%>

<tr align="center">
<td><%= i%></td>

<%
}
else
{
%>
<td><%= i%></td>
</tr>
<%
}
} // End of loop %>
</table>
</center>
</body>
</html>

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

13b. Write a JAVA JSP Program to implement verification of a particular user login and
display a welcome page.

login.jsp

<html>
<head>
<title>Login Page </title>
</head>
<body bgcolor="#aabbcc">
<center>
<H1>Login Page</H1>
<marquee>This page is to check the user Authentication</marquee>

<form action ="registration.jsp" method="post">


<table border="1" >
<tr><td>User name</td>
<td><input type="text" name="uname"/>
</tr>

<tr><td>Password</td>
<td><input type="password" name="pword"/>
</tr>

<tr><td colspan="2" align="center">


<input type="submit" value="Login"/>
</td></tr>
</table>
</form>
</center>
</body>
</html>

registration.jsp

<html>
<head>
<title>Register</title>
</head>
<body>
<center><br>
<h1>Registration success page</h1>

<%
String un = request.getParameter("uname");
String pw=request.getParameter("pword");

if(un.equals("Java")&& pw.equals("lab13b"))
{
out.println("<hr>");
out.println("<h3>"+un+" : Welcome to JSP</h3>");

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

}
else
{
out.println("<hr>");
out.println("You are not Valid user");
}
%>
</center>
</body>
</html>

register.jsp

<html>
<head>
<title>Register</title>
</head>
<body bgcolor="FFEEAA">
<center>
<h1>Registration success page</h1>

<%
String un = request.getParameter("uname");
String pw=request.getParameter("pword");

System.out.println(un);
System.out.println(pw);
%>

<h1>Hi, <%= un%> Your password is <%= pw%></h1>

</center>
</body>
</html>

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

14. Write a JAVA JSP Program to get student information through a HTML and create a
JAVA Bean Class, populate Bean and display the same information through another
JSP.

StudInfo.html

<html>
<head><title> Student Information </title></head>
<body>

<form action ="first.jsp" method = "post">


<center>
<h1>STUDENT INFORMATION</h1>
<h6>( Enter Student Information ) </h6><hr><br />

USN : <input type = "text" name = "usn" /><br />


Name : <input type = "text" name = "sname" /><br />
Marks : <input type = "text" name = "marks" /><br /><br />
<input type ="submit" value ="DISPLAY" />
</center>
</form>
</body>
</html>

first.jsp

<html>
<body>
<jsp:useBean id="stud" scope="request" class="beans.Student"/>
<jsp:setProperty name="stud" property="*"/>
<jsp:forward page="display.jsp"/>
</body>
</html>

display.jsp

<html>
<body>
<center>
<h1>STUDENT INFORMATION </h1>
<h6>( Accepted Information ) </h6><hr><br>
<jsp:useBean id="stud" scope="request" class="beans.Student"/>
Name : <jsp:getProperty name="stud" property="sname"/><br>
USN : <jsp:getProperty name="stud" property="usn"/><br>
Marks : <%out.print(stud.getmarks());%>
</center>
</body>
</html>

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

Student.java

package beans;
public class Student
{
public String sname;
public int usn;
public double marks;

public void setsname(String s)


{sname = s;}
public String getsname()
{return sname;}

public void setusn(int sn)


{usn=sn;}
public int getusn()
{return usn;}

public void setmarks(double smar)


{marks = smar;}
public double getmarks()
{return marks;}
}

Department of MCA BMS College of Engineering


07MCA46: Java and J2EE Laboratory

OUTPUT:

Department of MCA BMS College of Engineering

You might also like