how to check that jsp file is included or not in another jsp file?
see you all know about including file in a jsp... i have 2 files
one.jsp two.jsp
in two.jsp i have below given code
Long something = 0;
in one.jsp code is
<%@include file='two.jsp'%>
<%@include file='two.jsp'%>
i have included same file two times,
so there will be error because something variable will be created 2 times, right?
so it means before including file sec开发者_高级运维ond time i should check that, if once its included then i should not inculde it again, how to check that ?
as in php there are functions like include("file.php"); //that will include file
and include_once("file.php"); //this will include file if its not included before,
ANY ANY solutions for that????
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
精彩评论