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.
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(""))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With