You are on page 1of 30

JAVA/J2EE LAB

Department of MCA

PROGRAM 1 (a) Write a java program to demonstrate constructor overloading and method
overloading: // Demonstrate constructor overloading class Box { double width; double height; double depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } class OverloadCons { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } } Output: C:\Java\jdk1.5\bin>javac OverloadCons.java C:\Java\jdk1.5\bin>java OverloadCons Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0 // Demonstrate method overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); Page No1

JAVA/J2EE LAB } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; }

Department of MCA

} class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } Output: C:\Java\jdk1.5\bin>javac Overload.java C:\Java\jdk1.5\bin>java Overload No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625 *********************************************************************************** ********************

OR
//Another program for constructor and method overloading public class ConstructorOverloading{ public static void main(String args[]){ Rectangle rectangle1=new Rectangle(2,4); int areaInFirstConstructor=rectangle1.first(); System.out.println(" The area of a rectangle in first constructor is : areeaInFirstConstructor); Rectangle rectangle2=new Rectangle(5); int areaInSecondConstructor=rectangle2.second(); System.out.println(" The area of a rectangle infirst constructor is : areaInSecondConstructor); Rectangle rectangle3=new Rectangle(2.0f); float areaInThirdConstructor=rectangle3.third(); System.out.println(" The area of a rectangle in first constructor is : areaInThirdConstructor); Rectangle rectangle4=new Rectangle(3.0f,2.0f); float areaInFourthConstructor=rectangle4.fourth(); System.out.println(" The area of a rectangle in first constructor is : areaInFourthConstructor); } } class Rectangle{ int l, b; float p, q; public Rectangle(int x, int y){ l = x; b = y; }

"+

"+

"+

"+

Page No2

JAVA/J2EE LAB public int first(){ return(l * b); } public Rectangle(int x){ l = x; b = x; } public int second(){ return(l * b); } public Rectangle(float x){ p = x; q = x; } public float third(){ return(p * q); } public Rectangle(float x, float y){ p = x; q = y; } public float fourth(){ return(p * q); } } class OverloadingMethod { double method(int i) { return i; } boolean method(boolean b) { return !b; } static double method(int x, double y) { return x + y + 1; } static double method(double x, double y) { return x + y + 3; } public static void main(String[] args) { System.out.println(method(10, 20)); System.out.println(method(10, 20.0)); System.out.println(method(10.0, 20)); System.out.println(method(10.0, 20.0)); } } Output: C:\Java\jdk1.5\bin>java ConstructorOverloading The area of a rectangle in first constructor is : 8 The area of a rectangle infirst constructor is : 25 The area of a rectangle in first constructor is : 4.0 The area of a rectangle in first constructor is : 6.0

Department of MCA

(b) Write a JAVA Program to implement Inner class and demonstrate its Access Protections. In the following program, we will create an array, fill it with integer values and then output only values of even indices of the array in ascending order. The DataStructure class below consists of: * The DataStructure outer class, which includes methods to add an integer onto the array and print out values of even indices of the array. Page No3

JAVA/J2EE LAB

Department of MCA

