Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Abstract class in Jsp:useBean  RSS feed

Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers....
Hope you all doing well.
Today, while going through JSP tutorial, I looked on one odd thing.

The <jsp:useBean> standered action, has attributes like "class" that indicates the name of the class to be instantiated and an other attribute "Type" that indicate the type of instance variable.

My Bean Class Structure is as follows :

abstract class Animal{
String category;
...//other stuffs including getters n setters

class Person extends Animal{
String name;
int age;
//getters n setters here

I am trying to forward the request from Home.jsp to PersonInfo.jsp with requestDispatcher.

Home.jsp :

PersonInfo.jsp :

In this case, as PersonInfo.jsp is not receiving any object in request scope of name "p", the body of useBean get executed. In generated servlet for this jsp, the type of reference will be "Animal" and it stores object of type "Person" as specified by "class" attirbute in jsp:useBean tag.

My Question is , even if class Animal is abstract and is a superclass of Person, it is allowed to access the varialbles in its subclass i.e. Person. As, we are setting properties using jsp:setPrpeprty, meaning
we are using superclass type varialble to access subclass variables. Doesn't this look an odd to you also ?

Please let me know if you are not able to understand my doubt.

Thanks in advance.
Posts: 1843
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your point is well made. And it would be completely applicable in java programming.

The java equivalent of this jsp code would be approximately:

Obviously this wouldn't compile in the java language, because the Animal class doesn't have the setters for name and age.

However the setProperty tag is not actually bound by the type of the variable.
You could specify whatever property you like in the setProperty tag, and it will look for the appropriate setter to use - the same way it would for any java bean - normally via reflection into the get/set methods.
Of course it will complain if that property doesn't exist (no setter) but it does mean that this is entirely valid JSP code.

It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!