-1

I have started learning JSF recently I'm working on a JSF page along with a managed bean. now I'm trying to attach ajax functionality to my code but I'm facing a problem of null pointer exception.

This is my index.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:f="http://java.sun.com/jsf/core">
<h:head>
  <title>Student Registration Form</title>
</h:head>

<h:body>
    
    <h3>Please enter user name and password</h3>
    
    <h:form prependId="false">
        Username: <h:inputText id="username" value="#{student.username}" />
        
        <br></br>
        <br></br>
        
        Password: <h:inputSecret id="password" value="#{student.password}" />
        
        <br></br>
        <br></br>
        
        <h:commandButton value="Login">
            <f:ajax execute="username password" render="out" />
        </h:commandButton>
        
        <h:outputText id="out" value="#{student.greeting}"/>
        
        
    </h:form>

</h:body>

</html>

This is the Java code for the bean class

package com.ahmed.jsf.Studen_Registration;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class Student {
    
    private String username, Password;
    
    public Student() {}

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return Password;
    }

    public void setPassword(String username) {
        this.Password = username;
    }
    public String getGreeting() {
        if(username.length() == 0) return "";
        else return "Welcome to JSF 2.0 + AJAX" + username + "!";
    }
}

everything was working before adding the getGreeting function and the stacktrace states that the NullPointerException is coming from the getGreeting function

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

1 Answers1

0

When the page first loads, username is null. When checking username.length() you will get a NullPointerException because you're trying to access a method of a null value.

You can change it to username == null || username.length() == 0 (You can also use the isEmpty() method, which is the same as length() == 0).

cbender
  • 2,231
  • 1
  • 14
  • 18