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);
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!
Exercise
Key differences between Simple and Classic tags
Simple tags | Classic tags | |
---|---|---|
Tag interfaces | ||
Support implementation classes | ||
Key lifecycle methods that YOU might implement | ||
How you write to the response output | ||
How you access implicit variables and scoped attributes from a support implementation | ||
How you cause the body to be processed | ||
How you cause the current page evaluation to STOP |
Exercise Answers
Key differences between Simple and Classic tags
Simple tags | Classic tags | |
---|---|---|
Tag interfaces | SimpleTag (extends JspTag) | Tag (extends JspTag) IterationTag (extends Tag) BodyTag (extends IterationTag) |
Support implementation classes | SimpleTagSupport (implements SimpleTag) | TagSupport (implements IterationTag) BodyTagSupport (extends TagSupport, implements BodyTag) |
Key lifecycle methods that YOU might implement | doTag() | doStartTag() doEndTag() doAfterBody() (and for BodyTag— doInitBody() and setBodyContent()) |
How you write to the response output | getJspContext().getOut().println (no try/catch needed because SimpleTag methods declare IOException) | pageContext.getOut().println (wrapped in a try/catch because Classic tag methods do NOT declare the IOException!) |
How you access implicit variables and scoped attributes from a support implementation | With the getJspContext() method that returns a JspContext (which is usually a PageContext) | With the pageContext implicit variable--NOT a method like it is with SimpleTag! |
How you cause the body to be processed | getJspBody().invoke(null) | Return EVAL_BODY_INCLUDE from doStartTag(), or EVAL_BODY_BUFFERED if the class implements BodyTag. |
How you cause the current page evaluation to STOP | Throw a SkipPageException | Return SKIP_PAGE from doEndTag() |