* The InnerEvenIterator inner class, which is similar to a standard Java iterator. Iterators are used to step through a data structure and typically have methods to test for the last element, retrieve the current element, and move to the next element. *A main method that instantiates a DataStructure object (ds) and uses it to fill the arrayOfInts array with integer values (0, 1, 2, 3, etc.), then calls a printEven method to print out values of even indices of arrayOfInts. *********************************************************************************** *********************** public class DataStructure { //create an array private final static int SIZE = 15; private int[] arrayOfInts = new int[SIZE]; public DataStructure() { //fill the array with ascending integer values for (int i = 0; i < SIZE; i++) { arrayOfInts[i] = i; } } public void printEven() { //print out values of even indices of the array InnerEvenIterator iterator = this.new InnerEvenIterator(); while (iterator.hasNext()) { System.out.println(iterator.getNext() + " "); } } //inner class implements the Iterator pattern private class InnerEvenIterator { //start stepping through the array from the beginning private int next = 0; public boolean hasNext() { //check if a current element is the last in the array return (next <= SIZE - 1); } public int getNext() { //record a value of an even index of the array int retValue = arrayOfInts[next]; //get the next even element next += 2; return retValue; }

} public static void main(String s[]) { //fill the array with integer values and print out only values of even indices DataStructure ds = new DataStructure(); ds.printEven(); } } Output: C:\Java\jdk1.5\bin>javac DataStructure.java C:\Java\jdk1.5\bin>java DataStructure 0 2 4 6 8 10 12 Page No4

JAVA/J2EE LAB 14

Department of MCA

PROGRAM 2 (a) Write a java program to implement inheritance ******************************************************************************* ************** class Cleanser { private String s = new String("Cleanser"); public void append(String a) { s += a; } public void dilute() { append(" dilute()"); } public void apply() { append(" apply()"); } public void scrub() { append(" scrub()"); } public String toString() { return s; } public static void main(String[] args) { Cleanser x = new Cleanser(); x.dilute(); x.apply(); x.scrub(); System.out.println(x); } } public class Detergent extends Cleanser { // Change a method: public void scrub() { append(" Detergent.scrub()"); super.scrub(); // Call base-class version } // Add methods to the interface: public void foam() { append(" foam()"); } // Test the new class: public static void main(String[] args) { Detergent x = new Detergent(); x.dilute(); x.apply(); x.scrub(); x.foam(); System.out.println(x); System.out.println("Testing base class:"); Cleanser.main(args); } } Output: C:\Java\jdk1.5\bin>javac Detergent.java C:\Java\jdk1.5\bin>java Detergent Cleanser dilute() apply() Detergent.scrub() scrub() foam() Testing base class: Cleanser dilute() apply() scrub() (b) Write a java program to implement Exception Handling (using Nested try catch and finally). Page No5

JAVA/J2EE LAB

Department of MCA

*********************************************************************************** **************** class FinallyDemo { // Through an exception out of the method. static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } } // Return from within a try block. static void procB() { try { System.out.println("inside procB"); return; } finally { System.out.println("procB's finally"); } } // Execute a try block normally. static void procC() { try { System.out.println("inside procC"); } finally { System.out.println("procC's finally"); } } public static void main(String args[]) { try { procA(); } catch (Exception e) { System.out.println("Exception caught"); } procB(); procC(); } } Output: C:\Java\jdk1.5\bin>javac FinallyDemo.java C:\Java\jdk1.5\bin>java FinallyDemo inside procA Proc A's finally Exception caught inside procB procB's finally Inside procC procC's finally PROGRAM 3: (a) Write a java program to create an interface and implement it in class *********************************************************************************** ********************** * import java.lang.*; interface Area{ final static float pi=3.14F; float compute(float x, float y); } class Rectangle implements Area{ public float compute(float x, float y){ return(x*y); Page No6

JAVA/J2EE LAB

Department of MCA

} } class Circle implements Area{ public float compute(float x, float y){ return(pi*x*y); } } class InterfaceTest{ public static void main(String args[]) { Rectangle rect=new Rectangle(); Circle cir=new Circle(); Area area; area=rect; try{ System.out.println("Area of Rectangle = " +area.compute(10,20)); area=cir; System.out.println("Area of Circle = " +area.compute(10,0)); }catch(Exception e){} } } Output: C:\Java\jdk1.5\bin>javac InterfaceTest.java C:\Java\jdk1.5\bin>java InterfaceTest Area of Rectangle = 200.0 Area of Circle = 0.0 *********************************************************************************** *********************** OR interface Callback { void callback(int param); } class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } class AnotherClient implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("Another version of callback"); System.out.println("p squared is " + (p*p)); } } class TestIface { public static void main(String args[]) { Callback c = new Client(); AnotherClient ob = new AnotherClient(); c.callback(42); c = ob; // c now refers to AnotherClient object c.callback(42); } } Output: C:\Java\jdk1.5\bin>javac TestIface.java C:\Java\jdk1.5\bin>java TestIface callback called with 42 Another version of callback p squared is 1764 *********************************************************************************** *********************** OR Page No7

JAVA/J2EE LAB Interface Act{ void act(); } class Actor1 implements Act{ public void act(){ System.out.println("Tobe,ornottobe"); } } class Actor2 implements Act{ public void act(){ System.out.println("WhereforeartthouRomeo?"); } } class TryOut{ public static void main(String args[]){ Actor1 hamlet=new Actor1(); Actor2 juliet=new Actor2(); tryout(hamlet); tryout(juliet); } private static void tryout(Act actor){ actor.act(); } } Output: C:\Java\jdk1.5\bin>javac TryOut.java C:\Java\jdk1.5\bin>java TryOut Tobe,ornottobe WhereforeartthouRomeo?

Department of MCA

(b) Write a 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. *********************************************************************************** *********************** public class SetPriority extends Thread { private static Runnable makeRunnable() { Runnable r = new Runnable() { public void run() { for (int i = 0; i < 5; i++) { Thread t = Thread.currentThread(); System.out.println("in run() - priority=" + t.getPriority() + ", name=" + t.getName()); try { Thread.sleep(2000); } catch (InterruptedException x) { } } } }; return r; } public static void main(String[] args) { Thread threadA = new Thread(makeRunnable(), "threadA"); threadA.setPriority(8); //threadA.setName("My threadA"); threadA.start(); Thread threadB = new Thread(makeRunnable(), "threadB"); threadB.setPriority(2); //threadB.setName("My threadB"); Page No8

JAVA/J2EE LAB threadB.start();

Department of MCA

Runnable r = new Runnable() { public void run() { Thread threadC = new Thread(makeRunnable(), "threadC"); // threadC.setName("My threadC"); threadC.start(); } }; Thread threadD = new Thread(r, "threadD"); threadD.setPriority(7); //threadD.setName("My threadD"); threadD.start(); try { Thread.sleep(3000); threadA.setName("My threadA"); threadB.setName("My threadB"); // threadC.setName("My threadC"); threadD.setName("My threadD"); } catch (InterruptedException x) { } threadA.setPriority(3); System.out.println("in main() - threadA.getPriority()=" + threadA.getPriority()); } } Output: C:\Java\jdk1.5\bin>javac SetPriority.java C:\Java\jdk1.5\bin>java SetPriority in run() - priority=8, name=threadA in run() - priority=7, name=threadC in run() - priority=2, name=threadB in run() - priority=8, name=threadA in run() - priority=7, name=threadC in run() - priority=2, name=threadB in main() - threadA.getPriority()=3 in run() - priority=3, name=My threadA in run() - priority=7, name=threadC in run() - priority=2, name=My threadB in run() - priority=3, name=My threadA in run() - priority=7, name=threadC in run() - priority=2, name=My threadB in run() - priority=3, name=My threadA in run() - priority=7, name=threadC in run() - priority=2, name=My threadB PROGRAM 4 (a) : Create an Applet to Scroll a Text Message. *********************************************************************************** *********************** Code to create an applet to scroll a text message. /* <applet code=AppletBanner width=300 height=200> </applet> */ import java.awt.*; import java.applet.*; public class AppletBanner extends Applet implements Runnable { String str; int x,y; Page No9

JAVA/J2EE LAB public void init() { str="WELCOME TO RNSIT"; x=300; new Thread(this).start(); } public void run() { try{ while(true){ x=x-10; if(x < 0 ){ x=300; } repaint(); System.out.println(x); Thread.sleep(1000); } } catch(Exception e){} } public void paint(Graphics g) { for(int i=0;i<10;i++) g.drawString(str,x,100); } } Output :
E:\j2sdk1.4.0\bin>javac AppletBanner.java E:\j2sdk1.4.0\bin>appletviewer AppletBanner.java 290 280 270 260 250 240 230 220 210 200 190 180 170 160 150 140 130 120 110 100 90 80 70 60 50 40 E:\j2sdk1.4.0\bin>

Department of MCA

Page No10

JAVA/J2EE LAB

Department of MCA

Two instances of the applet : one at the value x = 210 and second at x = 50 (b) Write a java program to pass parameters to applets and display the same. ******************************************************************************* ************** import java.awt.*; import java.applet.*; /* <applet code="ParamDemo" width=300 height=80> <param name=fontName value=Courier> <param name=fontSize value=14> <param name=leading value=2> <param name=accountEnabled value=true> </applet> */ public class ParamDemo extends Applet{ String fontName; int fontSize; float leading; boolean active; // Initialize the string to be displayed. public void start() { String param; fontName = getParameter("fontName"); if(fontName == null) fontName = "Not Found"; param = getParameter("fontSize"); try { if(param != null) // if not found fontSize = Integer.parseInt(param); else fontSize = 0; } catch(NumberFormatException e) { fontSize = -1; } param = getParameter("leading"); try { if(param != null) // if not found leading = Float.valueOf(param).floatValue(); else leading = 0; } catch(NumberFormatException e) { leading = -1; } param = getParameter("accountEnabled"); Page No11

JAVA/J2EE LAB if(param != null) active = Boolean.valueOf(param).booleanValue(); } // Display parameters. public void paint(Graphics g) { g.drawString("Font name: " + fontName, 0, 10); g.drawString("Font size: " + fontSize, 0, 26); g.drawString("Leading: " + leading, 0, 42); g.drawString("Account Active: " + active,0,58); }

Department of MCA

} Output:

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). *********************************************************************************** ********************** // this programs was done using netbeans import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; import import import import import import import javax.swing.JButton; javax.swing.JFrame; javax.swing.JList; javax.swing.JPanel; javax.swing.JScrollPane; javax.swing.JTextArea; javax.swing.JTextField;

public class RSAccounts extends JFrame { private JButton getAccountButton, insertAccountButton, deleteAccountButton, updateAccountButton, nextButton, previousButton, lastButton, firstButton, gotoButton, freeQueryButton; private JList accountNumberList; private JTextField accountIDText, usernameText, passwordText, tsText, activeTSText, gotoText, freeQueryText; Page No12

JAVA/J2EE LAB private JTextArea errorText; private Connection connection; private Statement statement; private ResultSet rs; public RSAccounts() { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception e) { System.err.println("Unable to find and load driver"); System.exit(1); } } private void loadAccounts() { Vector v = new Vector(); try { rs = statement.executeQuery("SELECT * FROM acc_acc"); while (rs.next()) { v.addElement(rs.getString("acc_id")); } } catch (SQLException e) { displaySQLErrors(e); } accountNumberList.setListData(v); } private void buildGUI() { Container c = getContentPane(); c.setLayout(new FlowLayout());

Department of MCA

accountNumberList = new JList(); loadAccounts(); accountNumberList.setVisibleRowCount(2); JScrollPane accountNumberListScrollPane = new JScrollPane( accountNumberList); gotoText = new JTextField(10); freeQueryText = new JTextField(40); //Do Get Account Button getAccountButton = new JButton("Get Account"); getAccountButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { rs.first(); while (rs.next()) { if (rs.getString("acc_id").equals( accountNumberList.getSelectedValue())) break; } if (!rs.isAfterLast()) { accountIDText.setText(rs.getString("acc_id")); usernameText.setText(rs.getString("username")); passwordText.setText(rs.getString("password")); tsText.setText(rs.getString("ts")); activeTSText.setText(rs.getString("act_ts")); } Page No13

JAVA/J2EE LAB } catch (SQLException selectException) { displaySQLErrors(selectException); } } });

