Attempting to add a record into database using a shared connection(connection created upon intialising a request) Here i'm request.getAttribute() method to retrieve attribute from RequestListener.java and assigning it to Connection type reference.
here's my code:RequestListener.java
public class RequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
try {
Connection connection=(Connection) sre.getServletContext().getAttribute("conn");
connection.close();
} catch (SQLException ex) {
Logger.getLogger(RequestListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost/school?user=root&password=mysql");
sre.getServletContext().setAttribute("conn",connection);
} catch (Exception ex) {
Logger.getLogger(RequestListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
error:java.lang.NullPointerException
at servlets.One.processRequest(One.java:45)
at servlets.One.doGet(One.java:89)
////// One.java (servlet)
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String t1=request.getParameter("text1");
out.println("A");
Connection connection = (Connection) request.getAttribute("conn");
//line45 **PreparedStatement ps = connection.prepareStatement("insert into tb1 values(?)");**
ps.setString(1, t1);
ps.executeUpdate();
ps.close();
request.setAttribute("conn", connection);
request.getRequestDispatcher("B").forward(request, response);
request.getRequestDispatcher("Two").forward(request, response);
} catch (SQLException ex) {
Logger.getLogger(One.class.getName()).log(Level.SEVERE, null, ex);
}
}