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 info from child to parent

We have two main ways in which tags can cooperate with one another:

1) The child tag needs info (like an attribute value) from its parent tag.

2) The parent tag needs info from each of its child tags.

We’ve already seen how the first scenario works—the child tag gets a reference to its parent using getParent(), then calls getter methods on the parent. But what happens when the parent needs info from the child? We have to do the same thing. In other words, if the parent needs info from the child, it’s the child’s job to give it to the parent!

Since there’s no automatic mechanism for the parent to find out about its child tags, you simply have to use the same design approach to get info to the parent from the child as you do to get info from the parent to the child. You get a reference to the parent tag, and call methods. Only instead of getters, this time you’ll call some kind of set or add method.

In a JSP

<%@ taglib prefix="mine" uri="KathyClassicTags" %>
<html><body>

<mine:Menu >
   <mine:MenuItem itemValue="Dogs" />
   <mine:MenuItem itemValue="Cats" />
   <mine:MenuItem itemValue="Horses" />
</mine:Menu>

</body></html>

Result

image with no caption

Note

In this example we didn’t actually DO anything with the menu items except prove that we got them, but you can imagine that you might use the items to build a navigation bar, for example...

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