Department of MCA

//Do Insert Account Button insertAccountButton = new JButton("Insert Account"); insertAccountButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Statement statement = connection.createStatement(); int i = statement .executeUpdate("INSERT INTO acc_acc VALUES(" + accountIDText.getText() + ", " + "'" + usernameText.getText() + "', " + "'" + passwordText.getText() + "', " + "0" + ", " + "now())"); errorText.append("Inserted " + i + " rows successfully"); accountNumberList.removeAll(); loadAccounts(); } catch (SQLException insertException) { displaySQLErrors(insertException); } } }); //Do Delete Account Button deleteAccountButton = new JButton("Delete Account"); deleteAccountButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Statement statement = connection.createStatement(); int i = statement .executeUpdate("DELETE FROM acc_acc WHERE acc_id = " + accountNumberList.getSelectedValue()); errorText.append("Deleted " + i + " rows successfully"); accountNumberList.removeAll(); loadAccounts(); } catch (SQLException insertException) { displaySQLErrors(insertException); } } }); //Do Update Account Button updateAccountButton = new JButton("Update Account"); updateAccountButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Statement statement = connection.createStatement(); int i = statement.executeUpdate("UPDATE acc_acc " + "SET username='" + usernameText.getText() + "', " + "password='" + passwordText.getText() + "', " + "act_ts = now() " + "WHERE acc_id = " + accountNumberList.getSelectedValue()); errorText.append("Updated " + i + " rows successfully"); accountNumberList.removeAll(); loadAccounts(); } catch (SQLException insertException) { displaySQLErrors(insertException); } Page No14

