连接为空,但为什么

时间:2018-11-05 16:33:33

标签: java jdbc

在方法readAll()中,我的NullPointerException上有一个Connection,但是为什么,又该如何更改呢?

如果我使用主类对其进行测试,则一切正常,但是如果我在服务器(Web服务器-本地)上执行相同操作,则会抛出NullPointerException

这是我的ConnectionManager班:

public class ConnectionManager {

    private volatile static ConnectionManager connectionManager = null;
    private Connection connection = null;

    private ConnectionManager() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        DBProperties properties = DBProperties.getInstance();

        String url = properties.getStringProperty("databaseURL") + properties.getStringProperty("pathToDB") + properties.getStringProperty("urlSettings");
        String user = properties.getStringProperty("user");
        String passwort = properties.getStringProperty("password");

        try { // load driver
            Class.forName(properties.getStringProperty("dbDriver")).newInstance();
            connection = DriverManager.getConnection(url, user, passwort);
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized static ConnectionManager getInstance() throws SQLException {
        if (connectionManager == null) {
            try {
                connectionManager = new ConnectionManager();
            } catch (Exception ex) {
                Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return connectionManager;
    }

    public Connection getConnection() {
        return connection;
    }

    public static void closeConnection() {
        //close the connection only if there is a instance
        //--> closeConnection() can always be called. 
        //(e.g. if non JDBC-Dao's are used  --> ConnectionManager is not instantiated)
        if (connectionManager != null) {
            try {
                connectionManager.connection.close();
            } catch (SQLException ex) {
                Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}

这是抛出异常的JDBC类:

@Override
public List<User> readAll() {

    List<User> userList = new LinkedList<>();

    try (Statement statement = ConnectionManager.getInstance().getConnection().createStatement()){

        ResultSet result = statement.executeQuery("select * from Users");

        while(result.next()){
            int userID = Integer.valueOf( result.getString("UserID") );
            String firmenname = result.getString("Firmenname");
            boolean firma = Boolean.getBoolean( result.getString("Firma") );
            String vorname = result.getString("Vorname");
            String nachname = result.getString("Nachname");;
            int rollenID = Integer.valueOf( result.getString("RollenID") );
            String email = result.getString("Email");;
            String passwort = result.getString("Passwort");;
            String telefonnummer = result.getString("Telefonnummer");;
            String adresse = result.getString("Adresse");;
            int plz = Integer.valueOf( result.getString("PLZ") );
            String ort = result.getString("Ort");;

            userList.add( new User(userID, firmenname, firma, vorname, nachname, new Rolle(rollenID, "???", false, false, false, false, false, false), email, passwort, telefonnummer, adresse, plz, ort) );

        }
    } catch (SQLException ex) {
        Logger.getLogger(UserJDBCDAO.class.getName()).log(Level.SEVERE, null, ex);
    }

    return userList;
}

这是例外

java.lang.NullPointerException
at at.htlpinkafeld.langoscharly.dao.jdcb.UserJDBCDAO.readAll(UserJDBCDAO.java:68)
at at.htlpinkafeld.langoscharly.dao.factory.DAOFactory.readAllUser(DAOFactory.java:123)
at at.htlpinkafeld.langoscharly.service.LangosCharlyService.getUsers(LangosCharlyService.java:30)
at at.htlpinkafeld.langoscharly.gui.UserBean.getUsers(UserBean.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:97)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIData.getValue(UIData.java:732)
at org.primefaces.component.datatable.DataTable.getValue(DataTable.java:1002)
at org.primefaces.component.api.UIData.getDataModel(UIData.java:629)
at javax.faces.component.UIData.getRowCount(UIData.java:356)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:762)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:744)
at org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:258)
at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:220)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:84)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:456)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

1 个答案:

答案 0 :(得分:2)

很可能您有一个SQLException只能登录:

try { // load driver
    Class.forName(properties.getStringProperty("dbDriver")).newInstance();
    connection = DriverManager.getConnection(url, user, passwort);
} catch (SQLException ex) {
    Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
}

这里没有理由处理SQLException。您没有在ConnectionManager中的任何地方实现重新连接逻辑,如果您没有有效的连接,则应用程序将无法正常工作。您应该重新抛出它并让您的应用程序退出:

} catch (SQLException ex) {
    Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
    throw ex;
}