= = = = = = = = Problem
If you want to write a shopping cart, you usually need to write a number of different features of the servlet. For example, user login, add goods, check shopping cart, checkout and so on.
You need to read and write the database in these servlet. If we are connected in each servlet-> read-write-> disconnected operation, will consume a lot of server resources, not only the program response speed slows down, but also can aggravate the server and the database burden.
= = to put hope in HttpSession = =
As we have learned, the Servlet API provides methods and classes to specialize in short-term session tracking. Each user of the site is associated with a Javax.servlet.http.HttpSession object that the servlet uses to record and retrieve information for each user.
Luckily, we can store any Java object in the Session object. The methods of storage are already familiar, that is, using the SetAttribute () method. Connection, which represents the database connection, is no exception.
This gives us the hope that the different servlet will share the links within a session.
= = = = = = = Safety Problem
So, just do it as follows?
1. In Servlet1, set a property to the session:
Session.setattribute ("Connection", connection);
2. In Servlet2, remove this attribute:
Connection Connection = (Connection) session.getattribute ("Connection");
Theoretically, no problem. The Connection object produced in the Servlet1 can continue to be used in Servlet2.
But if Servlet2 accidentally changes the connection reference, such as connection = NULL; So, when it puts this connection into the properties of the session again, the other servlet gets a null-pointing connection!
the solution = = = = = = =
It seems not safe to pass the connection directly in the session.