I am trying to understand the use of type and class in the jsp standard action <jsp:usebean> . I have 2 questions regarding this.
1. In HFSJ Ch 8 pg 356 (we have abstract class Person and concrete class Employee) it says that
“If type is used without class, the bean must already exist”
but then in the example given:
<jsp:usebean id=”person” type=”foo.Person” scope=”page”/>
it works if the person attribute already exists in “page” scope otherwise you get an InstantiationException.
So I am assuming the authors are saying that if Person were a concrete class using type without class will work if person attribute is in page scope otherwise you will get the exception. Does that mean that if Person were a concrete class and the attribute was not in page scope you would get an error? Can anyone please clarify this for me?
2. My second question concerns the quiz “Be the Container” on pg 358.
Here we have:
<jsp:usebean id=”person” type=”foo.Employee” scope=”request” >
<jsp:setProperty name=”person” property=”name” value=”Fred”/>
Name is: <jsp:getProperty name=”person” property=”name”/>
The servlet code is:
foo.Person p = new foo.Employee();
We know that the body of the tag will never run if the bean already exists. If the bean already exists then using type=”foo.Employee” should work. Why does it not work here? Is it because the Container knows that Employee is a subclass of Person? Would it have worked if Employee were not a subclass of Person and the servlet code said
foo.Employee e = new foo.Employee();
I appreciate your input in advance.
Yes on page 420 in the answer section the explanation given is it "fails at request time. The "person" attribute is stored at request scope, so the <jsp:usebean> tag won't work since it specifies only a type. The Container knows that if you have only a type specified there MUST be an existing bean attribute of that name and scope"
I am confused with this explanation because it seems to be talking about 2 different things as to why it fails:
1) scope: request, page
2) use of type.
Here the bean Employee is already existing. So that must not be the reason why it failed. So it fails because the scope is request?
My take on it was that Person is abstract and Employee is concrete and when type is used without class where there is an inheritance it fails.