2013-10-26 61 views
0

我在爲我的jsp頁面編寫if-then-else條件時遇到了一些問題。我認爲這個問題與我的報價有關。也有可能在JavaScript中使用JSTL?JSTL if-then-else session屬性

代碼

<c:choose> 
    <c:when test= "'<%=request.getSession().getAttribute("userName")%>' == Guest"> 
     <button class="btn" id="getCitizens" onclick="DoGuestAccess()" type="button">Guest Access</button> 
    </c:when> 
    <c:otherwise> 
     <button class="btn" id="getCitizens" onclick="DoUsersAccess()" type="button">User Access</button> 
    </c:otherwise> 
</c:choose> 

錯誤

org.apache.jasper.JasperException: /WEB-INF/jsp/newpage.jsp (line: 485, column: 71) equal symbol expected 
+1

沒有事實並非如此。 JSTL只能在服務器端解釋。 – Farid

+0

所以我應該將JSTL值傳遞給html元素,然後使用javascript從條件元素中獲取值? – devdar

+0

JSTL可以用來渲染JavaScript。 –

回答

2

這看起來與測試表達式有問題,試試這個:

<c:choose> 
    <c:when test= "${request.getSession().getAttribute("userName").equals("Guest")}"> 
     <button class="btn" id="getCitizens" onclick="DoGuestAccess()" type="button">Guest Access</button> 
    </c:when> 
<c:otherwise> 
    <button class="btn" id="getCitizens" onclick="DoUsersAccess()" type="button">User Access</button> 
</c:otherwise> 

另外,Java使用equals方法進行字符串比較。

或者更詳細:

<% var userName = request.getSession().getAttribute("userName"); %> 
<c:choose> 
    <c:when test= "${userName.equals("Guest")}"> 
     <button class="btn" id="getCitizens" onclick="DoGuestAccess()" type="button">Guest Access</button> 
    </c:when> 
<c:otherwise> 
    <button class="btn" id="getCitizens" onclick="DoUsersAccess()" type="button">User Access</button> 
</c:otherwise> 

+0

「$ {userName.equals('Guest')}」爲我工作 – devdar

+1

是的,'$ {..}'是重要的,不確定引號,有時會轉義幫助:「$ {userName.equals(\」客人\」)}」。單引號用於java中的字符,但如果它起作用,它就可以工作。 –