I would like to clarify answer to a mock exam question from chapter 6. The following is the question:
Q: Which statements about session attributes are true? (Choose all that apply.)
A. The return type of HttpSession.getAttribute(String) is Object.
B. The return type of HttpSession.getAttribute(String) is String.
C. Attributes bound into a session are available to any other servlet that belongs to the same ServletContext.
D. Calling setAttribute("keyA", "valueB") on an HttpSession which already holds a value for the key keyA will cause an
exception to be thrown.
E. Calling setAttribute("keyA", "valueB") on an HttpSession which already holds a value for the keyA will cause the previous
value for this attribute to be replaced with the String valueB.
My answer to this question is AE and the correct answer is ACE.
My doubt is in the answer C, "Attributes bound into a session are available to any other servlet that belongs to the same ServletContext only if any other servlet also participating in the same session.".
The servlet context can have many servlets, how one servlet can access to other servlet's session attributes unless they are in same session.
Since the question didn't mention anything about whether the servlet is in same session or not, answer C is wrong.
Anybody please correct me I am wrong.
Ankit Garg wrote:Lets say that there are two servlets, servlet1 and servlet2 in a web application. servlet1 sets a session attribute "name" in the session scope. Now will it not be able to servlet2?? What do you mean by "participating" in a session. If the same client that called servlet1 calls the servlet2, it will have the same session that servlet1 had (of course assuming that session has not timed out)...
The above scenario is true if the same client sends request to servlet2 with the same session id as servlet1. However, in the mock exam question, it is mentioned that any other servlet in the servlet context can access session attributes. If other servlets doesn't have session id how they're going to access session attributes of servlet1?
Am I correct?
Sai Surya wrote:If other servlets doesn't have session id how they're going to access session attributes of servlet1?
But if it has the session ID, then it has access to the attributes. So the attributes will be available to it if a call is made from the same client to the second servlet. If there was a situation that the second servlet can't access the attribute even if it is in the same session, then the statement would have been false...