Java Reference
In-Depth Information
The servlet engine initializes the servlet once when it is first loaded. The init()
method can receive runtime parameters just like applets and do any one-time ini-
tialization required for the servlet. Once they are loaded, servlets stay loaded unless
the servlet engine decides to shut them down. Servlets are handed requests from a
thread pool, which is both good and bad. The good part is that the startup overhead
for new requests is minimal. The bad part is that you need to be concerned about
trashing your internal data if two service requests start executing simultaneously.
Remember that only one copy of your servlet is in the memory of the VM. If
browser number 1's request comes to the servlet and you set a value in your class in-
stance during the processing of that request, that value will still be set when browser
number 2's request is handed to your servlet. In reality, the situation is even more
complicated. Depending upon the thread-switching mechanisms in place in the VM,
request number 2 might actually change the value of your variables even while re-
quest number 1 is still being processed. You might wonder how anyone can ever
code in this environment. Although several solutions exist to the problem of reen-
trancy, the most common solution and the easiest is to create a session.
The servlet engine has the ability to create a Session object that is associated
with the session between the browser and the Web server. A session is a time-sen-
sitive association between an instance of a browser and the Web site. This Session
object can exist across the interactions between the browser and the Web server.
Typical logic is to create a Session object when someone first enters a site. The
HttpRequest object has a method that returns the session if it exists or creates it if it
doesn't exist.
HttpSession session = req.getSession();
Once you have a session, you can put variables and objects in it:
String userId = "auser";
session.setAttribute("userId ", userId);
You can also retrieve values from it:
String userId = (String) session.getAttribute(“userId “);
Search WWH ::




Custom Search