Domanda

So I have a Listener that implements ServletContextListener. in the contextInitialized method that makes a database connection with Oracle 11g schema.

After establishing a database connection in the listener (I do get a successful println that I wrote in case the connection was made), I set Attributes to a servletcontext

context=event.getServletContext();
context.setAttribute("DatabaseConnection", conn); 
//conn is the Connection instance in listener

In my jsp file under a scriplet tag I make an instance of the Connection interface and initialize it with context's attribute:

Connection conn = (Connection) application.getContext("DatabaseConnection");
out.println("Connection Made");
PreparedStatement ps = conn.prepareStatement("select * from Category");
out.println("PreparedStatement created");

So in the output i am getting "Connection Made" but i am getting a NullPointerException from the Prepared Statement line; (I am not getting "preparedstatement created" in the output.

Why is this prepared statement causing problems?

È stato utile?

Soluzione

You need to use getAttribute(), not getContext().

If you were to look at the servlet code generated for the page you would see:

application = pageContext.getServletContext();

So application is already the ServletContext. This should return what you need:

Connection conn = (Connection) application.getAttribute("DatabaseConnection");

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top