servlet中的con.createStatement()中的NullPointerException

时间:2014-02-05 07:05:13

标签: eclipse nullpointerexception

我正在使用eclipse kepler IDE。 我得到了java.lang.nullpointerexception,我知道原因,因为我在con对象中得到null而con用于调用抛出此异常的方法createStatement()。 我想知道为什么这个con对象通过getAttribute()方法从 MyListener.java 访问null。 我创建了msaccess DB和名为 servletTest 的数据源。但我不知道 为什么con正在访问null,这就是为什么它会给出异常。 例外如下:

Feb 05, 2014 11:48:12 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre8/bin/client;C:/Program Files/Java/jre8/bin;C:/Program Files/Java/jre8/lib/i386;C:\Windows\System32;C:\Program Files\Java\jdk1.8.0\bin;C:\Users\praveen\Desktop\eclipse;;.
Feb 05, 2014 11:48:12 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:advanced java' did not find a matching property.
Feb 05, 2014 11:48:12 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Feb 05, 2014 11:48:12 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Feb 05, 2014 11:48:12 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1175 ms
Feb 05, 2014 11:48:12 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Feb 05, 2014 11:48:12 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.50
Feb 05, 2014 11:48:14 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Feb 05, 2014 11:48:14 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Feb 05, 2014 11:48:14 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1189 ms
java.lang.NullPointerException
    at com.student.servletcontextevent.FetchData.doGet(FetchData.java:47)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:744)

**inde.html**
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="FetchData">fetch records</a>
</body>
</html>

**FetchData**
package com.student.servletcontextevent;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FetchData
 */
@WebServlet("/FetchData")
public class FetchData extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FetchData() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        try {
            // Retrieving connection object from ServletContext object
            ServletContext ctx = getServletContext();
            Connection con = (Connection) ctx.getAttribute("mycon");

            // retieving data from emp table
            Statement ps = con.createStatement();
            ResultSet rs = ps.executeQuery("Select * from emp");

                        while (rs.next()) {
                out.print("<br>" + rs.getString(1) + " " + rs.getString(2));
            }


            con.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        out.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

**MyListener**
package com.student.servletcontextevent;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyListener
 */
@WebServlet("/MyListener")
public class MyListener extends HttpServlet implements ServletContextListener {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyListener() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
    }

    /**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent event) {
        // TODO Auto-generated method stub
        try{  
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String dataSourceName = "servletTest";
            String dbUrl = "jdbc:odbc:" + dataSourceName;
            Connection con=DriverManager.getConnection(dbUrl);  

            //storing connection object as an attribute in ServletContext  
            ServletContext ctx=event.getServletContext();  
            ctx.setAttribute("mycon", con);  

            }catch(Exception e){e.printStackTrace();}  

    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

3 个答案:

答案 0 :(得分:0)

您的侦听器类不应该扩展HttpServlet,因为它不是servlet,而只是ServletContextListener。因此,它应该用@WebListener注释,而不是@WebServlet。

也就是说,你不应该在你的webapp中使用单个数据库连接,因为很明显,如果同时处理两个请求,两者都将使用相同的连接,因此无法正确地进行事务处理。

阅读servlet容器的文档,了解如何正确创建DataSource并从servlet访问它(请参阅http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html了解Tomcat)。每个请求处理方法都应从DataSource获取连接,使用它,然后关闭连接。此外,不要使用JDBC / ODBC桥,这是错误的,缓慢的和完全过时的。将JDBC驱动程序用于数据库。如今,地球上的每个数据库都有一个JDBC驱动程序。

要完成的注意事项:无论是使用Eclipse,NetBeans还是记事本编写代码,都与在运行时,在Web容器中执行代码后获得的异常无关。 IDE与您的问题完全无关。

答案 1 :(得分:0)

您确定可以连接到您的数据库吗? 我的猜测是'con'在FetchData servlet中为null,因为在连接到数据库时MyListener中抛出异常,或者根本不使用MyListener。 实际上,数据库连接不应该在您的应用程序中以编程方式进行管理,如果你谷歌搜索'tomc1t database jndi',你应该找到一个很棒的教程。

答案 2 :(得分:0)

只需添加更多 @JB Nizet的正确答案..

数据库连接上空指针异常的原因:

1)无法访问数据库。

2)数据库访问可能需要提供或不正确的用户名和密码。

3)数据库名称/网址错误。

只是一些建议:

1)为什么要在监听器中创建连接对象?您可以在单独的java文件中创建它们并访问servlet中的那些文件而不是侦听器。

2)为什么要在servlet上下文中保存连接对象(con)?对我没有任何意义。由于您确定您的应用程序使用单个数据库,您可以使连接对象保持静态,并且您只能通过类名访问它。