nervosol
nervosol

Reputation: 1291

Target Unreachable, 'null' returned null in JSF2

I am quite new to JSF and I have this problem. I was reading some posts about that but I could found answer( or I didnt understood one...). I have following user bean:

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped
public class User implements Serializable {

    private String login;


    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }
}

and login bean:

@ManagedBean(name="login")
@SessionScoped
public class Login implements Serializable{
    private static final long serialVersionUID = 1L;

    @ManagedProperty("#{user}")
    private User user;
    @PostConstruct
    public void init() {
        System.out.println("Init called");
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

And my view looks like this:

<h:inputText id="login" value="#{login.user.login}" required="true"/>
<h:commandButton value="Login" action="#{login.user.login}"/><br/>

I want access to user fields in few classess and this how I am trying to achieve this. Unfortunately I keep got this error. I have found some information that I need beans.xml. Is that true? Where can I find sample? I am using JSF2.

Answer My fault was that I choose same name for field and for login method. Because of that I was using login.login( before implementing User class) for geting login, and login.login as a action of commandButton. After I implemented User class I changed both login.login to login.user.login. Thanks again for help.

Upvotes: 0

Views: 229

Answers (1)

atamanroman
atamanroman

Reputation: 11818

You are binding a method User#login() to your CommandButton, which does not exist. There is only a property login (get/set).

You need a proper action method in your User bean:

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped
public class User implements Serializable {

    private String login;


    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public void doLogin() { 
        // whatever you want to do here
    }
}

and bind to the doLogin() method:

<h:commandButton value="Login" action="#{login.user.doLogin}"/>

beans.xml is required to enable CDI, which you don't use here. You are using jsf managed beans. CDI is a more powerful alternative.

Upvotes: 1

Related Questions