Skip to Content
Head First Servlets and JSP, 2nd Edition
book

Head First Servlets and JSP, 2nd Edition

by Bryan Basham, Kathy Sierra, Bert Bates
March 2008
Intermediate to advanced
911 pages
20h 31m
English
O'Reilly Media, Inc.
Content preview from Head First Servlets and JSP, 2nd Edition

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!

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Java, 2nd Edition

Head First Java, 2nd Edition

Kathy Sierra, Bert Bates
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck

Publisher Resources

ISBN: 9780596516680Errata PageSupplemental Content