saluyotamazing saluyotamazing - 1 year ago 71
HTML Question

Why am I getting this error using if statement in jsp?

Here is my code for the LoginServlet class.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userName = request.getParameter("username");
String password = request.getParameter("password");

boolean loginFailed;

User user = null;

user = loginService.getUser(userName);

if(user != null && user.getPassword().equals(password)){

userType = loginService.getUserType(user).getUser_type();

HttpSession session = request.getSession();
session.setAttribute("username", user.getUsername());

loginFailed = true;

request.setAttribute("username", userName);
request.setAttribute("loginFailed", loginFailed);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp");
dispatcher.forward(request, response);

I have boolean named loginFailed. It will be give a value true when the user does not have an account. I made a code in my jsp page to check this variable. Here is my jsp code.

<div class="container container-table" id="login">
<div class="row vertical-center-row">
<div class="col-md-4 col-md-offset-4">
<div style="background-color: #297f56; padding: 15px; border-radius: 5%;">
<h1 style="text-align: center; color: white;">JJ STORE</h1>
<% Boolean loginFailed = (Boolean) request.getAttribute("loginFailed");
out.println("<div class='alert alert-warning'>Warning! Dont submit this.</div>");
<form action="processLogin" method="post">
<div class="form-group" >
<label for="email" style="color: white;">Username:</label>
<input type="text" class="form-control" name="username" value="${username}">
<div class="form-group">
<label for="pwd" style="color: white;">Password:</label>
<input type="password" class="form-control" name="password">
<button type="submit" class="btn btn-default">Submit</button>

I am not sure what is the problem here. I tried changing the condition in the if block by putting "true" and code went smoothly. However, if I put the boolean I got from the servlet, it gives me this error.

enter image description here

What am I doing wrong?

Answer Source

You're only setting loginFailed when it fails. When it succeeds, you're not setting the attribute, so you're getting a null value in the JSP, resulting in a NullPointerException when you call if(loginFailed).

One way to fix the problem is to test the Boolean object without unboxing:

if (Boolean.TRUE.equals(loginFailed))

Another option is to make sure to set the attribute whether it succeeds or fails:

if (user != null && user.getPassword().equals(password)) {
    loginFailed = false;
} else {
    loginFailed = true;
request.setAttribute("loginFailed", loginFailed);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download