Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / January 2006

Tip: Looking for answers? Try searching our database.

komische NullPointerException in Servlet

Thread view: 
Sebastian Berger - 09 Jan 2006 14:43 GMT
Hi,

ich schreibe derzeit ein kleines Servlet, das mittles OJDBC auf eine
Oracle-Datenbank zugreifen will.

Zuerst habe ich den Code als simpele Java-Application geschrieben, und
dort funktioniert alles ganz wundervoll. Nun, seitdem ich versuche, das
ganze in ein Servlet zu integrieren, erhalte ich ständig
NullPointerExceptions. Hier ist mein Code:
import java.io.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class OJDBCServlet extends HttpServlet
{
    public Connection conn;
    public Statement stmt;

   public void doGet(HttpServletRequest request, HttpServletResponse
response)
   throws IOException, ServletException
   {
       initDB(response);

    PrintWriter out = response.getWriter();
       out.println("<html>");
       out.println("<head>");
       out.println("<title>Hello World!</title>");
       out.println("</head>");
       out.println("<body>");
       out.println("<h1>Hello World!</h1>");
       out.println("<h1>"+(time2-time1)+"</h1>");
       out.println("</body>");
       out.println("</html>");
   }

   private void initDB(HttpServletResponse response) throws
ServletException
   {
        PrintWriter out = null;

        // prepare ojdbc
       try
       {
           out = response.getWriter();

DriverManager.registerDriver((Driver)(Class.forName("oracle.jdbc.driver.OracleDriver").newInstance()));

           conn = DriverManager.getConnection
("jdbc:oracle:thin:@129.178.12.240:1521:test",
                                                "test_user", "passw");

           if(conn == null)
               out.println("error02");

            // context to call sql-statements (reusable)
            stmt = conn.createStatement();

            if(stmt == null)
               out.println("error03");

       }
       catch (SQLException e)
       {
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       if(conn == null)
           out.println("error04");
       if(stmt == null)
           out.println("error05");

            // Hier tritt die exception auf
       try
       {
           ResultSet rset = stmt.executeQuery(sqlStatement);
        }
       catch (SQLException e)
       {
           System.out.println("Error in SQL-Statement: ");
           System.out.println(sqlStatement);
            e.printStackTrace();
        }
    }
}

Nachdem in initDB der try-Bereich verlassen wurde, erhalte ich
Ausgaben: error04 und error05; im try-Block sind die Variablen conn und
stmt noch "korrekt" initialisiert, nur scheinbar verlieren sie ihre
Gültigkeit, sobald der try-Block verlassen wird.

Hat irgendjemand eine Idee??

Vielen, tausend Dank für eure Hilfen,
Sebastian
Sebastian Berger - 09 Jan 2006 14:46 GMT
Sorry, I didn't recognize, that this is an english newsgroup, cause I
am new to google news.

Sorry, for that!
impaler - 09 Jan 2006 14:57 GMT
what's the exact error ?

It might be that the servlet can't get the connector jar file and you
have to make it available.
What is the server you are using?
For tomcat for example try to copy the jar file into the /server/lib
directory and restart the server or even better, copy it into the
WEB-INF/lib folder of your webapp.

Viel glück und willkommen
nikita777@web.de - 09 Jan 2006 15:25 GMT
Hi,

i think you have a NullpointeException in this line:
DriverManager.registerDriver((Driver)(Class.forName("oracle.jdbc.driver.Ora­cleDriver").newInstance()));

Class.forName returns null and newInstance() makes the Exception.

Do, what impaler said. Make the Driver available for your application,
while putting the jar into the global classpath or
(dirty for a JDBCDriver-jar) put it in your web-inf/lib directory of
your war-file.

Greetings

Joe
Malte Christensen - 09 Jan 2006 16:17 GMT
> Nachdem in initDB der try-Bereich verlassen wurde, erhalte ich
> Ausgaben: error04 und error05; im try-Block sind die Variablen conn und
[quoted text clipped - 5 lines]
> Vielen, tausend Dank für eure Hilfen,
> Sebastian

Ich schlage vor, zunächst die beiden public Felter stmt und conn
woanders zu plaziere, zum Beis. in initDB(). Dieses um zu sehen, ob's
dann funktioniert. Ziemlich früh danach würde ich eine Java Klasse für's
Singleton Pattern entwerfen, und eine getConnection() dort rufen. Die
Klasse würde einen connection pool anbieten.

Damit bist du dir einigermassen sicher, dass die connections richtig
instantiert werden.

Dann, wo's notwendig ist (pseudokode!)

Connection conn = myClass.getConnection();
if (conn == null) { return; }

try {
    Statement stmt = conn.createStatement();

// dein Kode: wo wird sqlStatement deklariert/instantiert?
    String sqlStatement = "select ename, dept from scott.emp";
    ResultSet rset = stmt.executeQuery(sqlStatement);
    while rset.next() {
        whatever();
        // or return rset or an array to keep the interface clean.
    }
catch (SQLException sqle) {
    whatever();
}
finally {
    try {
        rset.close();
        stmt.close();
        myClass.closeConnection(conn);
    } catch (Exception e) {
        // safe to ignore;
    }

Oder so ungefähr.

Viel Glück!

Malte Christensen


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.