问题
I am very new in JSP development and I have the following doubt.
If into a JSP page I have 2 div like this:
<div id="succes">
<p>SUCCESS</p>
</div>
<div id="failure">
<p>FAILURE</p>
</div>
and I have to show only one of these div according to the value of a status variable putted into the Http Session that can have only 2 value: OK and KO.
Can I do something like this:
<% if(request.getSession(false).getAttribute("status")=="OK"> { %>
<div id="succes">
<p>SUCCESS</p>
</div>
<% } %>
<% else { %>
<div id="failure">
<p>FAILURE</p>
</div>
<% } %>
It works? Is it ok? or there are some better way to achieve this task? (maybe can I do something like this using JavaScript\JQuery?)
回答1:
With JSPs the right way to do it is using JSTL tags. Google for 'jstl tutorial' and read up what is offered.Your example uses scriptlets instead. Though that would get it done too but is not the right way to do it. One example is shown below:
<c:choose>
<c:when test= "${request.getSession().getAttribute("userName").equals("Guest")}">
<div> Welcome Guest</div>
</c:when>
<c:otherwise>
<div> Welcome Real User</div>
</c:otherwise>
</c:choose>
来源:https://stackoverflow.com/questions/27273220/how-conditionally-show-the-content-of-a-div-rather-than-another-div-in-a-jsp-pag