views:

481

answers:

1

I'm creating a site on which there are many page components that refer to objects that are used elsewhere in the page. Some of these components are used in other pages as well, thus my desire to use includes rather than cut-and-paste.

The problem is that if I have identical "jsp:useBean" statements in multiple components of the page, the compiler gives the error "duplicate local variable".

How can I use the same objects in multiple components of a JSP page without having everything in the file?

Example: in the main (parent) page:

<jsp:useBean id="fred" class="..." scope="request" />

<jsp:directive.include file="myWidget.jsp" />

the included page, myWidget.jsp, also needs to make use of the "fred" object:

<jsp:useBean id="fred" class="..." scope="request" />

However, this causes compilation to fail with "duplicate local variable 'fred'".

This basically defeats the idea of having a page broken up into components; I don't want to have JSP files that are hundreds of lines long, that are only slightly different from one another!

For one component, where it's absolutely essential that it be consistent across every page of the site, I've worked around the problem with a scriptlet:

<%
    { // for scope
        Object _o1 = request.getAttribute("fred");
        if (_o1 !=null && _o1 instanceof MyClass)
        {
            // use a deliberately obscure variable name to avoid conflict
            MyClass _myLocalFred1 = (MyClass) _o1; 

        }
    } // for scope
%>

This works, but it's ugly; several books say "don't ever use scriptlets", but scriptlets seem to be the only method where variable scope can be controlled, and I can use names without worrying that they're in use elsewhere in the page.

How does one use jsp:useBean in an include'd file?

A: 

I ended up using the "Tiles" part of the Struts framework. It provides isolation of components, so they don't befoul each others' namespace.

Matt Hucke