简体   繁体   English

java servlet如何从init()方法获取值并在方法之外使用它们?

[英]java servlet how to get value from init() method and use them outside the method?

Help please I'm new on servlet I'm trying to initialize value on the init method and use them after but I get nullpointerexception this is my classe Hello it contains 2 methods init() and jdbcinfo() i need to get data base connection once 请帮忙,我是servlet的新手,我试图初始化init方法的值并在之后使用它们,但我得到nullpointerexception这是我的类您好,它包含2个方法init()和jdbcinfo()我需要获取数据库连接一旦

 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";
        }



        }

my web.xml 我的web.xml

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

</servlet>

@geert3 is correct. @ geert3是正确的。 You do not want to create a connection and save it in a field in a servlet's init() method. 您不想创建连接并将其保存在servlet的init()方法的字段中。 Servlets are singletonscan handle requests from multiple threads, so all fields should reference objects that are deeply immutable and thread-safe. Servlet是来自多个线程的单例扫描句柄请求,因此所有字段都应引用深度不变且线程安全的对象。 Connection objects are niether. Connection对象是虚无的。

Instead, you should use a database connection pool . 相反,您应该使用数据库连接池 Don't build your own connection pool code; 不要建立自己的连接池代码; there are many choices out there. 很多 选择 那里。 If you are running the code inside an application server, your application server might have built-in database pool support. 如果在应用程序服务器中运行代码,则您的应用程序服务器可能具有内置的数据库池支持。

As for the particular problem with the code, the best way to trouble-shoot it is to look at the printed stack trace. 对于代码中的特定问题,解决它的最佳方法是查看打印的堆栈跟踪。

//I get nullpointerexception here con = null //我在这里得到nullpointerexception con = null

Your Instance variable of Class Connection con can be null if it didn't get initialized . 如果未初始化,则Class Connection con Instance变量可以为null。 Now how can this be possible : 现在怎么可能:

At this line 在这一行

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

if jar file is not present in your class Path this line will throw ClassNotFoundException and in that case it comes out of try block without executing this line 如果您的类Path中不存在jar文件,则此行将抛出ClassNotFoundException ,在这种情况下,它会从try块中出来而不执行该行

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

and in this case your con will be null So Just check if the jar file is actually present in your class path or not 并且在这种情况下,您的con将为null,所以只需检查jar文件是否确实存在于您的类路径中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM