If session exist or not

40,317

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(""))
Share:
40,317
Muaz Usmani
Author by

Muaz Usmani

Updated on July 30, 2022

Comments

  • Muaz Usmani
    Muaz Usmani almost 2 years

    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.