문제

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?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top