[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 517
  • Last Modified:

Applet Servlet SQL Problem

I have set up an applet servlet communication link, when i call the doPost() method i wish to recieve the data sent by the applet a Java Object, namely Job. I can recieve the job without any problems in the servlet, i want to then store that job in my SQL db, for which i have created a separate class namely DataStore. Which has the ability to store and update data in my db. When i test the db using in a separate class as:


    public static void main (String[] args){
       DataStore ds = new DataStore();
       ds.connect();
       Job aJob = new Job(1, "today", "bye");
       ds.addJobEntry(aJob);
    }

This works fine. HOWEVER, when i invoke the same operation in my servlet using:

      public void doPost(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
            try {
                  response.setContentType("application/x-java-serialized-object");
                  InputStream in = request.getInputStream();
                  ObjectInputStream inputFromApplet = new ObjectInputStream(in);
                  Job newJob = (Job) inputFromApplet.readObject();
                        inputFromApplet.close();
                       
                        //add to database
                        ds = new DataStore();
                        ds.connect();        
                        ds.addJobEntry(newJob);
                       
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }

It doesnt seem to add the entry to the database!!! PLEASE HELP

Any advice or help will be greatly appreciated

Regards.
0
ACEAFTY
Asked:
ACEAFTY
  • 17
  • 16
  • 4
  • +1
1 Solution
 
ACEAFTYAuthor Commented:
I think its somthing to do with my SQL driver, i am using Apache tomcat, where must i put the driver classes ?
0
 
CEHJCommented:
>>
                     //add to database
                       ds = new DataStore();
                       ds.connect();        
                       ds.addJobEntry(newJob);
>>

This looks wrong, you wouldn't want to create a new connection every time for optimal use, but if you're  going to do that, you'll need to close it too
0
 
CEHJCommented:
Check the references to those objects you're using by printing them and look in the log file
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
limaidealCommented:
Put SQl driver in WEB-INF/lib directory, restart tomcat and see what happens
also can you check log file see if there's any error message dunmpped in?
0
 
ACEAFTYAuthor Commented:
nope doesnt work if i do put the *.jar file in the lib folder

this is what im using:
Class.forName("com.mysql.jdbc.Driver");
0
 
CEHJCommented:
Check for exceptions in your log file
0
 
ACEAFTYAuthor Commented:
classNotFound
0
 
ACEAFTYAuthor Commented:
i cant get the applet to locate the driver ive tried puttin it everywhere!!
if i put it in http://localhost:8080/JobApp/WEB-INF/lib

what would  Class.forName("com.mysql.jdbc.Driver");  be?
0
 
CEHJCommented:
Try putting it in

%CATALINA_HOME%\common\lib

too


0
 
ACEAFTYAuthor Commented:
does that mean i have to change this Class.forName("com.sql.jdbc.Driver"); if i put it wer you just told me to put it? because it still doesnt work! i put
mysql-connector-java-3.1.8a-bin.jar in there this is driving me crazy!!
0
 
ACEAFTYAuthor Commented:
this is what im getting!

network: Connecting http://localhost:8080/com/mysql/jdbc/Driver.class with proxy=DIRECT
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
      at sun.applet.AppletClassLoader.findClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      at sun.applet.AppletClassLoader.loadClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      at java.lang.ClassLoader.loadClassInternal(Unknown Source)
      at java.lang.Class.forName0(Native Method)
      at java.lang.Class.forName(Unknown Source)
      at JobApp.DataStore.connect(DataStore.java:25)
 ETC......
0
 
CEHJCommented:
Ah i see it's being loaded by your applet. In that case put the driver jar in the archive tag:


<applet code="XXX" archive="mysql-connector-java-3.1.8a-bin.jar" ... etc

Make sure it's with the applet in its package root
0
 
ACEAFTYAuthor Commented:
ARGGGGHHH!!! Still not working!!!

this what i have done in ClientApplet.html

<HTML>
<HEAD>
   <TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>

<H3><HR WIDTH="100%">Job Client Applet<HR WIDTH="100%"></H3>

<P>
<APPLET codebase=.. code="JobApp/ClientApplet.class" archive="mysql-connector-java-3.1.8a-bin.jar" width=500 height=250></APPLET>
</P>

<HR WIDTH="100%"><FONT SIZE=-1><I>@author Rehan Uddin</I></FONT>
</BODY>
</HTML>
0
 
CEHJCommented:
>><APPLET codebase=..

better

<APPLET codebase=".."

Do you mean that by the way?

>>code="JobApp/ClientApplet.class"

If that applet's in the package 'JobApp' it should be

code="JobApp.ClientApplet.class"

0
 
CEHJCommented:
>>Do you mean that by the way?

As, if so, this:

>>archive="mysql-connector-java-3.1.8a-bin.jar"

should be

archive="../mysql-connector-java-3.1.8a-bin.jar"
0
 
ACEAFTYAuthor Commented:
ive tried both approaches still nothing!! it still cannot locate the driver for the db

0
 
CEHJCommented:
You'll have to get the paths right or it won't
0
 
ACEAFTYAuthor Commented:
i have put everythin everywhere!! and still not working!! is it possible to send u my files so u can check wot i am doing wrong?
0
 
CEHJCommented:
Not now sorry - it's 2 am here and i'm turning in!
0
 
aozarovCommented:
>> i cant get the applet to locate the driver ive tried puttin it everywhere!!
Why does the applet need the driver?
Where does the exception come from Tomcat (your servlet container) or your Applet?
Also, can you make sure that your jar is not corupt?
do: jar tf  mysql-connector-java-3.1.8a-bin.jar ( and search for an entry com/sql/jdbc/Driver.class)
0
 
ACEAFTYAuthor Commented:
The driver class exits, sorry i mean i want to load the driver in the servlet when i do a get post so i can add a new entry to the sql database
0
 
CEHJCommented:
If the applet is not making a direct connection to the db then it doesn't need the driver. If the driver is only used by the servlet, then putting it into WEB-INF/lib should be sufficient. From the previous stack trace it appeared that the applet was loading the driver
0
 
ACEAFTYAuthor Commented:
ok i will try it
0
 
ACEAFTYAuthor Commented:
where is the log file situated for tomcat?
0
 
CEHJCommented:
$CATALINA_HOME/logs/catalina.out
0
 
ACEAFTYAuthor Commented:
this is what i get in catalina.... . txt file

04-May-2005 19:31:33 org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
04-May-2005 19:31:33 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1360 ms
04-May-2005 19:31:33 org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
04-May-2005 19:31:33 org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/5.5.9
04-May-2005 19:31:33 org.apache.catalina.core.StandardHost start
INFO: XML validation disabled
04-May-2005 19:31:35 org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
04-May-2005 19:31:36 org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
04-May-2005 19:31:36 org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/47  config=null
04-May-2005 19:31:36 org.apache.catalina.storeconfig.StoreLoader load
INFO: Find registry server-registry.xml at classpath resource
04-May-2005 19:31:36 org.apache.catalina.startup.Catalina start
INFO: Server startup in 3343 ms

and this is what im doing:
      public void doPost(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
            try {
                  response.setContentType("application/x-java-serialized-object");
                  InputStream in = request.getInputStream();
                  ObjectInputStream inputFromApplet = new ObjectInputStream(in);
                  Job newJob = (Job) inputFromApplet.readObject();
                        inputFromApplet.close();
                    try{    
                        //add to database
                        ds = new DataStore();
                        ds.connect();        
                        ds.addJobEntry(newJob);
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                   
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }

the *.jar file is in the lib and everywhere i can think ov what am i doing wrong or not doing?
0
 
aozarovCommented:
I assume you still get the class not found exception triggered from (new DataStore), right?
Can you post the code for it?
Did you try to configure/user Tomcat DS instead of loading the driver yourself -> see: http://jakarta.apache.org/tomcat/tomcat-5.5-doc/jndi-datasource-examples-howto.html
0
 
CEHJCommented:
That looks like the wrong logfile. Try this:


System.err.println("SEARCHFORME");

then look for that String in the file system
0
 
ACEAFTYAuthor Commented:
yes i tried that! this is my datastore code:

public class DataStore extends Thread{
    private Connection conn;
    /** Creates a new instance of DataStore */
   
    public void connect(){
        try {  
           // Step 1: Load the JDBC driver.  
           Class.forName("com.mysql.jdbc.Driver");

            // Step 2: Establish the connection to the database.  
            String url = "jdbc:mysql://localhost:3306/jobdb";  
            conn = DriverManager.getConnection(url,"root","password");
            Statement st = conn.createStatement();
        } catch (Exception e) {  
            e.printStackTrace();
        }

    }
    public void createTable(){
       
    }
   
    public void addJobEntry(Job addJob){
        String insert = "INSERT INTO jobtable " + "VALUES (?)";
        try {
        PreparedStatement ps = conn.prepareStatement(insert);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bout);
        out.writeObject(addJob);
        byte[] bytes = bout.toByteArray();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ps.setBinaryStream(1, in, bytes.length);
        ps.executeUpdate();
        } catch (Exception e) {  
            e.printStackTrace();
        }
    }
   
    public ArrayList getJobList(){
        ArrayList jobList = new ArrayList();
        int i = 0;
        String query = "SELECT Job FROM jobtable";
        try{
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
           
            while (rs.next()){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                InputStream in = rs.getBinaryStream(1);
                int buf = -1;  
               
                while ((buf = in.read()) > -1) {
                    out.write(buf);
                }
               
                in.close();
                ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
                Object retrievedObject = ois.readObject();
                Job recievedJob = (Job) retrievedObject;
                jobList.add(i, recievedJob);
                i++;
            }
        } catch (Exception e) {  
            e.printStackTrace();
        }
            return jobList;
    }
   
    public void updateJob(Job oldJob, Job newJob){
        String query = "SELECT * FROM jobtable";
        try{
            Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            ResultSet rs = stmt.executeQuery(query);
           
            while (rs.next()){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                InputStream in = rs.getBinaryStream(1);
                int buf = -1;  
               
                while ((buf = in.read()) > -1) {
                    out.write(buf);
                }
               
                in.close();
                ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
                Object retrievedObject = ois.readObject();
                Job recievedJob = (Job) retrievedObject;
                if ((recievedJob.getJobNumber()) == (oldJob.getJobNumber())){
                    rs.deleteRow();
                    addJobEntry(newJob);
                }
            }
        } catch (Exception e) {  
            e.printStackTrace();
        }
    }
0
 
ACEAFTYAuthor Commented:
0
 
CEHJCommented:
>> yes i tried that!

An the result was ...?
0
 
aozarovCommented:
Did you try adding the jar to your war WEB-INF/lib?
Did you check if the jar is not corrupted?
Did you try using the Tomcat DS aproach instead?
0
 
ACEAFTYAuthor Commented:
>>Did you try adding the jar to your war WEB-INF/lib?
yes
>>Did you check if the jar is not corrupted?
yes downloaded fresh copy n checked and Driver does exist

>>Did you try using the Tomcat DS aproach instead?
Yes dont knw if what i did is correct this is my server.xml file

<Context path="/JobApp" docBase="JobApp"      ************** have i got this correct? the name of my folder is JobApp and the name ov my package is JobApp
        debug="5" reloadable="true" crossContext="true">

  <Logger className="org.apache.catalina.logger.FileLogger"
             prefix="localhost_DBTest_log." suffix=".txt"
             timestamp="true"/>

  <Resource name="jdbc/JobApp"
               auth="Container"
               type="javax.sql.DataSource"/>

  <ResourceParams name="jdbc/JobApp">
    <parameter>
      <name>factory</name>
      <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>

    <!-- Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to 0 for no limit.
         -->
    <parameter>
      <name>maxActive</name>
      <value>100</value>
    </parameter>

    <!-- Maximum number of idle dB connections to retain in pool.
         Set to -1 for no limit.  See also the DBCP documentation on this
         and the minEvictableIdleTimeMillis configuration parameter.
         -->
    <parameter>
      <name>maxIdle</name>
      <value>30</value>
    </parameter>

    <!-- Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->
    <parameter>
      <name>maxWait</name>
      <value>10000</value>
    </parameter>

    <!-- MySQL dB username and password for dB connections  -->
    <parameter>
     <name>username</name>
     <value>root</value>
    </parameter>
    <parameter>
     <name>password</name>
     <value>password</value>
    </parameter>
   
    <!-- Class name for the official MySQL Connector/J driver -->
    <parameter>
       <name>driverClassName</name>
       <value>com.mysql.jdbc.Driver</value>
    </parameter>
   
    <!-- The JDBC connection url for connecting to your MySQL dB.
         The autoReconnect=true argument to the url makes sure that the
         mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
         connection.  mysqld by default closes idle connections after 8 hours.
         -->
    <parameter>
      <name>url</name>
      <value>jdbc:mysql://localhost:3306/jobdb?autoReconnect=true</value>
    </parameter>
  </ResourceParams>
</Context>

      </Host>

    </Engine>

  </Service>

</Server>


0
 
aozarovCommented:

<Context path="/JobApp" docBase="JobApp"      ************** have i got this correct? the name of my folder is JobApp and the name ov my package is JobApp
        debug="5" reloadable="true" crossContext="true">

docBase="/JobApp" -> this should be the full path to your web application.
path="/JobApp" -> this is the web application context name: probably should be path="JobApp"
see: http://jakarta.apache.org/tomcat/tomcat-5.5-doc/config/context.html
0
 
CEHJCommented:
Before you go any further, i'd get your logging organised, or you're not going to be able to diagnose anything...
0
 
ACEAFTYAuthor Commented:
where is my log? where should i b looking?
0
 
CEHJCommented:
>> where is my log?

That's the point - you need to find out. If it's configured you should be able to search the file system to find it. If it isn't you need to configure it. See your Tomcat docs
0
 
CEHJCommented:
:-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 17
  • 16
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now