1

Here is my code:

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

%>    

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

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

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

    <%
 }
    %>

This is how I am setting the session attribute:

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

This is throwing a null pointer exception. I understand since nobody is logged in, the attribute value is null.

How do I fix this?

user63762453
  • 1,734
  • 2
  • 22
  • 44
  • This may help - http://stackoverflow.com/questions/4988086/include-file-from-dynamic-property-value – Puneet Chawla Sep 11 '15 at 07:51
  • Take a variable and if session equals to null or first condition is true then set 'header.jsp' in a variable and if session is not equal to null or second condition is true then set 'pheader.jsp' in a variable. and use like this - .. (Use this jsp:include... line in both condition). – Puneet Chawla Sep 11 '15 at 07:58
  • But, the NullPointerException is in the `if(..)` part. @PuneetChawla – user63762453 Sep 11 '15 at 07:59

1 Answers1

2

First, do not use scriptlets in JSP. Use JSTL and 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>

Second, if you insist on using scriplets, do

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

instead of

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

as you cannot invoke the equals method, if there is no object.

Jozef Chocholacek
  • 2,874
  • 2
  • 20
  • 25
  • Hey Thannx! :) Didn't know that thing about the equals() method. And I don't know how to use JSTL and EL. I will try to learn to learn though. – user63762453 Sep 11 '15 at 08:01
  • Hey @Jozef Chocholacek, your answer looks like correct. But can't we do this by using scriplets in JSP? – Puneet Chawla Sep 11 '15 at 08:19
  • @PuneetChawla You can (see the second part of my answer), but you should not: http://www.coderanch.com/how-to/java/WhyNotUseScriptlets – Jozef Chocholacek Sep 11 '15 at 08:41