Let's say I have simple Login servlet that checks the passed name
and creates User
object and stores it in a session.
User user = new User();
user.setId(name);
request.getSession().setAttribute("user", user);
response.sendRedirect("index.jsp");
In the index.jsp
page I access the user object through jsp:useBean
<jsp:useBean id="user" scope="session"
class="package.name.User"/>
<div class="panel">
Welcome ${user.id}
</div>
It works so far.
From the jsp beans documentation
To locate or instantiate the Bean, takes the following steps, in this order:
- Attempts to locate a Bean with the scope and name you specify.
- Defines an object reference variable with the name you specify.
- If it finds the Bean, stores a reference to it in the variable. If you specified type, gives the Bean that type.
- If it does not find the Bean, instantiates it from the class you specify, storing a reference to it in the new variable. If the class name represents a serialized template, the Bean is instantiated by java.beans.Beans.instantiate.
- If has instantiated (rather than located) the Bean, and if it has body tags or elements (between and ), executes the body tags.
The questions:
Attempts to locate a Bean with the scope and name you specify
It does not specify the "locate" process. Does it mean it will check HttpServletRequest.getSession()
or just check whether other pages already created this bean or not?
If it does not find the Bean, instantiates it from the class you specify, storing a > reference to it in the new variable.
This actually means that Jsp can associate newly created bean with session using jsp_internal_name_user. There is no any word about how Jsp stores and finds beans in the session.
There is an option to access session objects by using ${sessionScope.user}
and that will guarantee that "user" from the Java session object will be get. The same one I put into by myself.
Java EE 5 example "Book Store" access session objects using ${sessionScope.name}
approach.
Using just ${user}
works. And this is what makes me worry. I would like to see specific sentence in some specification about locate
process and whether ${user}
must work or it is up to JSP and/or JSTL reference implementation.