Vivek Vardhan
Vivek Vardhan

Reputation: 1178

Getting Null pointer Exception while String comparision

I have written a simple login module in jsp (a lot of scriplets are there :) ). But, i am continuously getting NullPointer exception error. I am not able to find, i tried a lot.

JSP Login code

<form action="loginAction.jsp" method="post" name="config-form">
<table align="center">
    <tr>
        <td> UserName:</td>
        <td><input type="text" name="username" required parameter=*"></td>
    </tr>
    <tr>
        <td> Password:</td>
        <td><input type="password" name="username" required parameter=*"></td>
    </tr>
    <tr><td><input type="submit" value="LogIn"></td></tr>
</table>

LoginAction.jsp

<body>
<%
    String username=request.getParameter("username");
    String password=request.getParameter("password");


    LoginModel login = new LoginModel();
    login.setUsername(username);
    login.setPassword(password);

    LoginValidator validator = new LoginValidator();
    boolean validate=validator.validateLogin(login);

    if(validate==false)
    {
        response.sendRedirect("login.jsp");
    }
    else
    {
        response.sendRedirect("index.jsp");
    }

%>

LoginModel.java

public class LoginModel {
private String username;
private String password;
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}

}

LoginValidator.java

public boolean validateLogin(LoginModel login)
{
    String uname="vivekaltruist";
    String passwd="somePassword";
    System.out.println(login.getUsername());
    if((login.getUsername().equals(uname)) && login.getPassword().equals(passwd))
    {
        return true;
    }
        return false;
}

The Stacktrace:

java.lang.NullPointerException at LoginValidator.validateLogin(LoginValidator.java:12)

I am sure, it will be a silly reason,but i am not able to find it. The same thing, i tried without jsp, its working fine. Help me out

Upvotes: 1

Views: 435

Answers (2)

user2813412
user2813412

Reputation: 31

The problem here

<td><input type="text" name="username" required parameter=*"></td>
<td><input type="password" name="username" required parameter=*"></td>

Your tows field have same name.While processing,there is not password value gotten

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280179

You've named your password input parameter username too

<td><input type="password" name="username" required parameter=*"></td>

This

String password=request.getParameter("password");

will return null because there is no request parameter identified by password and eventually cause a NullPointerException when you try to get it and call equals() on it. Change its name attribute to "password".

Upvotes: 4

Related Questions