O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting an arbitrary ancestor

There is another mechanism you can use if you want to, say, skip some nesting levels and go straight to a grandparent or something even further up the tag nesting hierarchy. The method is in both TagSupport and SimpleTagSupport (although they have slightly different behavior), and it’s called findAncestorWithClass().

Getting an immediate parent using getParent()

OuterTag parent = (OuterTag) getParent();

Getting an arbitrary ancestor using findAncestorWithClass()

WayOuterTag ancestor = (WayOuterTag) findAncestorWithClass(this, WayOuterTag.class);
image with no caption

The Container walks the tag nesting hierarchy until it finds a tag that’s an instance of this class. It returns the first one, so there’s no way to say “skip the first tag you see that’s an instance of WayOuterTag.class and give me the second instance instead...” So if you really know for a fact that you wanted the second instance of a tag ancestor of that type, you’ll just have to get the return value of findAncestorWithClass(), and then call getParent() or findAncestorWithClass() on it.

You will not be tested on any details of using findAncestorWithClass(). All you need to know for the exam is that it exists!

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required