简体   繁体   中英

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

 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

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

</servlet>

@geert3 is correct. You do not want to create a connection and save it in a field in a servlet's init() method. Servlets are singletonscan handle requests from multiple threads, so all fields should reference objects that are deeply immutable and thread-safe. Connection objects are niether.

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

Your Instance variable of Class Connection con can be null if it didn't get initialized . 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

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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