JAVA/J2EE LAB } }); //Do Next Button nextButton = new JButton(">"); nextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (!rs.isLast()) { rs.next(); accountIDText.setText(rs.getString("acc_id")); usernameText.setText(rs.getString("username")); passwordText.setText(rs.getString("password")); tsText.setText(rs.getString("ts")); activeTSText.setText(rs.getString("act_ts")); } } catch (SQLException insertException) { displaySQLErrors(insertException); } } }); //Do Next Button previousButton = new JButton("<"); previousButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (!rs.isFirst()) { rs.previous(); accountIDText.setText(rs.getString("acc_id")); usernameText.setText(rs.getString("username")); passwordText.setText(rs.getString("password")); tsText.setText(rs.getString("ts")); activeTSText.setText(rs.getString("act_ts")); } } catch (SQLException insertException) { displaySQLErrors(insertException); } } }); //Do last Button lastButton = new JButton(">|"); lastButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { rs.last(); accountIDText.setText(rs.getString("acc_id")); usernameText.setText(rs.getString("username")); passwordText.setText(rs.getString("password")); tsText.setText(rs.getString("ts")); activeTSText.setText(rs.getString("act_ts")); } catch (SQLException insertException) { displaySQLErrors(insertException); } } }); //Do first Button firstButton = new JButton("|<"); firstButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {

Department of MCA

Page No15

