由于classnotfoundexception和nullpointerexception,无法连接到数据库

时间:2015-11-22 17:41:14

标签: java

我正在尝试连接我的数据库。当我运行项目并尝试输入用户名和密码时,我收到以下错误:

Nov 22, 2015 10:56:29 PM com.dts.core.util.LoggerManager writeLogWarning
WARNING: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
    at com.dts.core.util.LoggerManager.writeLogWarning(LoggerManager.java:62)
    at com.dts.core.dao.AbstractDataAccessObject.getConnection(AbstractDataAccessObject.java:51)
    at com.dts.dae.dao.SecurityDAO.<init>(SecurityDAO.java:23)
    at org.apache.jsp.LoginAction_jsp._jspService(LoginAction_jsp.java:124)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

java.lang.NullPointerException
    at com.dts.dae.dao.SecurityDAO.loginCheck(SecurityDAO.java:93)
    at org.apache.jsp.LoginAction_jsp._jspService(LoginAction_jsp.java:124)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

以下是相应的java代码

LoggerManager.java

package com.dts.core.util;

import java.io.File;
import java.io.PrintStream;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class LoggerManager {
    public static Logger logger = Logger.getLogger(LoggerManager.class.getName());;

    LoggerManager() throws InstantiationException {
        throw new InstantiationException("This is an util class and should not be instantiated.");
    }

    public static Logger getLogger(String file) {
        String dir = file.substring(0, file.lastIndexOf("/"));
        System.out.println("-----dir----" + dir);
        if (logger == null) {
            logger = Logger.getLogger("LoggerManager");
        }
        try {
            File f = new File(dir);
            boolean success = f.exists();

            if (!success) {
                success = f.mkdir();
            }
            LogManager lm = LogManager.getLogManager();
            FileHandler fh = new FileHandler(file, true);
            logger = Logger.getLogger("LoggerManager");
            logger.setUseParentHandlers(false);
            lm.addLogger(logger);
            logger.setLevel(Level.INFO);
            fh.setFormatter(new SimpleFormatter());
            logger.addHandler(fh);

        } catch (Exception e) {

            logger.log(Level.INFO, e.toString(), e.fillInStackTrace());
        }
        return logger;
    }

    public static void writeLogInfo(Exception e) {
        logger.log(Level.INFO, e.toString(), e.fillInStackTrace());
    }

    public static void writeLogSevere(Exception e) {
        logger.log(Level.SEVERE, e.toString(), e.fillInStackTrace());
    }

    public static void writeLogWarning(Exception e) {
        logger.log(Level.WARNING, e.toString(), e.fillInStackTrace());
    }

    public static void writeLogInfo(String info) {
        logger.log(Level.INFO, info);
    }

    public static void writeLogSevere(String severe) {
        logger.log(Level.SEVERE, severe);
    }

    public static void writeLogWarning(String warning) {
        getLogger(warning).log(Level.WARNING, warning);
    }
}

数据库连接java代码如下:

AbstractDataAccessObject.java

package com.dts.core.dao;
import com.dts.core.util.LoggerManager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class AbstractDataAccessObject {
    Connection con;
    static Properties props;
    public AbstractDataAccessObject() {}
    public Properties getProperties() {
        return props;
    }
    public void setProperties(Properties props) {
        AbstractDataAccessObject.props = props;
    }
    public Connection getConnection() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "Bug", "dog567");
        } catch (ClassNotFoundException cnf) {
            LoggerManager.writeLogWarning(cnf);
        } catch (SQLException se) {
            LoggerManager.writeLogWarning(se);
        }
        return con;
    }
    public int getSequenceID(String tableName, String pkid) {
        int id = 0;
        try {
            con = getConnection();
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select max(" + pkid + ") from " + tableName);
            if (rs.next()) id = rs.getInt(1);
            id++;
        } catch (SQLException se) {
            LoggerManager.writeLogWarning(se);
            try {
                con.close();
            } catch (SQLException se1) {
                LoggerManager.writeLogWarning(se1);
            } catch (Exception e) {
                LoggerManager.writeLogWarning(e);
            }
        } catch (Exception e) {
            LoggerManager.writeLogWarning(e);
            try {
                con.close();
            } catch (SQLException se) {
                LoggerManager.writeLogWarning(se);
            } catch (Exception e1) {
                LoggerManager.writeLogWarning(e1);
            }
        } finally {
            try {
                con.close();
            } catch (SQLException se) {
                LoggerManager.writeLogWarning(se);
            } catch (Exception e) {
                LoggerManager.writeLogWarning(e);
            }
        }
        return id;
    }

