Adding a type attribute to <jsp:useBean>

With the changes we just made to the Person class, we’re in trouble if the attribute can’t be found:

image with no caption

Our original JSP

<jsp:useBean id="person" class="foo.Person" scope="page"/>

Has this result

java.lang.InstantiationException: foo.Person

Because the Container tries to:

new foo.Person();

Note

Person is now abstract! Obviously, you can’t make one, but the Container still tries, based on the class attribute in the tag.

We need to make the reference variable type Person, and the object an instance of class Employee. Adding a type attribute to the tag lets us do that.

Our new JSP with a type

image with no caption

Type can be a class type, abstract type, or an interface—anything that you can use as a declared reference type for the class type of the bean object. You can’t violate Java typing rules, of course. If the class type can’t be assigned to the reference type, you’re screwed. So that means that class must be a concrete implementation of the type.

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.