How conditionally show the content of a div rather than another div in a JSP page?

我们两清 提交于 2019-12-21 21:42:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!