2015-02-09 39 views
0

请帮助我在servlet的 我想在init方法初始化值和 后使用它们,但我得到的NullPointerException 新的,这是我的CLASSE你好它含有2个方法init()和jdbcinfo() 我需要获取数据库连接,一旦java servlet如何从init()方法获取值并在方法外使用它们?

package com.Ws; 
    //imports..  
    public class Hello extends HttpServlet { 

     public static Connection con; 


     @Override 
     public void init() throws ServletException 
     { 





        try { 
        Class.forName("net.sourceforge.jtds.jdbc.Driver"); 
        con =DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:6543/Dbname","user",""); 


       } catch (ClassNotFoundException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
        System.out.println("--printStackTrace--"+e); 

       } catch (SQLException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
        System.out.println("--printStackTrace2--"+e); 
       } 
       } 


    } 
    //I get nullpointerexception here con = null 

     public String jdbcInfo(String req) { 

      PreparedStatement statementT; 

      try { 




    connection =con; 

       PreparedStatement statement = connection.prepareStatement(req); 
       ResultSet result = statement.executeQuery(); 

       while (result.next()) { 

        /// 

       } 
      } 

      catch (Exception e) { 
       e.printStackTrace(); 
       System.out.println("exception: Serveur base de donnée indosponnible"); 

      } 



      if (res == "1") 
       return res; 
      else 
       return "false"; 
     } 



     } 

我的web.xml

<servlet> 
    <servlet-name>Hello</servlet-name> 
    <servlet-class>com.Ws.Hello</servlet-class> 
    <load-on-startup>1</load-on-startup> 

</servlet> 
+2

您的代码不能编译。你不能在函数外面有'System.out.println(“返回值+名称);''。 – Jens 2015-02-09 12:26:10

+0

你不重写contextDestroyed(ServletContextEvent arg0)方法也是一个错误! – Prashant 2015-02-09 12:33:24

+1

和你在哪里得到异常? – Prashant 2015-02-09 12:37:54

回答

0

@ geert3是正确的。您不想创建连接并将其保存在servlet的init()方法的字段中。 Servlet是singletonscan可处理来自多个线程的请求,因此所有字段都应引用非常不可变且线程安全的对象。 Connection对象是其他的。您可以使用database connection pool。不要建立自己的连接池代码;那里有manychoicesout。如果您在应用程序服务器中运行代码,则您的应用程序服务器可能具有内置数据库池支持。

至于代码的特定问题,故障排除它的最佳方法是查看打印的堆栈跟踪。

0

//我得到的NullPointerException这里CON = NULL

类连接con你的实例变量可以为空,如果它没有得到初始化。现在,这怎么可能:

在这条线

Class.forName("net.sourceforge.jtds.jdbc.Driver"); 

如果jar文件中不存在的类路径这条线将抛出ClassNotFoundException在这种情况下,它出来try块而不执行这条线

con =DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:6543/Dbname","user",""); 

在这种情况下您con将是无效 所以只检查jar文件在类路径中实际存在或不

相关问题