2015-09-11 15 views
0

這裏是我的代碼:如何根據會話屬性的值更改包含在JSP頁面中的頭文件?

<% 
if(session.getAttribute("loggedIn").equals(null)) 
{ 

%>  

<%@ include file="header.jsp"%> 

    <% 
} 
else if(session.getAttribute("loggedIn").equals("user")) 
{ 
    %> 

    <%@ include file="pheader.jsp"%> 

    <% 
} 
    %> 

這是我如何設置會話屬性:

if(utype.equals("admin")) 
{ 
    session.setAttribute("loggedIn", "admin"); 
} 
else 
{ 
    session.setAttribute("loggedIn", "user"); 
} 

這是拋出一個空指針異常。 我明白,因爲沒有人登錄,屬性值爲空。

我該如何解決這個問題?

+0

這可能有幫助 - http://stackoverflow.com/questions/4988086/include-file-from-dynamic-property-value –

+0

採取一個變量,如果會話等於空或第一個條件爲真然後設置'標題。 jsp'中的變量,如果會話不等於null或第二個條件爲真,則在變量中設置'pheader.jsp'。並像這樣使用 - ..(在這兩種情況下使用此jsp:include ...行)。 –

+0

但是,NullPointerException在'if(..)'部分。 @PuneetChawla – Nivedita

回答

2

首先,不要在JSP中使用scriptlets。使用JSTL和EL:

<c:choose> 
    <c:when test="empty loggedIn"> 
    <%@ include file="header.jsp"%> 
    </c:when> 
    <c:when test="loggedIn == 'user'"> 
    <%@ include file="pheader.jsp"%> 
    </c:when> 
    <c:otherwise> 
    <%-- handle the default case --%> 
    </c:otherwise> 
</c:choose> 

第二,如果你堅持要用scriplets,做

if (session.getAttribute("loggedIn") == null) 

,而不是

if (session.getAttribute("loggedIn").equals(null)) 

因爲你不能調用equals方法,如果沒有目的。

+0

Hey Thannx! :)不知道關於equals()方法的東西。我不知道如何使用JSTL和EL。儘管我會盡力學習。 – Nivedita

+0

嘿@Jozef Chocholacek,你的回答看起來是正確的。但是,我們不能通過在JSP中使用腳本來做到這一點嗎? –

+0

@PuneetChawla你可以(見我的答案的第二部分),但你不應該:http://www.coderanch.com/how-to/java/WhyNotUseScriptlets –