View All Applets


A) General
1. Differences between Applications and Applets
2. Simple Java example with Life cycle with HTML file
3. Drawing Strings & Graphics on Applet window
4. Reading HTML <param> Tag in Applet Example
5. Drawing Images & Playing Audio Clips

B) Special
6. HTML to Applet & Inter-Applet Communication
7. Banner, Applet cum Application
8. Converting Applet to Application
9. Converting Application to Applet
10. Applet with AWT GUI – Buttons
11. Difference between start and init in Applet

79 thoughts on “View All Applets”

  1. Hi,
    How can i send array of string objects from an applet to a servlet and how can i see it in the servlet?

    Here is your posted code.
    so please help me to send array of object using ur code only.

    OutputStream ostream = ucon.getOutputStream( );
    ObjectOutputStream oos = new ObjectOutputStream(ostream);

    Integer i1 = new Integer( str );

    oos.writeObject( i1 ); —> here how can i send the more than 2 objects

    Thanks & Regards
    Bikash

  2. Hi;

    In previous post i have mention wrong sql query i.e instead of

    ” select count(*) from table A where empno=?; (?=empno of A) ”

    the query is

    ” select count(*) from table B where empno=?; (?=empno of A)”

  3. Hi,

    In jdbc i have a requirement i.e

    1. I have to access the empno from table A.

    2. with empno from A i have to check the total no of same empno present in another table i.e B.

    i.e select count(*) from table A where empno=?; (?=empno of A)

    3. If count(*) >0 then i don’t want to insert the corresponding record into table B.
    4. if count(*) =0 then i want to insert the record in table B.

    The fact is i have implemented the same in my code .When i execute my code it is very slow.

    For this i am using simple JDBC. I can’t use Hibernate.

    How can i speed up my code performance.

    Sorry i can’t attach my code due to some problem.

    Please help me on this.

    Thanks & Regards

    Bikash

      1. Hi ,

        Actually it’s a simple java application. I am not using any servlet .so how can it possible ?

        Thanks & Regards

        Bikash

  4. Hi,

    Could u clarifying me what is the difference between java 1.6 and 1.7 ?

    i.e what are the enhancement in java 1.7 ?

    with regards

    Bikash

  5. HI Sir,

    I have a tool which will read data from the main table and inserted same data into mytable. The main table has 2 lakhs of records.

    I am using preparedstatement to read and insert the data.

    But the problem is that it has taken lot of time to read and insert.

    How can i speed up my tool perfermance?

    Can i use addBatch()? if yes i want to read and insert 10,000 records at a time and then i will use con.commit.

    So that when next time i start my tool it will not read and insert the old records.i.e first 10000 records.It will start from new one i.e from 10001.

    How can i do this ?

    If no , please guide me what can i do to increase my tool perfermance ?

    I am using simple jdbc.

    with regards
    Bikash

  6. Hi,

    I have a properties file which contains db credentials. I have to access the file dynamically in my java file. i.e i don’t want to hard code the path of the file .

    How can i access the file and how can i read all the values from that file in my java application.

    Please help me.

    with regards
    Bikash

  7. Hi Sir,

    I have devloped a tool, in that i have an requirement to popup a message to the user.

    For an example

    In that tool some i have implemented a query that deletes some records from the table.

    So i have to show the user how many recors has deleted from the db through a pop message.

    My tool is a simple java file.

    So how can i implement this.

    with regards

    Bikash

  8. Hi sir,

    I have to insert more than 1000 of record in mytable.For that i have developed a tool which will insert records from mastertable to my table. But when i run my tool , my tool can inserted only 148 records for 1st run and it will showing a error i.e

    java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1
    ORA-01000: maximum open cursors exceeded
    ORA-00604: error occurred at recursive SQL level 1
    ORA-01000: maximum open cursors exceeded
    ORA-01000: maximum open cursors exceeded

    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1030)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:785)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:860)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3381)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3425)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1490)
    at com.per.sub.ReadNostroReadCount.main

    After that it will insert 148/2=74 records into the table with same above specified error.

    After that it will insert 74/2=37 records into the table with same above specified error.

    and will insert records so on with same error.

    But at last it will enter only single record with same error and after that it will not enter any reocord.

    I am afraid why it happens like that.

    Please help me and please solve the problem.

    with regards

    Bikash

  9. Hi sir,
    i have 2 tables.One is mastertable and another is mytable and both have their own primary key .There is no foreign key relationship between these 2 tables.

    Now have a tool in which i have 2 stmts.i.e

    a. delete the records from mytble whose balance is 0.
    b. insert the new reocords into mytable from mastertable whose balance is not 0.

    My requirement is :-

    Before inserting the records into mytable i have to check the primary key value of mastertable is present in mytable or not.

    if it is present then i will not insert the record into mytable

    If it is not present then i will enter the records into mytable.

    I am doing with this code
    ……………
    …………..
    ……………

    st=con.createStatement();
    ResultSet rs1=st.executeQuery(“select statement_tag61 from NOSTRO_KASTLE”);

    while(rs1.next())
    {
    stmttag=rs1.getString(1);
    System.out.println(“nostro is”+stmttag);
    count++;
    //***************** start count(*)
    try
    {
    ps=con.prepareStatement(nostro_pk_no);
    ps.setString(1, stmttag);
    System.out.println(“the value of str is”+stmttag);
    rs=ps.executeQuery();—-> here i am getting error
    while(rs.next())
    {
    no=rs.getInt(1);
    }
    if(no==0)
    {
    System.out.println(“new nostro”);
    }
    else
    {
    System.out.println(“old record”);
    }
    System.out.println(“resultset is created”);
    //ps.close();
    //con.close();
    }
    catch(Exception e)
    {
    System.out.println(“Got an exception”);
    e.printStackTrace();
    }

    //*************** end conunt(*)
    }
    rs1.close();
    //System.out.println(“total records are”+count);
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }

    *** i hv mention a piece of code.

    i am not getting my output with the above implemented logic.

    So how can i do it, Please tell me.

    with regards

    BIkash

  10. Hi ,

    I am developing a tool which will do 3 things.
    A. delete some records based on some condition.
    B. select records from one table.
    C. Insert into another table.

    I have already imlemented it. First time it has worked.But when i run it from 2nd time onwards , i have to commit my db explicitely.

    So i have used con.commit(); in my programme. But it is still not working since i run commit command in db explicitely.

    So what can i do to solve the issue ?

    Please tell me.

    with regards

    Bikash

      1. Hi ,

        Thanks for your suggestion.

        But i have call con.commit() after each executeUpdate() method .but it won’t work.

        Could u clarify me how many times we have to call con.commit() in our programme?

        I have called this method for each transaction.
        Is it fine or i have to call one and only one time in the programme.

        Thanks & Regards

        Bikash

  11. Hi sir,

    I have an account table as like this

    Accno Accnm accbal
    1 Kumar 0
    2 sanu 2

    I have to delete the record whose accbal=0 .
    My code is:-
    package com.per.sub;

    import java.sql.*;
    class Check {
    static void main(String[] args)
    {
    int n=0;
    int i=0;
    Connection con=null;
    PreparedStatement ps=null;
    String del_query=”delete from accounts where accbal=?”;
    try
    {
    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    =DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
    System.out.println(“connected successfully”);
    ps=con.prepareStatement(del_query);
    ps.setInt(1, i);
    n=ps.executeUpdate();
    System.out.println(n+”records are deleted”);
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    finally
    {
    try{
    if (ps != null) {
    ps.close();
    }

    if (con!= null) {
    con.close();
    }
    }
    catch(Exception e1)
    {
    e1.printStackTrace();
    }
    }
    }

    }

    But the record is not deleted.But if i delete the record where accbal=2 then it works.

    Please tell me what is the problem?

    with regards

    bikash

  12. Hi Sir,

    I have an requirement to write 2 update statement in my java file and the 2 files will be fired one after another.i.e 1st update stmt and then the 2nd stmt . These 2 update stmt are different i.e 1st stmt update one record and 2nd one update the other column.

    How can i do it ?

    Can do it by addBatch() ? If yes then how ? If not , what is the another way to achive ?

    Please help me ?

    with regards

    Bikash

  13. Hi Sir,

    Is there any function named instr(). if it is then what is the use of this and how can we use it?

    Please tell me ?

    with regards

    Bikash

  14. Hi Sir,

    how can i conver the string value to long.i.e

    String inward=”30.98″;

    I have to convert inward to long type.

    If i use long l1=Long.parseLong(inward);

    I found Exception in thread “main” java.lang.NumberFormatException: For input string: “30.98”.

    How can i do it ?

    Pls help me

    with regards
    bikash

  15. Hi Sir,

    I have a string i.e

    String str=” id=1,nm=p,age=32″;

    How can i print nm value from str .

    Please help me.

    with regards

    Bikash

  16. Hi Sir,

    I have an simple object which contains some data.

    I have to print all the data that object contains.

    How can i do this ?

    Please help me.

    with regards

    Bikash

    1. Override toString() method as follows.

      public class Employee
      {
      int salary;
      String name;

      public String toString()
      {
      return “Employee Name: ” + name + ” and Employee Salary Rs.” + salary;
      }

      public static void main(String args[])
      {
      Employee emp1 = new Employee(); //
      Employee emp2 = new Employee();

      emp1.salary = 5000;
      emp2.salary = 6000;

      emp1.name =”biksah”;
      emp2.name =”Rao”;

      System.out.println(emp1);
      System.out.println(emp2);
      }
      }

  17. Hi sir,

    I have a textfield in my applet and i.e

    private TextField nostroValueDate;

    nostroValueDate = new TextField( 10 );

    nostroValueDate.addKeyListener(this);

    Requirement :-
    —————–
    1. I have to polulate the date in nostroValueDate field which is coming from the database.

    2. But the date is coming and it has shown for fraction of time in the nostroValueDate filed and after that is get disable.

    3. I have to fix the data shown in the textfield.

    How can i do this ?

    Please help me

    Thanks & Regards

    Bikash

  18. Hi,

    I have an applet which have some drop dwon fields and text fields and one button which are interlinked to each other.i.e when i select one value from one field then another field will polulated. i.e the data came from the database and populated in the corresponding field.

    Requiremnt:-

    When i select a value from the drop down list then the button field will blinking . I have to stop the blinking.

    How can i do it ?

    Please help me.

      1. Hi sir,

        I am not getting ur respnse regarding button blinking.

        1.Which logic that i have to place in sleep() method ?

        2.Where i have to place the sleep method ?

        Can u please send me the demo code ?

        Thanks & Regards

        Bikash

  19. Hi,

    I have 2 files having some records/contents. My requirement is that i have to find out the common records as well as non matching records.

    How can i get the answer ?

    Please help me.

  20. Hi,

    I am new to stored procedure. I have one table and i have written a stored procedure.
    My doubt is how to execute the below stored procedure.

    Please help me as soon as possible.

    oracle table structure
    ——————————-

    CREATE TABLE ACCOUNTS
    ( ACCNO NUMBER(10),
    ACCNM VARCHAR2(10 BYTE),
    ACCBAL NUMBER(7,4)
    )

    Procedure
    —————

    CREATE OR REPLACE PROCEDURE addinterest(
    ano IN accounts.accno%TYPE,
    bal OUT accounts.accbal%TYPE)
    IS
    BEGIN

    select accbal into bal from accounts where accno=ano;
    bal:=bal+bal*0.5;
    update accounts set accbal=bal where accno=ano;
    end;

    Please help me how to execute the stored procedure in oracle.

  21. Hi,

    I am new to stored procedure. I have one table and i have written a stored procedure.
    My doubt is how to execute the below stored procedure.

    Please help me as soon as possible.

    oracle table structure
    ——————————-

    CREATE TABLE ACCOUNTS
    ( ACCNO NUMBER(10),
    ACCNM VARCHAR2(10 BYTE),
    ACCBAL NUMBER(7,4)
    )

    Procedure
    —————

    CREATE OR REPLACE PROCEDURE addinterest(
    ano IN accounts.accno%TYPE,
    bal OUT accounts.accbal%TYPE)
    IS
    BEGIN

    select accbal into bal from accounts where accno=ano;
    bal:=bal+bal*0.5;
    update accounts set accbal=bal where accno=ano;
    end;

    Please help me how to execute the stored procedure in oracle.

    – See more at: http://way2java.com/view-all/view-all-applets/comment-page-1/#comment-95504

  22. HI Sir,

    I hv create a sp which contains one select stmt and one update stmt in oracle and i have to access it through my java class .But i am getting some errors .

    I mention here my .java file,procedure and table structure and the error file.

    Please make some necessary correction and send me updated code.

    Please respond this post as soon as possible.

    The details are as follows:-

    StoredProcedure.java
    ——————————–

    import java.sql.*;

    class StoredProcedure
    {
    public static void main(String[] args)throws Exception
    {
    try
    {
    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:orcl”,”scott”,”tiger”);

    CallableStatement cst = con.prepareCall(“{call addinterest(?,?)}”);

    cst.registerOutParameter(2,Types.FLOAT);

    cst.setInt(1,123);

    cst.execute();

    float accbal = cst.getFloat(2);
    System.out.println(“Modified balance is rs:” +accbal);
    cst.close();
    con.close();
    }
    catch (Exception e)
    {

    e.printStackTrace();
    }

    }
    }

    oracle table structure
    ——————————-

    CREATE TABLE ACCOUNTS
    ( ACCNO NUMBER(10),
    ACCNM VARCHAR2(10 BYTE),
    ACCBAL NUMBER(7,4)
    )

    Procedure
    —————

    CREATE OR REPLACE PROCEDURE addinterest(
    ano IN accounts.accno%TYPE,
    bal OUT accounts.accbal%TYPE)
    IS
    BEGIN

    select accbal into bal from accounts where accno=ano;
    bal:=bal+bal*0.5;
    update accounts set accbal=bal where accno=ano;
    end;

    and the error is
    ———————

    java.sql.SQLException: ORA-01403: no data found
    ORA-06512: at “RETDEV.ADDINTEREST”, line 8
    ORA-06512: at line 1

    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1030)
    at oracle.jdbc.driver.T4CCallableStatement.doOall8(T4CCallableStatement.java:191)
    at oracle.jdbc.driver.T4CCallableStatement.executeForRows(T4CCallableStatement.java:944)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1222)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3381)
    at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3482)
    at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:3856)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1373)
    at com.per.sub.StoredProcedure.main(StoredProcedure.java:20)

    1. Hi,

      I am new to stored procedure. I have one table and i have written a stored procedure.
      My doubt is how to execute the below stored procedure.

      Please help me as soon as possible.

      oracle table structure
      ——————————-

      CREATE TABLE ACCOUNTS
      ( ACCNO NUMBER(10),
      ACCNM VARCHAR2(10 BYTE),
      ACCBAL NUMBER(7,4)
      )

      Procedure
      —————

      CREATE OR REPLACE PROCEDURE addinterest(
      ano IN accounts.accno%TYPE,
      bal OUT accounts.accbal%TYPE)
      IS
      BEGIN

      select accbal into bal from accounts where accno=ano;
      bal:=bal+bal*0.5;
      update accounts set accbal=bal where accno=ano;
      end;

      Please help me how to execute the stored procedure in oracle.

  23. Hi sir,

    Thank for ur response.

    I have gone through the code as u have mentioned above .But i didn’t get my result.
    The contrl can’t enter into the while loop that i have placed in my programme.I am posting my programme .Please go through this.

    import java.sql.*;

    class Populate
    {
    public static void main(String[] args)
    {
    try
    {
    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    String cs=”jdbc:oracle:thin:@localhost:1521:orcl”;
    Connection con=DriverManager.getConnection(cs,”SCOTT”,”TIGER”);
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery(“select sid,sname from student where amt <0");
    System.out.println("rsultset object created");
    while(rs.next())
    {
    //float a =rs.getFloat(1);
    int sid=rs.getInt(1);
    String nm=rs.getString(2);
    System.out.println("a/c details");
    System.out.println("a/c no is :" + sid);
    System.out.println("name is "+nm);
    }
    System.out.println("at line no 25");
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    }
    }

    The output of the above programme is

    rsultset object created
    at line no 25

    But i have more than 100 records in my table and i want to populate all the records in the dropdown list of my jsp.

    How can i do it?

    Please help me as soon as possible.

    with regards
    Bikash

  24. Hi sir,

    my requirement is as follows:-

    1.In my database has amount column having datatype number(12,4).That column contains both + and – values.

    2. I have to fetch only – records from the database.

    3. Those data has to transfer to the web layer i.e jsp and polulate all the negetive values in one drop down list in jsp.

    How can i do it ?

    Please help me with code .

    with regards

    Bikash

  25. Hi sir,

    In my ResultSet object i have 200 records . I want to see those records .How can i see ?

    The code should be generic i.e industry standard.

    Please reply this post as soon as possible.

    with regards

    Bikash

  26. Hi sir,

    I have my code below.I can get the values from the table but the same records could’t inserted in another table.

    The code is

    //package com.per.sub;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.sql.*;

    public class SelectInsert
    {
    public static void main(String[] argv) throws Exception
    {
    try
    {
    Connection con = DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:orcl”,”soctt”,”tiger”);
    Connection con1 = DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:orcl”,”soctt”,”tiger”);

    //String sql = “INSERT INTO employee1(“+ “empid,”+ “empname)”+ “VALUES(?,?)”;
    String sql = “INSERT INTO employee1(empid,empname)”+ “VALUES(?,?)”;
    //Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
    Statement statement = con.createStatement();
    PreparedStatement pstmt = con1.prepareStatement(sql);

    ResultSet rs = statement.executeQuery(“SELECT * FROM employee”);
    while ( rs.next() )
    {
    /*String nm = rs.getString(2);
    Boolean ac = rs.getBoolean(3);
    String log = rs.getString(4);
    String pass = rs.getString(5);
    pstmt.setString(1, nm);
    pstmt.setBoolean(2, ac);
    pstmt.setString(3, log);
    pstmt.setString(4, pass);
    pstmt.executeUpdate();*/
    int id=rs.getInt(1);
    String nm=rs.getString(2);
    pstmt.setInt(1, id);
    pstmt.setString(2, nm);
    }
    con.close();statement.close();
    con1.close();pstmt.close();rs.close();
    }
    catch (SQLException e)
    {
    System.out.println(“could not get JDBC connection: ” +e);
    }
    }
    }

    Please make necessary correction and update me with the correct code.

    with regards

    Bikash

  27. Hi sir,

    I have my code below.I can get the values from the table but the same records could’t inserted in another table.

    Please make necessary correction and update me with the correct code.

    with regards

    Bikash

  28. Hello Sir,

    I have an requirement to fetch date in this format i.e 11/07/2014 (dd/mm/yyyy) from the database .
    What would be the code to get the date as per my requirement.Please help me.

    If i used the getDate() method i can get the date like 2014-07-11.

    with regards

    bikash

  29. Hi sir,

    Would you tell me why i am getting this error ?

    I have seen in tomcat’s log i.e catalina.out.The error msg is as follows

    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
    at org.apache.catalina.valves.RequestFilterValve.process(RequestFilterValve.java:276)
    at org.apache.catalina.valves.RemoteAddrValve.invoke(RemoteAddrValve.java:81)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
    at java.lang.Thread.run(Thread.java:595)

    Please reply this post as soon as possible.

    with regards

    Bikash

  30. Hi Sir,

    I have an applet and servlet communication using tomcat.I have an System.out.prinln in my servlet. Where i can find out the output i.e which tomcat file i can find out the restult.

    Please help me.

    with regards

    Bikask

  31. Thanks for ur reply.
    Actually the two .html files are not visible .Would u provide these 2 html files once again.

    with regards

    bikash

  32. Hi Sir,

    I have sent some post since yesterdat.But i am not getting any response from ur side.
    Whatever code that u have given with that myapplet can’t connect to servlet.I am getting following exception

    some problemjava.io.IOException: Server returned HTTP response code: 502 for URL: https://ip/webapps/folder_name/CustomServlet

  33. Hello Sir,

    Thank for the response.In this post the 2 .html files are not visible in any browser i.e (IE,Fire Fox,Google Chrome ). Do me a favour please attach these 2 .html file in this post or mail me on [email protected].

    It’s urgent.

    Thanks & Regards

    Bikash

  34. Hello sir,

    How can a value can be sent to the servlet for database manipulation after selecting the value from the drop down list of an applet?

    a. First of all i need the applet-servlet communication.
    b. Then i need the code to send data from applet to servlet?

    Please help me soon.

    Thanks & regards.

    1. Follow this and may be helpful in your code.

      Applet to Servlet Communication

      Applet to Servlet communication is of 2 types:

      1. Text-based communication
      2. Object-based communication

      1) Text based Communication

      It is assumed that there exists a table Employee with following fields:

      empid number
      empname varchar2(15)
      empsal number(6, 2)

      The source code involves 3 programs:

      1. FetchRecordApplet.hmtl for calling applet
      2. FetchRecordApplet.java to display an UI to take user’s input of empid and forward it to the servlet. This UI receives the employee particulars from the servlet and displays them in the text fields.
      3. FetchRecordServlet.java to receive data from the applet, search for database Employee table, take the values and send them to the applet.

      When you run this program, you may get Security Exception. To overcome this, do the following:

      Browser menu bar  Tools  Internet Options  Security  Internet  Custom Level  Miscellaneous  Access Data Sources across domains  Select enable

      Also with

      Browser menu bar  Tools  Internet Options  Security  Local Intranet  Custom Level  Miscellaneous  Access Data Sources across domains  Select enable

      1st Program: FetchRecordApplet.html (copy to examplesWebApp)

      2nd Program: FetchRecordApplet.java (copy to examplesWebApp)
      (for applet file, web.xml file need not be written)

      import java.applet.*; import java.awt.*; import java.awt.event.*;
      import java.net.*; import java.io.*;

      public class FetchRecordApplet extends Applet implements ActionListener
      {
      TextField idField, nameField, salaryField ;
      Button fetchButton ;

      public void init( )
      {
      setLayout(new BorderLayout( ) );
      Panel p1 = new Panel( );
      p1.setLayout(new GridLayout( 2, 2, 5, 5 ) );
      p1.setBackground(Color.cyan);

      Panel p2 = new Panel( );
      p2.setBackground(Color.pink);
      p2.setLayout(new GridLayout( 2, 2, 5, 5 ));

      p1.add( new Label(“Enter Employee ID” ));
      p1.add( idField = new TextField(15) );
      p1.add( new Label(“Click for Details” ));
      p1.add( fetchButton = new Button(“Fetch Details” ));
      fetchButton.setBackground(Color.yellow);

      p2.add( new Label( “Employee Name” ));
      p2.add( nameField = new TextField(15));
      p2.add( new Label( “Employee Salary” ));
      p2.add( salaryField = new TextField(15) );

      fetchButton.addActionListener(this);

      add(p1, “North”); add(p2, “South”);

      }
      public void actionPerformed(ActionEvent e)
      {
      try
      {
      String str = idField.getText( );

      URL u1 = new URL(“http://home:7001/examplesWebApp/
      myFetchRecordServlet?t1=”+str);
      URLConnection ucon = u1.openConnection( );

      InputStream istream = ucon.getInputStream( );

      BufferedReader br = new BufferedReader(new
      InputStreamReader(istream));
      String details[ ] = new String[2];

      int i = 0 ;
      String str1=””;

      while( (str1 = br.readLine( ) ) != null )
      {
      details[i] = str1 ;
      i + + ;
      }
      br.close( );

      nameField.setText(details[0]);
      salaryField.setText(details[1]);
      }
      catch(Exception e1)
      {
      nameField.setText(“Some Problem” + e1);
      salaryField.setText(“Data not received”);
      }
      }
      }

      3rd Program: FetchRecordServlet.java (copy to examplesWebApp)

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

      public class FetchRecordServlet extends HttpServlet
      {
      public void doGet(HttpServletRequest req, HttpServletResponse res) throws
      ServletException, IOException
      {
      res.setContentType(“text/plain”);
      PrintWriter out = res.getWriter( );
      String idno = req.getParameter(“t1”);

      try
      {
      Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” );
      Connection con = DriverManager.getConnection(
      “jdbc:odbc:snrao”,”scott”,”tiger”);
      Statement stmt = con.createStatement( );

      ResultSet res1 = stmt.executeQuery(“select *from Employee where
      empid=” + idno);
      res1.next( );

      String name = res1.getString(2);
      String salary = res1.getString(3);
      out.println(name);
      out.println(salary);
      out.flush( );

      res1.close( ); stmt.close( ); con.close( ); out.close( );
      }
      catch(ClassNotFoundException e)
      {
      out.println(“The database driver is not found”);
      }
      catch(SQLException e)
      {
      out.println(“Name not found”);
      out.println(“Salary not found”);
      }
      }
      }

      2. Object-based Communication:

      In this objects are passed and retrieved.
      The source code involves 3 independent programs.

      1st Program: ObjectCommunicationApplet.html


      2nd Program: ObjectCommunicationApplet.java ( copy it to the examplesWebApp
      directory)
      import java.applet.*; import java.awt.*; import java.awt.event.*;
      import java.net.*; import java.io.*; import java.util.*;

      public class ObjectCommunicationApplet extends Applet implements ActionListener
      {
      TextField idField, nameField, salaryField ;
      Button fetchButton;

      public void init( )
      {
      setLayout(new BorderLayout( ) );
      Panel p1 = new Panel( );
      p1.setLayout(new GridLayout( 2, 2, 5, 5 ));
      p1.setBackground(Color.cyan);

      Panel p2 = new Panel( );
      p2.setBackground(Color.pink);
      p2.setLayout(new GridLayout(2,2,5,5));

      p1.add( new Label(“Enter Employee ID” ));
      p1.add( idField = new TextField(15) );
      p1.add( new Label(“Click for Details” ));
      p1.add( fetchButton = new Button(“Fetch Details” ));
      fetchButton.setBackground(Color.yellow);

      p2.add( new Label( “Employee Name” ));
      p2.add( nameField = new TextField(15));
      p2.add( new Label( “Employee Salary” ));
      p2.add( salaryField = new TextField(15) );

      fetchButton.addActionListener(this);

      add(p1, “North”); add(p2, “South”);

      }
      public void actionPerformed(ActionEvent e)
      {
      try
      {
      String str = idField.getText( );

      URL u1 = new URL(“http://home:7001/examplesWebApp/
      myObjectCommunicationServlet”);

      URLConnection ucon = u1.openConnection( );

      ucon.setUseCaches(false);
      ucon.setDoInput(true);
      ucon.setDoOutput(true);
      ucon.setRequestProperty(“Content-Type”, “application/octet-stream”);
      // code to send data(employee id) to the servlet
      OutputStream ostream = ucon.getOutputStream( );
      ObjectOutputStream oos = new ObjectOutputStream(ostream);

      Integer i1 = new Integer( str );

      oos.writeObject( i1 );

      oos.flush( );
      oos.close( );
      // code to receive data(employee name and salary) from the servlet

      InputStream istream = ucon.getInputStream( );
      ObjectInputStream ois = new ObjectInputStream(istream);
      // get an object from the servlet that contains the data
      Object obj = ois.readObject( );
      Vector vect1 = (Vector) obj;
      ois.close( );

      String name = (String) vect1.elementAt( 0 );
      String salary = (String) vect1.elementAt( 1 );

      nameField.setText(name);
      salaryField.setText(salary);
      }
      catch(Exception e1)
      {
      nameField.setText(“Some Problem” + e1);
      salaryField.setText(“Data not received”);
      }
      }
      }

      3rd Program: ObjectCommunicationServlet.java

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

      public class ObjectCommunicationServlet extends HttpServlet
      {
      public void service(HttpServletRequest req, HttpServletResponse res) throws
      ServletException, IOException
      {
      res.setContentType(“text/plain”);

      ObjectInputStream ois = new ObjectInputStream(req.getInputStream( ));
      ObjectOutputStream oos = new ObjectOutputStream(
      res.getOutputStream( ) );
      res.setContentType(“application/octet-stream”);

      try
      {
      Integer idno1 = (Integer) ois.readObject( );
      String idno = idno1.toString( );

      Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
      Connection con = DriverManager.getConnection( “jdbc:odbc:snrao”,
      “scott”,”tiger”);
      Statement stmt = con.createStatement( );

      ResultSet res1 = stmt.executeQuery(“select *from Employee where
      empid = ” +idno);
      res1.next( );

      String name = res1.getString(2);
      String salary = res1.getString(3);

      Vector vect2 = new Vector( );
      vect2.addElement(name);
      vect2.addElement(salary);

      oos.writeObject(vect2);

      res1.close( ); stmt.close( ); con.close( );
      }
      catch(ClassNotFoundException e)
      {
      e.printStackTrace( );
      }
      catch(SQLException e)
      {
      e.printStackTrace( );
      }
      }
      }

  35. Amani Chowdary

    Sir! I wants to know the methods of passing parameters to applets. Iam nt gettng it here. Can u pls help me……

Leave a Comment

Your email address will not be published.