Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF Bean property not updated [duplicate]

Tags:

java

jsf

cdi

I have a bean with a field called 'name', and a JSF form that has an inputText mapped with this field. The initial value of the field is well displayed on the form.

The problem is when I submit the form, the value is not updated with the content of the inputText. In the savePlayer() method below, the value of name is always 'name', not what I typed inside the form input.

The bean :

@Named
@RequestScoped
public class PlayerForm {

    @Inject
    private PlayerRepository playerRepository;

    private String name = "name";


    public String savePlayer(){
        Player player = new Player();
        player.setName(name);
        playerRepository.savePlayer(player);
        return "saveUserOk";
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

The form :

   <h:form>
        <h:inputText value="#{playerForm.name}" />
        <h:commandButton value="Submit" action="#{playerForm.savePlayer}" />
    </h:form>

Thanks very much for any help!

like image 257
kgautron Avatar asked Aug 27 '11 22:08

kgautron


1 Answers

This can happen if you imported @RequestScoped from the package javax.faces.bean (JSF) instead of from javax.enterprise.context (CDI). Every single EL expression #{} would then create a brand new and completely separate instance of the bean. The given form example would then end up in two instances of the bean, one where the name is set and another where the action is invoked.

The javax.faces.bean.RequestScoped annotation can only be used in conjunction with JSF's own @ManagedBean annotation not with CDI's @Named annotation.

like image 131
BalusC Avatar answered Oct 09 '22 07:10

BalusC