处理请求时出错上下文路径:/员工
Servlet Path:/Dipendente
路径信息:空
查询字符串:空
堆栈跟踪
java.lang.NullPointerException
it.proxima.dipendenti.dao.DipendenteDAO.getDipendente(DipendenteDAO.java:53)
这是道
public class DipendenteDAO
{
private Connection con;
private Statement cmd;
private static DipendenteDAO istance;
public static DipendenteDAO getIstance()
{
if(istance == null) istance = new DipendenteDAO();
return istance;
}
private DipendenteDAO()
{
try
{
DataSource ds = (DataSource) new
InitialContext().lookup("java:jboss/datasources/andreadb");
Connection con = ds.getConnection();
System.out.println("con:"+con);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Dipendente getDipendente(String Codicefiscale)
{
Dipendente result = null;
try
{
// Eseguiamo una query e immagazziniamone i risultati in un oggetto
ResultSet
String qry = "SELECT * FROM dipendenti WHERE Codicefiscale
='"+Codicefiscale+"'";
ResultSet res = cmd.executeQuery(qry);
while(res.next())
{
result = new Dipendente();
result.setNome(res.getString("Nome"));
result.setCodicefiscale("Codicefiscale");
result.setCognome(res.getString("Cognome"));
result.setDatadinascita(res.getDate("Datadinascita"));
result.setLuogodinascita(res.getString("Luogodinascita"));
}
}
catch (SQLException e)
{
// Auto-generated catch block
e.printStackTrace();
}
return result;
}
这是 Servlet 代码
@WebServlet("/Dipendente")
public class DipendenteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public Dipendente getAnagrafica(String Cf)
{
DipendenteDAO dd = DipendenteDAO.getIstance();
Dipendente dip = dd.getDipendente(Cf);
if(dip == null) System.out.println("ERRORE: Codice fiscale non presente
nel sistema");
else System.out.println(dip.getNome() + " " + dip.getCognome());
dd.close();
return dip;
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String codiceFiscale = request.getParameter("Codice_Fiscale");
Dipendente ds = this.getAnagrafica(codiceFiscale);
response.getWriter().append(ds.getNome()+" "+ds.getCognome());
}
有谁知道可能取决于什么?
错误的第 53 行是这样的:
53: ResultSet res = cmd.executeQuery(qry);
在调试模式下,语句 cmd 为空
初始化cmd时我得到同样的错误。也许连接骗局中还有另一个错误?
你的cmd
是...
private Statement cmd;
。但是你从不给它分配任何东西。那么,您如何期望它成为其他任何东西,然后null
?尝试在null
对象上调用方法将导致NullPointerException
。
你缺少的是第 53 行之前的类似的东西......
cmd = con.createStatement();
这将允许Connection
对象创建一个新Statement
并将其分配给cmd
变量。
另请注意,这...
Connection con = ds.getConnection();
。意味着...
private Connection con;
。也将始终null
,导致相同的问题。将其替换为...
con = ds.getConnection();
说明:使用您的代码,您正在创建一个 NEW 变量con
,该变量仅在构造函数中有效,而另一个变量(也称为 con
(仍将null
。这不是你想要的。您想以某种方式创建一个Connection
并将其分配给已经存在的变量con
,而不是创建一个一旦构造函数完成就会被遗忘的新变量con
。
使用以下命令初始化语句:
cmd = con.createStatement();
以前
ResultSet res = cmd.executeQuery(qry);
https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html