JAVA/J2EE LAB try { rs.first(); accountIDText.setText(rs.getString("acc_id")); usernameText.setText(rs.getString("username")); passwordText.setText(rs.getString("password")); tsText.setText(rs.getString("ts")); activeTSText.setText(rs.getString("act_ts")); } catch (SQLException insertException) { displaySQLErrors(insertException); } } }); //Do gotoButton gotoButton = new JButton("Goto"); gotoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { rs.absolute(Integer.parseInt(gotoText.getText())); accountIDText.setText(rs.getString("acc_id")); usernameText.setText(rs.getString("username")); passwordText.setText(rs.getString("password")); tsText.setText(rs.getString("ts")); activeTSText.setText(rs.getString("act_ts")); } catch (SQLException insertException) { displaySQLErrors(insertException); } } });

Department of MCA

//Do freeQueryButton freeQueryButton = new JButton("Execute Query"); freeQueryButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (freeQueryText.getText().toUpperCase().indexOf("SELECT") >= 0) { rs = statement.executeQuery(freeQueryText.getText()); if (rs.next()) { accountIDText.setText(rs.getString("acc_id")); usernameText.setText(rs.getString("username")); passwordText.setText(rs.getString("password")); tsText.setText(rs.getString("ts")); activeTSText.setText(rs.getString("act_ts")); } } else { int i = statement .executeUpdate(freeQueryText.getText()); errorText.append("Rows affected = " + i); loadAccounts(); } } catch (SQLException insertException) { displaySQLErrors(insertException); } } }); JPanel first = new JPanel(new GridLayout(5, 1)); first.add(accountNumberListScrollPane); first.add(getAccountButton); first.add(insertAccountButton); first.add(deleteAccountButton); first.add(updateAccountButton); Page No16

JAVA/J2EE LAB

Department of MCA

accountIDText = new JTextField(25); usernameText = new JTextField(25); passwordText = new JTextField(25); tsText = new JTextField(25); activeTSText = new JTextField(25); errorText = new JTextArea(5, 25); errorText.setEditable(false); JPanel second = new JPanel(); second.setLayout(new GridLayout(6, 1)); second.add(accountIDText); second.add(usernameText); second.add(passwordText); second.add(tsText); second.add(activeTSText); JPanel third = new JPanel(); third.add(new JScrollPane(errorText)); JPanel fourth = new JPanel(); fourth.add(firstButton); fourth.add(previousButton); fourth.add(nextButton); fourth.add(lastButton); fourth.add(gotoText); fourth.add(gotoButton); JPanel fifth = new JPanel(); fifth.add(freeQueryText); c.add(first); c.add(second); c.add(third); c.add(fourth); c.add(fifth); c.add(freeQueryButton); setSize(500, 500); show(); } public void connectToDB() { try { //Class.forName("com.mysql.jdbc.Driver"); String connectionUrl = "jdbc:mysql://localhost/rvcemca?" + "user=root&password=poilkj"; connection = DriverManager.getConnection(connectionUrl); System.out.println ("Database connection established sss"); /* connection = DriverManager .getConnection("jdbc:mysql://192.168.1.25/accounts? user=spider&password=spider");*/ statement = connection.createStatement(); } catch (SQLException connectException) { System.out.println(connectException.getMessage()); System.out.println(connectException.getSQLState()); System.out.println(connectException.getErrorCode()); System.exit(1); } } Page No17

JAVA/J2EE LAB

Department of MCA

private void displaySQLErrors(SQLException e) { errorText.append("SQLException: " + e.getMessage() + "\n"); errorText.append("SQLState: " + e.getSQLState() + "\n"); errorText.append("VendorError: " + e.getErrorCode() + "\n"); } private void init() { connectToDB(); } public static void main(String[] args) { RSAccounts accounts = new RSAccounts(); accounts.addWindowListener(new WindowAdapter() { public void WindowClosing(WindowEvent e) { System.exit(0); } }); accounts.init(); accounts.buildGUI(); } } PROGRAM 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). *********************************************************************************** *********************** Code for Client Program. import java.net.*; import java.util.*; import java.io.*; public class Client { public static void main(String args[]) { Socket client=null; BufferedReader br=null; try { System.out.println(args[0] + " " + args[1]); client=new Socket(args[0],Integer.parseInt(args[1])); } catch(Exception e){} DataInputStream input=null; PrintStream output=null; try { input=new DataInputStream(client.getInputStream()); output=new PrintStream(client.getOutputStream()); br=new BufferedReader(new InputStreamReader(System.in)); String str=input.readLine();//get the prompt from the server System.out.println(str); // display the prompt on the client String filename=br.readLine(); if(filename!=null) output.println(filename); Page No18

machine

JAVA/J2EE LAB

Department of MCA

String data; while((data=input.readLine())!=null) System.out.println(data); client.close(); } catch(Exception e) { System.out.println(e); } } } Code for Server Program. import java.net.*; import java.io.*; import java.util.*; public class Server { public static void main(String args[]) { ServerSocket server=null; try {

server=new ServerSocket(Integer.parseInt(args[0])); }catch(Exception e){} while(true) { Socket client=null; PrintStream output=null; DataInputStream input=null; try { client=server.accept(); } catch(Exception e){ System.out.println(e);} try { output=new PrintStream(client.getOutputStream()); input=new DataInputStream(client.getInputStream()); } catch(Exception e){ System.out.println(e);} // send the command prompt to the client output.println("ENTER THE FILE NAME >"); try { // get the file name from the client String filename=input.readLine(); System.out.println("Client requested file: " + filename); try { FileReader(f));

File f=new File(filename); BufferedReader br=new BufferedReader(new String data; while((data=br.readLine()) != null) Page No19

JAVA/J2EE LAB {

Department of MCA

output.println(data); } } catch(FileNotFoundException e) { output.println("FILE NOT FOUND"); } client.close(); }catch(Exception e){ System.out.println(e); }

} }

} Output : Run Server Program first and then Client Program Output of Server :

