請幫助我在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>
您的代碼不能編譯。你不能在函數外面有'System.out.println(「返回值+名稱);''。 – Jens 2015-02-09 12:26:10
你不重寫contextDestroyed(ServletContextEvent arg0)方法也是一個錯誤! – Prashant 2015-02-09 12:33:24
和你在哪裏得到異常? – Prashant 2015-02-09 12:37:54