ManagedBean中@PostConstruct中设置的属性的可见性

时间:2015-02-22 11:27:22

标签: jsf jsf-2.2 postconstruct

我正在尝试在@PostConstruct中设置的@RequestScoped Bean中获取属性值。我有editUser页面从其他页面获取userId,我从@PostConstruct中的数据库获取用户,但是当我尝试在同一页面中编辑该用户时,用户对象为null,在方法editUser中。 有没有办法获得在PostConstruct中设置的对象?

这是我的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";
}

}

1 个答案:

答案 0 :(得分:1)

页面完全呈现后,@RequestScoped bean及其所有实例变量(包括user)都会被销毁。我认为这是你尝试执行导致NPE的editUser()的点。

改为使用@ViewScoped bean,以确保实例变量在回发到同一视图后仍然存在