E:\j2sdk1.4.0\bin>javac Server.java Note: Server.java uses or overrides a deprecated API. Note: Recompile with -deprecation for details. E:\j2sdk1.4.0\bin>javac -d Server.java E:\j2sdk1.4.0\bin>java Server 4000 Client requested file: gra.java Client requested file: kk.txt ^C E:\j2sdk1.4.0\bin> Output of Client : E:\j2sdk1.4.0\bin>javac Client.java Note: Client.java uses or overrides a deprecated API. Note: Recompile with -deprecation for details. E:\j2sdk1.4.0\bin>javac -d Client.java E:\j2sdk1.4.0\bin>java Client localhost 4000 localhost 4000 ENTER THE FILE NAME > gra.java import java.awt.*; import java.applet.*; public class gra extends Applet { public void paint(Graphics g) { g.drawRect(10,10,700,500); } } E:\j2sdk1.4.0\bin>java Client localhost 4000 localhost 4000 ENTER THE FILE NAME > kk.txt FILE NOT FOUND E:\j2sdk1.4.0\bin>

PROGRAM 7 : Write a Java Program to implement the Simple Client / Server Application using RMI . *********************************************************************************** *********************** Code for Remote Interface. import java.rmi.*; public interface HelloInterface extends Remote { public String getMessage() throws RemoteException; public void display() throws RemoteException; } Page No20

JAVA/J2EE LAB

Department of MCA

Code for Server. import java.rmi.*; import java.rmi.server.*; public class HelloServerImpl extends unicastRemoteobject implements HelloInterface { public HelloServerImpl() throws RemoteException { } public String getMessage() throws RemoteException { return "Hello Krishna Kumar"; } public void display() throws RemoteException { System.out.println("Hai how are you "); } public static void main (String args[]) { try{ HelloServerImpl Server = new HelloServerImpl(); Naming.rebind("rmi://localhost:1099/Server",Server); }catch(Exception e){} } } Code for Client. import java.rmi.*; public class HelloClient { public static void main(String args[]) { try{ HelloInterface Server = (HelloInterface)Naming.lookup("rmi://localhost:1099/Server"); String msg = Server.getMessage(); System.out.println(msg); Server.display(); }catch(Exception e){} } OUTPUT : E:\j2sdk1.4.0\bin>javac HelloInterface.java E:\j2sdk1.4.0\bin>javac HelloServerImpl.java E:\j2sdk1.4.0\bin>javac HelloClient.java E:\j2sdk1.4.0\bin>rmic HelloServerImp E:\j2sdk1.4.0\bin>start rmiregistry // Opens a New Window E:\j2sdk1.4.0\bin>java HelloServerImpl // Run in the New Window E:\j2sdk1.4.0\bin>java HelloClient // Run in New Window Hello Krishna Kumar Server Window Output Hai how are you *********************************************************************************** *********************** Page No21 }

JAVA/J2EE LAB

Department of MCA

PROGRAM 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). *********************************************************************************** *********************** //post.java import java.io.*; import java.util.*; import javax.servlet.*; public class post extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException,IOException { PrintWriter pw = response.getWriter(); Enumeration e = request.getParameterNames(); while(e.hasMoreElements() ) { String pname=(String)e.nextElement(); pw.print(pname); String pvalue=request.getParameter(pname); pw.println(pvalue); } pw.close(); } } post.html <html> <body> <center> <form name="form1" method ="post" action="http://localhost:8080/examples/servlets/servlet/post"> <table> <tr> <td><B>Username</td> <td><input type=textbox name="username"></td> </tr> <tr> <td><B>Password</td> <td><input type=textbox name="password"></td> </tr> </table> <input type=submit value="submit"> </form> </body> </html> PROGRAM 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) *********************************************************************************** *********************** import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class FileDownloads extends HttpServlet Page No22

JAVA/J2EE LAB

Department of MCA