SecurityDAO.java

package com.dts.dae.dao;

import com.dts.core.dao.AbstractDataAccessObject;
import com.dts.core.util.DateWrapper;
import com.dts.core.util.LoggerManager;
import com.dts.dae.model.Profile;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

public class SecurityDAO
 extends AbstractDataAccessObject {
    Connection con;
    private String desc;
    private boolean flag;

    public SecurityDAO() {
        con = getConnection();
    }



    public boolean checkPassword(Profile regbean) {
        String loginid = regbean.getLoginID();
        String oldpassword = regbean.getPassword();

        try {
            PreparedStatement pst = con.prepareStatement("select * from logindetails where password=? and loginname=?");
            pst.setString(1, oldpassword);
            pst.setString(2, loginid);
            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
                flag = true;
                LoggerManager.writeLogInfo("Login Success");
            } else {
                flag = false;
            }
        } catch (SQLException ex) {
            LoggerManager.writeLogSevere(ex);
            LoggerManager.writeLogInfo("Database Connection problem");
            flag = false;
        }
        return flag;
    }


    public int checkFirstLogin(String loginname) {
        int fstatus = 2;

        try {
            con.setAutoCommit(true);
            PreparedStatement pst = con.prepareStatement("select firstlogin from logindetails where loginname=?");
            pst.setString(1, loginname);
            ResultSet rs = pst.executeQuery();

            if (rs.next()) {
                fstatus = rs.getInt(1);
            }
            con.close();
        } catch (SQLException ex) {
            LoggerManager.writeLogSevere(ex);
            LoggerManager.writeLogInfo("Database Connection problem");
            flag = false;
        }
        return fstatus;
    }


    public String loginCheck(Profile regbean) {
        String loginid = regbean.getLoginID();
        String password = regbean.getPassword();
        String role = "";
        try {
            con.setAutoCommit(true);
            PreparedStatement pst = con.prepareStatement("select logintype from logindetails where password=? and loginname=? and loginstatus=1");
            pst.setString(2, loginid);
            pst.setString(1, password);

            ResultSet rs = pst.executeQuery();
            if (rs.next()) {


                role = rs.getString(1);
                desc = "Login Success";
            } else {
                flag = false;
                desc = "Entered Invalid password";
            }

        } catch (SQLException ex) {
            LoggerManager.writeLogSevere(ex);
            desc = "Database Connection problem";
            flag = false;
        }
        loginaudit(loginid, desc);
        return role;
    }



    public void loginaudit(String loginid, String desc) {
        try {
            String newdate = DateWrapper.parseDate(new Date());
            PreparedStatement pst = con.prepareStatement("insert into loginaudit values(?,?,?)");
            pst.setString(1, loginid);
            pst.setString(2, newdate);
            pst.setString(3, desc);
            int i = pst.executeUpdate();
            if (i == 1) {
                con.commit();
            } else con.rollback();
            con.close();
        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException ex) {
                LoggerManager.writeLogSevere(ex);
            }
            e.printStackTrace();
        }
    }


    public boolean changePassword(Profile regbean) {
        String loginid = regbean.getLoginID();
        String oldpassword = regbean.getPassword();
        String newpassword = regbean.getNewPassword();
        try {
            con.setAutoCommit(false);
            String newdate = DateWrapper.parseDate(new Date());
            PreparedStatement pst = con.prepareStatement("UPDATE logindetails SET password=?,passmodifieddate=? WHERE loginname=? and password=?");

            pst.setString(1, newpassword);
            pst.setString(2, newdate);
            pst.setString(3, loginid);
            pst.setString(4, oldpassword);

            int i = pst.executeUpdate();
            if (i == 1) {
                flag = true;
                con.commit();
            } else {
                flag = false;
                con.rollback();
            }
            con.close();
        } catch (SQLException ex) {
            LoggerManager.writeLogSevere(ex);
            flag = false;
            try {
                con.rollback();
            } catch (SQLException sex) {
                LoggerManager.writeLogSevere(sex);
            }

        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            try {
                con.rollback();
            } catch (SQLException sex) {
                LoggerManager.writeLogSevere(sex);
            }
        }
        return flag;
    }



    public boolean changeQuestion(Profile regbean) {
        String loginid = regbean.getLoginID();
        String password = regbean.getPassword();
        int secretquestid = regbean.getSecretQuestionID();
        String ownsecretquest = regbean.getOwnSecretQuestion();
        String secretans = regbean.getSecretAnswer();


        int i = 0;
        try {
            con.setAutoCommit(false);
            if (checkPassword(regbean)) {
                if (secretquestid == 0) {
                    Statement st = con.createStatement();
                    ResultSet rs = st.executeQuery("select (max(questionid))+1 from questionbase");

                    if (rs.next()) secretquestid = rs.getInt(1);
                    PreparedStatement pst = con.prepareStatement("INSERT INTO question_base VALUES(?,?)");

                    pst.setInt(1, secretquestid);
                    pst.setString(2, ownsecretquest);

                    pst.executeUpdate();
                }

                PreparedStatement pst = con.prepareStatement("UPDATE logindetails SET squestionid=?,sanswer=? WHERE loginname=? and password=?");

                pst.setInt(1, secretquestid);
                pst.setString(2, secretans);
                pst.setString(3, loginid);
                pst.setString(4, password);

                i = pst.executeUpdate();
                if (i == 1) {
                    flag = true;
                    con.commit();
                } else {
                    flag = false;
                    con.rollback();
                }
            }
            con.close();
        } catch (SQLException ex) {
            LoggerManager.writeLogSevere(ex);
            flag = false;
            try {
                con.rollback();
            } catch (SQLException sex) {
                LoggerManager.writeLogSevere(sex);
            }
        } catch (Exception e) {
            LoggerManager.writeLogSevere(e);
            flag = false;
            try {
                con.rollback();
            } catch (SQLException sex) {
                LoggerManager.writeLogSevere(sex);
            }
        }
        return flag;
    }



    public String recoverPasswordByExistQuestion(Profile regbean) {
        String loginid = regbean.getLoginID();
        int secretquestid = regbean.getSecretQuestionID();
        String secretans = regbean.getSecretAnswer();
        String password;
        try {
            con.setAutoCommit(true);
            PreparedStatement pst = con.prepareStatement("SELECT password FROM logindetails  WHERE loginname=? and squestionid=? and sanswer=?");

            pst.setString(1, loginid);
            pst.setInt(2, secretquestid);
            pst.setString(3, secretans);

            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
                password = rs.getString(1);
            } else password = "";
            con.close();
        } catch (SQLException ex) {
            LoggerManager.writeLogSevere(ex);
            password = "";
        } catch (Exception e) {

            LoggerManager.writeLogSevere(e);
            password = "";
        }
        return password;
    }




    public String recoverPasswordByOWNQuestion(Profile regbean) {
        String loginid = regbean.getLoginID();
        String ownsecretquest = regbean.getOwnSecretQuestion();
        String secretans = regbean.getSecretAnswer();
        String password;
        try {
            con.setAutoCommit(true);
            PreparedStatement pst = con.prepareStatement("SELECT password FROM logindetails  WHERE loginname=? and squestionid=(select questionid from questionbase where questiondetails=?) and sanswer=?");

            pst.setString(1, loginid);
            pst.setString(2, ownsecretquest);
            pst.setString(3, secretans);


            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
                password = rs.getString(1);
            } else password = "";
            con.close();
        } catch (SQLException ex) {
            LoggerManager.writeLogSevere(ex);
            password = "";
        } catch (Exception e) {

            LoggerManager.writeLogSevere(e);
            password = "";
        }
        return password;
    }

在SecurityDAO.java中,我在con.setAutoCommit(true)获得nullpointerexception;

1 个答案:

答案 0 :(得分:0)

shadowing变量con。取代

Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","Bug","dog567");

con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","Bug","dog567");
如果要从con方法的范围返回变量,请在try-catch块之前

或声明getConnection