Indeed, having those two static includes will result in an error of having the same variable declared twice. Those imports, at compilation time, will append the code of the included page in the including one, and will then be compiled altogether.
I'm not aware of any include_once
approach built-in in JSP, but you could do something similar by having a global Set
(i.e. HashSet
), declared as a variable in the top-level page, or as a request attribute (that you should be clearing when the processing ends) in which you could be adding the names of the pages already included.
one.jsp
<% HashSet<String> pagesSet = new HashSet<String>(); %>
...
<%@include file='two.jsp'/>
two.jsp
<% if (!pagesSet.contains("two.jsp"){ %>
//... Remember to actually ADD two.jsp to pageSet,
// because it IS being included NOW.
pageSet.add("two.jsp");
// Entire contents of two.jsp
// ....
<% } %>
Note this is quite similar to the #ifndef #define #endif
pattern in C.
Take into account that using dynamic includes you would be avoiding the problem of having duplicate variables. The included page would execute on its own scope, and to access server-side variables you'll have to pass them through with <jsp:param>
or in one of Request
, Session
or Application
scopes. See this question's answer for the differences between static and dynamic includes: include directive and attribute name problem
Additionally, if you have a great number of those "conditional" static includes, you can end up hitting the 64K method limit