0

i am having a Problem with disabled Cookies. i am Having a page where a User logs in with his User account. The connection itself is saved in the session, if the login was sucessfull.

request.getSession().setAttribute("connection"  , connection);

the Object DBConnection, named connection in the Session, is an Object, which has got a static Connection con Object

protected static Connection con = null;

when the User logs in, the Connections gets established with

con = DriverManager.getConnection(url, this.user, this.password);

This also works with dectivated cookies. if was checking the Connection and the con Object i want to save with a System.out.println.

System.out.println(("DBConnection == null: " + connection == null));
System.out.println("Connection" connection.getCon());
//result ->
//DBConnection == null: false
//oracle.jdbc.driver.T4CConnection@15d51e5

So the Login was sucessfull. now the User leave this side and go to some other information Pages due to a button. in Here i need this connection again and i am getting it in a Servlet.

DBConnection connection = (DBConnection)request.getSession().getAttribute("connection");

with the Same System.out.println as before it gives the same result as before, when cookies are enabled. When cookies are disabled, it throws an Exception with this results:

DBConnection == null: false
java.lang.NullPointerException

So now my Question. Why does my connection break, when i have my cookies disabled? In my mind cookies don´t have anything to deal with the connection Object, or any other Object beeing saved within a JSP? The connection Object throwing the Nullpointer is the Object in the Package java.sql.Connection;

SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
  • Your real problem is however bigger. You're storing an external DB resource in the HTTP session. This is a very bad idea! It should be created, used and closed in the shortest possible scope and absolutely not be stored in the HTTP session which may live longer than the DB connection is allowed to be opened (and may thus cause it to leak away or a runout of available connections when there are many sessions). – BalusC Dec 05 '12 at 16:36

1 Answers1

1

This problem is related on how does the application or web servers store the session id on the cliente side: they use cookies for this.

On how to enable session binding for disabled cookies clients, you could check this related question on this very same site: How can i do sessions in java if some one disables cookies in my browser?

Community
  • 1
  • 1
Tomas Narros
  • 13,390
  • 2
  • 40
  • 56