Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > mysql-connector + Tomcat


Автор: initmax 19.3.2010, 14:52
Доброго, возникла проблема подключения к БД MySQL к серверу Tomcat который запущен как отдельное прижение

вот  собственно сам сервтел:

Код

/*
 * Class is the start poitn to start web-application
 */
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Statement;
import java.sql.ResultSet;

public class indexServlet extends HttpServlet {

//Connected MySQL

    private String url = "jdbc:mysql://127.0.0.1:3306/initmax"+"?autoReconnect=true&useUnicode=true&characterEncoding=utf8"+
              "&SET NAMES utf8";
    private String name = "root";
    private String password = "mypass";
     
    private Connection currentConnect;
    
    public void initDisconnection(){
        try {
            currentConnect.close();
         }
         catch (SQLException e) {
                e.printStackTrace();
         }
    }

    public void initConnection(){
//FIRST register and download driver
        try {
            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        
        try{
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException e){
            e.printStackTrace();
        }

//SECOND Connect to database
        try {
                currentConnect = DriverManager.getConnection(url, name, password);
        }
        catch (SQLException e) {
                e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        initConnection();   
        PrintWriter out = response.getWriter();

         try {
             Statement st = (Statement) currentConnect.createStatement();
             String query = ("select * from up_menu");
             ResultSet resultQuery = null;
             resultQuery = st.executeQuery(query);

//step in cycle after execution query, and create Vector object
             while (resultQuery.next()) {
                 out.println(resultQuery.getString("theme"));       
             }
             out.close();
         }
         catch (SQLException e) {
             e.printStackTrace();
         }        
        initDisconnection();
    }
}


если запускаю данный сервлет из NetBeans всё работает отлично, т.е. в браузер получаю вывод из БД,
если переношу данный откомпилированный сервлет на отдельностоящий запущенный Tomcat, то получаю следующую ошибку

Код

java.lang.NullPointerException
    indexServlet.doGet(indexServlet.java:80)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
    java.security.AccessController.doPrivileged(Native Method)
    javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
    org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
    org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)


В каталог 
/usr/share/tomcat5.5-webapps/initMaxTest/WEB-INF/lib# ls
пробовал подкладывать разные версии драйверов
mysql-connector-java-3.1.14-bin.jar 
mysql-connector-java-5.1.6-bin.jar
результат не изменился.
пароль подключения к БД и наличие БД == true

такое впечатление что не срабатывает драйвер подключения mysql-connector-java
кто что может подсказать?




Автор: batigoal 19.3.2010, 15:19
Добавь логирующих сообщений. Крепко подозреваю, что вот этот блок валится:

Код

try {
                currentConnect = DriverManager.getConnection(url, name, password);
        }
        catch (SQLException e) {
                e.printStackTrace();
        }

, но в результате e.printStackTrace() ничего не выводит в лог сервера. Ну а потом при обращении к currentConnect уже следует NPE.

Автор: MaxPayneC 19.3.2010, 16:12
Код

DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());


Это не mysql jdbc драйвер ни разу. Нормальный драйвер это com.mysql.jdbc.Driver.

Еще возможно проблема в том, что у вас осуществлен импорт стейтмента из пакета с дровами mysql. Попробуйте его убрать и работать со стандартными jdbc-стейтементами.

Автор: initmax 22.3.2010, 10:45
Да, но как не странно NetBeans очень успешно использует 
mysql-connector-java-3.1.14-bin.jar что править?

Автор: MaxPayneC 22.3.2010, 11:17
Джар заменить на свежий, из кода класса убрать импорт, о котором я говорил выше.

Автор: initmax 22.3.2010, 23:18
Переписал,
права на каталог с сервлетом == chmod -R 777

Код

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

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

public class indexServlet extends HttpServlet {
      private String url = "jdbc:mysql://127.0.0.1:3306/initmax"+"?autoReconnect=true&useUnicode=true&characterEncoding=utf8"+
              "&SET NAMES utf8";
    private String login = "root";
    private String password = "mypass";
    private Connection currentConnect;

    public void initDisconnection() throws Exception {
        currentConnect.close();
    }

    public void initConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        currentConnect = DriverManager.getConnection(url, login, password);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            initConnection();
            PrintWriter out = response.getWriter();
            Statement st = currentConnect.createStatement();
            String query = ("select * from up_menu");
            ResultSet resultQuery = st.executeQuery(query);
            
            while (resultQuery.next()) {
                out.println(resultQuery.getString("theme"));
            }
            
            out.close();
        }

        catch (Exception e) {
            throw new ServletException(e);
        }


        finally {
            try {
                initDisconnection();
            }
            catch (Exception e) {
                throw new ServletException(e);
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}


Ошибка такая же:
Код

java.lang.NullPointerException
    indexServlet.doGet(indexServlet.java:80)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
    java.security.AccessController.doPrivileged(Native Method)
    javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
    org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
    org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)


уже в шоке...

Автор: jk1 22.3.2010, 23:23
Цитата

indexServlet.doGet(indexServlet.java:80)


А ведь указанный вами класс меньше 80 строк. Редеплой приложения на сервер точно происходит?

Автор: initmax 23.3.2010, 10:10
Прошу прощения за копипаст старой ошибки, в новом листинге всё выглядит так:

Цитата

javax.servlet.ServletException
    indexServlet.doGet(indexServlet.java:55)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
    java.security.AccessController.doPrivileged(Native Method)
    javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
    org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
    org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)


java.lang.NullPointerException
    indexServlet.initDisconnection(indexServlet.java:22)
    indexServlet.doGet(indexServlet.java:52)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
    java.security.AccessController.doPrivileged(Native Method)
    javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
    org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
    org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)










Строках 22 и 55 выделены красным

public void initDisconnection() throws Exception {
        currentConnect.close();
    }

-------

   finally {
            try {
                initDisconnection();
            }
            catch (Exception e) {
   throw new ServletException(e); 
            }
        }
    }

Автор: initmax 23.3.2010, 12:31
Проблема решилась после переустановки Java и запуска Tomcat 6 вместо Tomcat 5.5. всем спасибо за участие!!!

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)