-1

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);
        }

    }
  • If `connection` is null, then you should check if the attribute `conn` is really available in the request. – Tom Sep 15 '14 at 17:44
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Mark Rotteveel Sep 16 '14 at 13:31

1 Answers1

0

RequestListener.java

"sre.getServletContext().setAttribute("conn",connection)" has to corrected as sre.getServletRequest().setAttribute("conn",connection) and avoid sending requests to two servlets as "request.getRequestDispatcher("B").forward(request, response); request.getRequestDispatcher("Two").forward(request, response);" which results a illegalStateException