Reputation: 21
this might be a pretty stupid question, im trying to figure out why im getting a null exception, please help.
String username = (String)session.getAttribute("username");
if (!username.equals("ADMIN")) {
request.setAttribute("Error", "You are not the admin");
RequestDispatcher rd = request.getRequestDispatcher("LoginPage.jsp");
rd.forward(request,response);
}
im trying to get the jsp to check whether the username equals "ADMIN", if it doesnt equal admin then it will give an error and then request the login page.
but i get a null pointer exception for line:
if (!username.equals("ADMIN")) {
thanks
Upvotes: 0
Views: 5394
Reputation: 17622
thats because username
is null
Best practice is to say if (!"ADMIN".equals(username))
Since a constant String "ADMIN" is a non-null value, invoking equals()
on it will not cause any error and will be safe
OR do a null check on username
before comparing:
if (username != null && !username.equals("ADMIN"))
Upvotes: 2
Reputation: 13966
Looks like username
is null, i.e. not stored in the session. If using an IDE like Eclipse, you can put a breakpoint in, hover over the term with your mouse, and see what is null.
Upvotes: 0