jspjsp-tagstagfile

How to get a variable from scriplet in tag file


These are my first steps in tag file. Maybe this question is very simple. But I can't solve it.

I have the following tag file

<% 
Foo foo=new Foo();
%>
<jsp:include page="${foo.getFileName()}"/>

It seems to me that jasper doesn't see foo variable. What am I doing wrong?


Solution

  • Using the expression language ${...} your variable must be accessible in one of the PageContext, Request, Session, Application... scopes.

    In order to make your code work, you must change it to:

    <% 
    Foo foo=new Foo();
    pageContext.setAttribute("foo", foo);
    %>
    <jsp:include page="${foo.getFileName()}"/>
    

    If you are using a tag file, then prefer maybe jspContext instead of pageContext:

      <% 
        Foo foo=new Foo();
        jspContext.setAttribute("foo", foo);
        %>
        <jsp:include page="${foo.getFileName()}"/>