错误处理requestContext路径:/Employees
Servlet路径:/Dipendente
路径信息:null
查询字符串:null
堆栈跟踪
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我得到相同的错误。也许在联系骗局里还有另外一个错误?
发布于 2017-05-10 10:43:45
你的cmd是。
private Statement cmd;...but你从来不给它分配任何东西。那么,除了null,您还期望它是什么呢?试图调用null对象上的方法将导致NullPointerException。
你所缺少的是在53线之前.
cmd = con.createStatement();这将使Connection对象创建一个新的Statement并将其分配给您的cmd变量。
还请注意这个..。
Connection con = ds.getConnection();...means说.
private Connection con;...will也总是null,导致了同样的问题。代之以..。
con = ds.getConnection();说明:使用您的代码,您将创建一个仅在构造函数中有效的新变量con,而另一个变量,也称为con,仍然是null。这不是你想要的。您希望以某种方式创建一个Connection,并将其分配给已经存在的变量con,而不是创建一个新变量con,该变量一旦构造函数完成就会被遗忘。
发布于 2017-05-10 10:45:51
用以下方法初始化语句:
cmd = con.createStatement();在此之前
ResultSet res = cmd.executeQuery(qry);https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html
https://stackoverflow.com/questions/43890102
复制相似问题