In the documentation, the “name” inside a <bean:write> tag is mentioned to be the name of the bean whose property has to be printed. If the property isn’t mentioned, the value of the bean itself is printed.
But if I set an attribute in the Action class like :
setAttribute("dda","hello");
and in the JSP say :
<bean:write name="dda"/>
I get “hello” even though “dda” is not the name of any bean.
Why does that happen? And what is meant by “bean itself is printed”? Is its object’s hashcode rendered?
The documentation says the following about the
nameattribute:Pay close attention to this wording: the attribute name of the bean.
Let’s lose the naming “bean” for a moment and talk about objects (since a bean is just a special kind of object).
You can create an object and place it as attribute in a scope (
request.setAttribute(...),session.setAttribute(...)etc). And you place it with an attribute name. This is like a map if you will, the attribute name is the key and the object is the value.What
<bean:write>does is lookup an object with the name attribute you give it (by means ofjspContext.findAttribute(...)). Now it has an object to work with!If you also specify a
propertyattribute for the tag, the tag will try to call a getter with the property name on that object. Now we are talking about beans because by definition a bean has getters/setters for its properties.But in your example you have set a string
"hello"with a named attribute"dda"and you specified no property attribute for<bean:write>. A string is not a bean by definition because it has no getters/setters, it is just a plain object. In this case, the tag falls-back to printing the object itself; as the documentations again specifies: the usualtoString()conversions will be applied."hello".toString()is still"hello"so that gets printed.Instead of
"hello"just place anew Object()in your code and you will see theObject.toString()method being called and you get something likejava.lang.Object@123456printed out.Place instead a bean with a
getBlagetter and a<bean:write name="dda" property="bla" />will trigger the call to theddabean for thebla’s property getter.