{ public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("<html><head>Download a File Example</head></html>"); out.println("<pre><a href=DS.java> click here to download DS.java file </a><br> "); out.println("<pre><a href=SS.java> click here to download SS.java file </a> "); out.println("<pre><a href=askmeabtfreesoftware.png> click here to download askmeabtfreesoftware.png file </a><br> "); out.println("<pre><a href=fsfhead.pdf> click here to download fsfhead.pdf file </a> "); out.println("<pre><a href=pigeon.jpg> click here to download pigeon.jpg file </a><br> "); out.println("<pre><a href=stallman.jpg> click here to download stallman.jpg file </a> "); } } make entries in the web.xml file <servlet> <servlet-name>FileDownloads</servlet-name> <servlet-class>FileDownloads</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileDownloads</servlet-name> <url-pattern>/FileDownloads</url-pattern> </servlet-mapping> 10. a) Write a JAVA Servlet Program to implement RequestDispatcher object (use include() and forward() methods). *********************************************************************************** *********************** import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MultipleInclude extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Multiple Includes</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello from Level 1</h1>"); out.println("This text is displayed at Level 1."); RequestDispatcher dispatcher = request.getRequestDispatcher("/Level4"); dispatcher.include(request, response); out.println("</body>"); out.println("</html>"); out.close(); } } Page No23

JAVA/J2EE LAB <!-- web.xml --> <servlet> <servlet-name>MultipleInclude</servlet-name> <servlet-class>MultipleInclude</servlet-class> </servlet> <servlet-mapping> <servlet-name>MultipleInclude</servlet-name> <url-pattern>/MultipleInclude</url-pattern> </servlet-mapping> <servlet> <servlet-name>Level4</servlet-name> <servlet-class>Level4</servlet-class> </servlet> <servlet-mapping> <servlet-name>Level4</servlet-name> <url-pattern>/Level4</url-pattern> </servlet-mapping> // here is another servlet import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

Department of MCA

public class Level4 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { java.io.PrintWriter out = response.getWriter(); out.println("<h4>Hello from another doGet</h4>"); out.println("Hello from another doGet."); } } 10. a) Write a JAVA Servlet Program to implement RequestDispatcher object (use include() and forward() methods). import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MultipleInclude extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Multiple Includes</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello from Level 1</h1>"); out.println("This text is displayed at Level 1."); RequestDispatcher dispatcher = request.getRequestDispatcher("/Level4"); dispatcher.include(request, response); out.println("</body>"); Page No24

JAVA/J2EE LAB out.println("</html>"); out.close(); } } <!-- web.xml --> <servlet> <servlet-name>MultipleInclude</servlet-name> <servlet-class>MultipleInclude</servlet-class> </servlet> <servlet-mapping> <servlet-name>MultipleInclude</servlet-name> <url-pattern>/MultipleInclude</url-pattern> </servlet-mapping> <servlet> <servlet-name>Level4</servlet-name> <servlet-class>Level4</servlet-class> </servlet> <servlet-mapping> <servlet-name>Level4</servlet-name> <url-pattern>/Level4</url-pattern> </servlet-mapping> // here is another servlet import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

Department of MCA

public class Level4 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { java.io.PrintWriter out = response.getWriter(); out.println("<h4>Hello from another doGet</h4>"); out.println("Hello from another doGet."); } } 10. b)Write a JAVA Servlet Program to implement and demonstrate get() and Post methods (Using HTTP Servlet Class). *********************************************************************************** *********************** <html> <body> <center> <form name="form1" method=post action="http://localhost:8080/examples/servlets/servlet/colorpost"> <B>color:</B> <select name="color"size="1"> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <br><br> <input type=submit value="submit"> </form> </body> </html> import java.io.*; Page No25

JAVA/J2EE LAB import javax.servlet.*; import javax.servlet.http.*;

Department of MCA

public class colorpost extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { String color=request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.println("the selected color is:"); pw.println(color); pw.close(); } } -------------usinng GET import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class color extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { String color=request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.println("the selected color is:"); pw.println(color); pw.close(); } } <html> <body> <center> <form name="form1" action="http://localhost:8080/examples/servlets/servlet/color"> <B>color:</B> <select name="color"size="1"> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <br><br> <input type=submit value="submit"> </form> </body> </html> PROGRAM 11 .Write a JAVA Servlet Program to implement sendRedirect() method(using HTTP Servlet Class). *********************************************************************************** *********************** //DS.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Page No26

JAVA/J2EE LAB

Department of MCA

