I'm dealing with a problem within my database class in Netbeans. I'm trying to display an html-page which you can use to search data about patients by just typing the patient ID in the input. When you click on "Get patient data", the servlet should connect to my database and get all the data. Though, this is not the case. I keep getting nullpointer exceptions in my Database class at this line:
try (Connection con = dataSource.getConnection();
PreparedStatement statement = con.prepareStatement(
"SELECT voorletters, voornaam, geboortenaam, geslacht, overleden, geboortedatum, adres, postcode, woonplaats, fam_aand" +
"FROM Patient" +
"WHERE patientnr = " + ?))
This is the entire code of my database class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package opdracht2;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.sql.DataSource;
/**
*
* @author me
*/
public class PlekDatabase {
private DataSource dataSource;
public PlekDatabase(DataSource dataSource)
{
this.dataSource = dataSource;
}
/** Voegt nieuwe patient aan db toe. Het patientnr mag nog niet in gebruik zijn.
* @return true als de patient is toegevoegd, anders false */
public boolean addPatient(int patientnr, String voorletters,
String voornaam, String geboortenaam, String geslacht,
String overleden, String geboortedatum, String adres,
String postcode, String woonplaats, String fam_aand)
throws SQLException
{
try (Connection connection = dataSource.getConnection();
PreparedStatement insertPatientStmt = connection.prepareStatement(
"INSERT INTO Patient(patientnr, voorletters, voornaam, geboortenaam, geslacht, overleden, geboortedatum, adres, "
+ "postcode, woonplaats, fam_aand) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))
{
// Voorkom race conditions; niet behandeld (zie paragraaf 11 in de handleiding)
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
// Als het patientnr al bestaat, houdt het op
if (exists(connection, patientnr)) return false;
insertPatientStmt.setInt(1, patientnr);
insertPatientStmt.setString(2, voorletters);
insertPatientStmt.setString(3, voornaam);
insertPatientStmt.setString(4, geboortenaam);
insertPatientStmt.setInt(5, geslacht.equals("man") ? 1 : 2);
insertPatientStmt.setBoolean(6, overleden.equals("on"));
insertPatientStmt.setString(7, geboortedatum);
insertPatientStmt.setString(8, adres);
insertPatientStmt.setString(9, postcode);
insertPatientStmt.setString(10, woonplaats);
insertPatientStmt.setString(11, fam_aand);
insertPatientStmt.executeUpdate();
connection.commit(); // voorkom race conditions
connection.setAutoCommit(true); // voorkom race conditions
}
return true;
}
/** Controleert of patientnr al bestaat.
* Alternatief: vang exception op als al bestaand patientnr wordt toegevoegd
* @return true als het patientnr al bestaat, anders false
* */
private boolean exists(Connection con, int patientnr) throws SQLException
{
int count;
try (PreparedStatement statement = con.prepareStatement(
"SELECT COUNT(*) FROM Patient WHERE patientnr = ?"))
{
statement.setInt(1, patientnr);
ResultSet rs = statement.executeQuery();
rs.next();
count = rs.getInt(1);
}
return count > 0;
}
public String[] zoekPatient(String patientnr) throws ServletException, IOException, SQLException
{
try (Connection con = dataSource.getConnection();
PreparedStatement statement = con.prepareStatement(
"SELECT voorletters, voornaam, geboortenaam, geslacht, overleden, geboortedatum, adres, postcode, woonplaats, fam_aand" +
"FROM Patient" +
"WHERE patientnr = ?"))
{
statement.setInt(1, Integer.parseInt(patientnr));
statement.execute();
ResultSet rs = statement.executeQuery();
// Doorlopen van rijen van resultset
if (rs.next()) {
String voorletters = rs.getString("voorletters");
String voornaam = rs.getString("voornaam");
String geboortenaam = rs.getString("geboortenaam");
String geslacht = rs.getString("geslacht");
String overleden = rs.getString("overleden");
String adres = rs.getString("adres");
String postcode = rs.getString("postcode");
String woonplaats = rs.getString("woonplaats");
String famaand = rs.getString("fam_aand");
String geboortedatum = rs.getString("geboortedatum");
String jaar = geboortedatum.substring(0,4);
String maand = geboortedatum.substring(5,7);
String dag = geboortedatum.substring(8,10);
String[] patientgegevens = {voorletters, voornaam, geboortenaam, geslacht, overleden, adres, postcode, woonplaats, famaand, dag, maand, jaar};
return patientgegevens;
}
String[] patientgegevens = {"Patient bestaat niet", "Patient bestaat niet", "Patient bestaat niet", "Patient bestaat niet", "Patient bestaat niet", "Patient bestaat niet", "Patient bestaat niet", "Patient bestaat niet", "Patient bestaat niet" ,"Patient bestaat niet", "Patient bestaat niet", "Patient bestaat niet"};
return patientgegevens;
}
}
public void updatePatient(String patientnr, String voorletters, String voornaam, String geboortenaam, String geslacht, String overleden, String geboortedatum, String adres, String postcode, String woonplaats, String fam_aand) throws ServletException, IOException, SQLException
{
try (Connection con = dataSource.getConnection();
PreparedStatement statement = con.prepareStatement("UPDATE Patient" +
"SET voorletters = ?, voornaam = ? , geboortenaam = ?, geslacht = ?, overleden = ?, geboortedatum = ?, adres = ?, postcode = ?, woonplaats = ?, fam_aand = ?" +
"WHERE patientnr = ?"))
{
statement.setInt(1, Integer.parseInt(patientnr));
statement.setString(1,voorletters);
statement.setString(2, voornaam);
statement.setString(3, geboortenaam);
statement.setString(4, geslacht);
statement.setString(5, overleden);
statement.setString(6, geboortedatum);
statement.setString(7, adres);
statement.setString(8, postcode);
statement.setString(9, woonplaats);
statement.setString(10, fam_aand);
statement.setInt(11, Integer.parseInt(patientnr));
statement.executeUpdate();
statement.execute();
statement.executeUpdate();
// Doorlopen van rijen van resultset
}
}
public void deletePatient(String patientnummer) throws SQLException
{ try (Connection con = dataSource.getConnection();
PreparedStatement statement = con.prepareStatement("DELETE FROM Patient WHERE patientnr = ?"
))
{
statement.execute();
statement.executeUpdate();
// Doorlopen van rijen van resultset
}
}
}
And this is the servlet I use:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package opdracht3;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import opdracht2.PlekDatabase;
/**
*
* @author me
*/
@WebServlet(name = "ZoekPatientServlet", urlPatterns = {"/zoekpatientservlet"})
public class ZoekPatientServlet extends HttpServlet {
@Resource(name = "jdbc/PLEK_me")
private DataSource dataSource;
PlekDatabase database = new PlekDatabase(dataSource);
private static final long serialVersionUID = 1L;
private static final String EMPTY_WARNING = "<em>niet ingevuld</em>";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @param patientnr
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
* @throws java.sql.SQLException
*/
// protected void doPost(HttpServletRequest request,
// HttpServletResponse response) throws ServletException, IOException
//{
//}
@Override
protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(ZoekPatientServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<html>");
out.println("<head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'>");
out.println("<link rel='stylesheet' type='text/css' href='style.css'>");
out.println("<title>Opgevraagde patientgegevens</title>");
out.println("</head>");
out.println("<body>");
out.println("test123");
out.println("test123");
out.println("test123");
String paramPatnr = request.getParameter("patientnummer");
out.println("test12");
String[] patientgegevens = null;
out.println("test1235");
try{
patientgegevens = database.zoekPatient(paramPatnr);
out.println("test1237");
}
catch(SQLException e){
System.out.println("Fout: " + e.getMessage());
}
printParameter("voorletters", patientgegevens[0], request, out);
printParameter("voornaam", patientgegevens[1], request, out);
printParameter("geboortenaam", patientgegevens[2], request, out);
printParameter("geslacht", patientgegevens[3], request, out);
printParameter("overleden", patientgegevens[4], request, out);
printParameter("adres", patientgegevens[5], request, out);
printParameter("postcode", patientgegevens[6], request, out);
printParameter("woonplaats",patientgegevens[7], request, out);
printParameter("fam_aand", patientgegevens[8], request, out);
printGeboortedatum(patientgegevens, request, out);
out.println("</tr>");
out.println("</table>");
out.println("<button id=\"update\" type=\"submit\" value=\"Submit\"><b>Zoek patientnummer</b></button>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
private void printParameter(String displayName, String waarde, HttpServletRequest request, PrintWriter out)
{
if (waarde == null || waarde.equals(""))
{
waarde = EMPTY_WARNING;
}
out.println("<tr><td>" + displayName + "</td><td>" + waarde + "</td>");
}
private void printGeboortedatum(String[] Array, HttpServletRequest request, PrintWriter out) throws SQLException
{
String dag = Array[9];
String maand = Array[10];
String jaar = Array[11];
String date;
if (dag.equals("") || maand.equals("") || jaar.equals(""))
{
date = EMPTY_WARNING;
} else
{
date = dag + "-" + maand + "-" + jaar;
}
out.println("<tr><td>Geboortedatum</td><td>" + date + "</td>");
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
}
}
I don't get it. Why does it keep giving me the nullpointerexception? I tried debugging and I tried catching it with an exception, but it doesn't show me the exception at all.
Here is the stackktrace I think you guys meant:
09-Oct-2015 12:52:02.685 SEVERE [http-nio-8084-exec-6] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [ZoekPatientServlet] in context with path [/mijnwebapp] threw exception
java.lang.NullPointerException
at opdracht2.PlekDatabase.zoekPatient(PlekDatabase.java:89)
at opdracht3.ZoekPatientServlet.processRequest(ZoekPatientServlet.java:87)
at opdracht3.ZoekPatientServlet.doPost(ZoekPatientServlet.java:57)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)