Reputation: 11
How can i include a JSP page in another JSP with the IF structure:
Can i use this part of code in a JSP file:
<%
UtilisateurAction useraction = new UtilisateurAction();
String statut = useraction.Connect();
//System.out.println(statut);
if(statut=="ADMIN"){
%> <%@ include file="menu.jsp"%>
<%}
else {if(statut=="USER"){%>
<%@ include file="menu.jsp"%>
<%}} %>
Upvotes: 0
Views: 14745
Reputation: 3682
You can use <jsp:include page="menu.jsp" flush="true"/>
to include pages in jsp, on conditions checks.
If you are not using jstl and trying to include menu.jsp
when statut value is either ADMIN or USER, you can do it like:
<% if (statut.equals("ADMIN") || statut.equals("USER")) { %>
<jsp:include page="menu.jsp" flush="true"/>
<% }%>
Note that menu.jsp
should be in the same folder of your current jsp, else give relative path.
Upvotes: 1
Reputation: 18030
The <%@ include file="menu.jsp"%>
is static include, so it will include contents of the menu.jsp
no matter of the condition. But it will be executed only if the condition is true.
The <jsp:include page="menu.jsp" flush="true"/>
is dynamic include, so, the menu.jsp
page will actually be called only if the condition is satisfied. But from the other side menu.jsp
must be a full page, not a page fragment, and cannot use variables defined in the 'parent' page.
So, it really depends on what you want to achieve.
And as Marco suggested, you should use "ADMIN".equals(statut)
instead of ==
.
Upvotes: 3
Reputation: 149075
If all you want is the possibility to use <c:if>
you must have a scoped variable. Attributes of current request, session of application context are with respective scope being request, session and application.
You can easily put variables in page context (valid only for the current jsp, and others included by @include
but not by <jsp:include>
) :
<%
...
String statut = useraction.Connect();
pageContext.setAttribute("statut", statut);
%>
<c:if test="${statut == 'ADMIN'}">
...
</c:if>
But if you want to to many excluvise test the correct tag is <c:choose>
:
<%
String statut = useraction.Connect();
pageContext.setAttribute("statut", statut);
%>
<c:choose>
<c:when test="${statut eq 'ADMIN'}">
...
</c:when>
<c:when test="${statut == 'USER'}">
...
</c:when>
<c:otherwise>
<p>Status ${statut} not found</p>
</c:otherwise>
</c:choose>
I've just tested it it works (on my machine ...), and the otherwise clause could explain why you do not get what you want.
Upvotes: 1
Reputation: 11
so i must use the . what i want is to include different pages depending on the statut value.
<%
UtilisateurAction useraction = new UtilisateurAction();
String statut = useraction.Connect();
//System.out.println(statut);
if(statut=="ADMIN"){
%> <%@ include file="menu.jsp"%>
<%}
else {if(statut=="USER"){%>
<%@ include file="menuother.jsp"%>
<%}} %>
Upvotes: 0