Nedimo
Nedimo

Reputation: 317

visibility of property set in @PostConstruct in ManagedBean

i am tryiing to get property value in my @RequestScoped Bean which is set in @PostConstruct. I have editUser page witch get userId from other page, and i am getting user from database in @PostConstruct, but when i try to edit that user in same page, user object is null, in method editUser. Is there a way to get that object, which is set in PostConstruct?

Here is my EditUserBean:

 package ba.nedim.colaborationtoolapp.model;

 import ba.nedim.colaborationtoolapp.dto.UserDTO;
 import ba.nedim.colaborationtoolapp.services.RegisterService;
 import java.io.Serializable;
 import javax.annotation.PostConstruct;
 import javax.annotation.PreDestroy;
 import javax.ejb.EJB;
 import javax.faces.bean.ManagedBean;
 import javax.faces.bean.ManagedProperty;
 import javax.faces.bean.RequestScoped;
 import org.primefaces.json.JSONObject;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;

@ManagedBean
@RequestScoped
public class EditUserBean implements Serializable{

@EJB
private RegisterService userService;
private final Logger log = LoggerFactory.getLogger(EditUserBean.class);

private int idUser;

@ManagedProperty("#{param.id}")
private int actionId;

public int getActionId() {
    return actionId;
}

public void setActionId(int actionId) {
    this.actionId = actionId;
}

private UserDTO user = new UserDTO();

public UserDTO getUser() {
    return user;
}

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

@PostConstruct
private void initialize(){
    if(actionId!=0){
        setUser(userService.getUserByID(actionId));
    }
}

public void editUser(){
    UserDTO user = getUser();
    log.info("UserID:" + user.getIdusers());
}

private String gotoUserPage(){
    return "users";
}

}

Upvotes: 0

Views: 642

Answers (1)

kolossus
kolossus

Reputation: 20691

After the page has been fully rendered, the @RequestScoped bean is destroyed along with all its instance variables (including the user). I presume this is the point at which you then attempt to execute editUser() which results in an NPE.

Use a @ViewScoped bean instead, to ensure your instance variables survive a postback to the same view

Upvotes: 1

Related Questions