My understanding is like : Session attributes(Attributes bound into a session) are availbale to the all the servlets that are part of the same session. But how it can be accessed by all servlets which are part of same servletcontext?
Sessions and Servlets and two different beasts. A request may be associated with a session, and forwarded by the container to the appropriate servlet. Servlets do not live in sessions, and are not associated with sessions either. Servlets can retrieve a session from a request, to set/get attributes. That's about it.
Servlets belonging to the same ServletContext (same app) can all access the same session, thus they can access the same objects with are bound to this session
Here my intenstion is to make the above statment clear.
Suppose for example there are two servlets, Serv1,Serv2 and Serv3 in a web app. So Serv1, Serv2 and Serv3 will be in same ServletContext.
For the logging Serv1 will be used.
Customer1 made a login request and session1 is created. For this session1 an attribute "Valid for PMT" is added allowing customer to make a payment.
request.setAttribute("isValid","Valid for PMT")
Customer2 made a login request and session2 is created. For this session2 an attribute "Not Valid for PMT" is added allowing customer not to make any payment. request.setAttribute("isValid","NotValid for PMT")
In your web app you are allowing payments to do online.For this Payment Transaction Serv2 is used.
When Customer1 makes a payment, In Serv2 to validate the customer the logic will be
And in your app you are allowing customers to make online balance transfer even. Condition here is, the customers who are valid for payment only can be allowed to make Balance Transfer online. Here Serv3 will be used to check this.
So in the Serv3 again to validat BT we can access the same session attributes which were set as a part of payment.
In this way until you make that session variable invalid (as per your business logic) or session expires, you can access this session variable in all servlets which are in the same servletcontext (same web app).
Hope this example will make you clear. If example is bad, don't scold me.
Here the Servlets acts as controller(to perform business logic). Servlet is indepent of session. [ March 19, 2008: Message edited by: kalle suresh ]
Joined: Mar 12, 2008
Thanks for your clarification... suresh your example is very good one thing...you used request.setAttribute("isValid","Valid for PMT") but it should be session.setAttribute("isValid","Valid for PMT") [ March 19, 2008: Message edited by: Shruthi Karthick ]
Joined: Nov 20, 2007
Yes you are right, that should be session1.setAttribute() and session2.setAttribute() like that. [ March 19, 2008: Message edited by: kalle suresh ]