Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If session exist or not

I am trying to write my first app on Google App Engine, I was trying to maintain a session, I created a login page on submit, it call to a servlet, servlet validates the user and create a new session using the following code.

void createSession(String Username) {
        getThreadLocalRequest().getSession(true).setAttribute("Username", Username);
    }

login page after calling the servlet redirects to some page i.e. abc.jsp, my abc.jsp page contains

<body><%
        try {
            if (request.getSession(false) == null) {

            } else {
    %>
    Welcome to
    <%=session.getAttribute("Username")%>
    <%
        if (session.getAttribute("Username").equals("")) {
    %>
    <a href="login.jsp"><b>Login </b></a>
    <%
        } else {
    %>
    <a href="logout.jsp"><b>Logout</b></a>
    <%
        }
            }
        } catch (Exception e) {

        }
    %></body>

it works fine, but when I access abc.jsp without creating a session it is throwing an exception at this if (session.getAttribute("Username").equals("")) line, I dunno why kindly help me. I think it dont detect if session exists. but I have read so many threads like this It gave me this solution, I dunno what I am doing wrong.

like image 861
Muaz Usmani Avatar asked Aug 12 '12 21:08

Muaz Usmani


1 Answers

As far as I remember

session.getAttribute("xyz")

returns null if the attribute does not exist... so your NullPointerException occurs because you try to call equals on null.

I suggest to do a check on your attribute itself before validating its content:

if (session.getAttribute("Username") == null || session.getAttribute("Username").equals(""))
like image 171
Pr0gr4mm3r Avatar answered Sep 28 '22 19:09

Pr0gr4mm3r