Using type without class

What happens if we declare a type, but not a class? Does it matter if the type is abstract or concrete?

JSP

image with no caption

Result if the person attribute already exists in “page” scope

It works perfectly.

Result if the person attribute does NOT exist in “page” scope

java.lang.InstantiationException: bean person not found within scope

Note

WON’T WORK!!

Note

If type is used without class, the bean must already exist.

If class is used (with or without type) the class must NOT be abstract, and must have a public no-arg constructor.

Q:

Q: In your example, “foo.Person” is an abstract type, so of COURSE it can’t be instantiated. What if you change the type to “foo.Employee”? Will it use the type for both the reference AND the object type?

A:

A: NO! It never works. If the Container discovers that the bean doesn’t exist, and it sees only a type attribute without a class, it knows that you’ve given it only HALF of what it needs—the reference type but not the object type. In other words, you haven’t told it what to make a new instance of!

There is no fallback rule that says, “If you can’t find the object, go ahead and use the type for BOTH the reference and the object.” No, that is NOT how it works.

Bottom line: if you use type without class, you better make CERTAIN that the bean is already stored as an attribute, at the scope and with the id you put in the tag.

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.