Basically, I have two classes in my web application, one class 'FormProcess.java', which takes information inserting into an HTML form, performs a few calculations, then outputs the result as HTML. This works absolutely fine.
I also have a class for adding the data into a new row of a MySQL database, the class is called 'SqlConnect.java'. This also works fine if I run it seperately on the server (ie. it correctly inserts a row on to the table).
What I am struggling with is getting the SqlConnect methods to run from the FormProcess class. When I add the following to FormProcess:
private SqlConnect sql;
and in a method:
sql.doPost(request, response);
I get the following error:
java.lang.NullPointerException
crunch.FormProcess.doGet(FormProcess.java:27)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
This is the SqlConnect class at the moment (I left out the imports etc.):
@WebServlet(name="sql",urlPatterns={"/sql"})
public class SqlConnect extends javax.servlet.http.HttpServlet {
FormProcess process = new FormProcess();
private static final long serialVersionUID = 1L;
public SqlConnect() {
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
performTask(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
performTask(request, response);
}
public void performTask(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
testJndiDataSource();
}
public void testJndiDataSource() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/CrunchDB");
conn = ds.getConnection();
st = conn.createStatement();
st.executeUpdate("INSERT INTO log " + "VALUES (20, '1', '1', " + process.salaryInt + ", "+ process.takeHomePAYE +", "+ process.takeHomeContractor +", 2)");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
I'm sure there is a simple way of doing this I just can't work it out, as I said the SqlConnect class will run fine on it's own.
Cheers