public class DS extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("<html><head>SendRedirect() Example</head></html>"); out.println("<body><center><font color=red size = 34>MyWeb </font>"); out.println("<pre><a href=SS>Search</a> <a href=DS>greetings</a> </pre>"); out.println("<table border = 1, width = 100 >"); out.println("<tr><th>SNO</th><th>B.name</th><th>Quality</th></tr>"); out.println("<tr><td>1</td><td>J2SE</td><td>10</td></tr>"); out.println("<tr><td>2</td><td>J2EE</td><td>10</td></tr>"); out.println("</table></center></body></body>"); } } //SS.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SS extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { res.sendRedirect("http://localhost:8080/examples/jsp/index.html"); } } 12. Write a JAVA Servlet Program to implement sessions (Using HTTP Session Interface). *********************************************************************************** *********************** import java.io.PrintWriter; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class SessionTracker extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); HttpSession session = req.getSession(true); Integer count = (Integer) session.getAttribute("count"); if (count == null) { count = new Integer(1);} else {count = new Integer(count.intValue() + 1); } session.setAttribute("count", count); out.println("<html><head><title>SessionSnoop</title></head>"); out.println("<body><h1>Session Details</h1>"); out.println("You've visited this page " + count + ((count.intValue()== 1) ? " time." : " times.") + "<br/>"); out.println("<h3>Details of this session:</h3>"); out.println("Session id: " + session.getId() + "<br/>"); out.println("New session: " + session.isNew() + "<br/>"); out.println("Timeout: " + session.getMaxInactiveInterval() + "<br/>"); out.println("Creation time: " + new Date(session.getCreationTime()) + "<br/>"); out.println("Last access time: " + new Date(session.getLastAccessedTime()) + "<br/>"); out.println("</body></html>"); Page No27

JAVA/J2EE LAB } }

Department of MCA

PROGRAM 13. a) Write a JAVA JSP Program to print 10 even and 10 odd number. *********************************************************************************** *********************** -------------------------//EvenOdd.jsp <html> <head> <title>Scriptlet for Even odd nos print</title> </head> <body> <h1>10 Even and 10 odd numbers</h1> <% out.print("<b>10 Even numbers starting from 1 are</><br>"); for (int i=1;i <= 20; i++){ if(i%2==0 ) { out.print("<br><b> " + i + "</b>"); } } out.print("<br><br><b> 10 Odd Nos starting from 1are </b><br>"); for (int i=1;i <= 20; i++){ if(i%2!=0 ) { out.print("<br><b> " + i + "</b>"); } } %> </body> </html> 13) b. Write a JAVA JSP Program to implement verification of a particular user login and display a welcome page. *********************************************************************************** *********************** ----------------------------indexforward.html <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>JSP Page</title> </head> <body><h1>Hello Users</h1> <form method="post" action="forward.jsp"> <p>please enter your username: <input type="text" name="username"> <br>and password: <input type="password" name="password"> </p> <p><input type="submit" value="login"></p> </form> </body> </html> --------------forward.jsp <% if (request.getParameter("username").equals("Richard")){ if(request.getParameter("password").equals("MStallman")) { %> <jsp:forward page="forward2.jsp" /> <% } %> Page No28

JAVA/J2EE LAB

Department of MCA

<% }else { %> <%@ include file="indexforward.html" %> <% } %> ---------------forward2.jsp <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> </head> <body> <h1>Forward action test :Login Successful</h1> <%= request.getParameter("username") %> </body> </html> 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. *********************************************************************************** ******************** -----------------Employee.java ( students should implement for the student class ) package beans; public class Employee { public String ename; public int eno; public double esalary; public void setename(String e) {ename = e;} public String getename() {return ename;} public void seteno(int en) {eno=en;} public int geteno() {return eno;} public void setesalary(double esal) {esalary = esal;} public double getesalary() {return esalary;} } Note: Before compiling create a directory called beans in /usr/share/tomcat6-examples/examples/WEB-INF/classes so that after compilation the Employee.class file has to place there ----------------EmpInfo.html <html> <head><title> employee information </title></head> <body> <form action ="first.jsp" method = "post"> Employee No : <input type = "text" name = "eno"/><br> Employee Name : <input type = "text" name = "ename"/><br> Employee Salaary : <input type = "text" name = "esalary"/><br> <input type ="submit" value ="show"/> </form> </body> </html> ----------------first.jsp <html> <body> Page No29

JAVA/J2EE LAB

Department of MCA

<jsp:useBean id="emp" scope="request" class="beans.Employee"/> <jsp:setProperty name="emp" property="*"/> <jsp:forward page="display.jsp"/> </body> </html> ---------------display.jsp <html> <body> <jsp:useBean id="emp" scope="request" class="beans.Employee"/> Emp Name <jsp:getProperty name="emp" property="ename"/><br> Emp Number <jsp:getProperty name="emp" property="eno"/><br> Emp Salary <%out.print(emp.getesalary());%> </body> </html>

Page No30

You might also like