Search code examples
javajsptagsjsp-tagstaglib

JSP invoke fragment vs print variable within a tag file


What are the differences, benefits, pitfalls of using <jsp:invoke fragment="var"/> vs <%=var%> within a tag file? Is there any difference once the code is compiled? In either case, are there any best practices on when to use one or the other or is pretty much a wash?


Solution

  • The <jsp:invoke> action must only be used in a tag file. It evaluates the named fragment, adding the output to the calling page's output stream or capturing it in a variable.

    The same works for <%=var%> as well, but advantage of invoke is you can provide the flexibility along with it like

    1.The scope for the variable.

    2.The name of the variable to hold the evaluation result as a String.

    3.The name of the variable to capture and expose the evaluation result as a java.io.Reader.

    by adding arguments to the tag like

      <jsp:invoke fragment="fragmentName" [var="var" | varReader="varReader"] 
      [scope="page|request|session|application"] />