Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data between JSF beans

I'm having this problem with passing on data between JSF beans.. What I want to do is when I login, pass the username to a next bean where I can use it. I have found many things about this but I can't get it to work in my project. What I've got is a UserService where I can manage my users. There's a method in here called getUsers(username). Now I'm trying to pass the username so I can retrieve my user-object.

xHtml:

        <h:link outcome="changeProfile" value="Change profile">
            <f:param name="username" value="#{userBean.username}" />
        </h:link>

changeProfileBean:

@Component("changeProfile")
@ManagedBean
@RequestScoped
public class ChangeProfileBean implements Serializable {

private UserService userService;
private User user;

@ManagedProperty("#{param.username}")
private String username;

@PostConstruct
public void init(){
    FacesContext facesContext = FacesContext.getCurrentInstance();
    this.username = facesContext.getExternalContext().getRequestParameterMap().get("username");

    try {
        if(username != null){
            user = userService.getUser(username);
        }
    } catch (UserServiceException e) {
        e.printStackTrace();
    }
}

@Autowired
public ChangeProfileBean(UserService userService) {
    this.userService = userService;
}

What happens is that the changeUserbean will be created when the app is starting. And immediately after that runs the @PostConstruct where username obviously equals null. But when I call the changeUserBean it doesn't execute the @PostConstruct anymore.. Does anybody know what I could do?

UserBean:

@Component("userBean")
@Scope("session")
public class UserBean implements Serializable
{
    @Autowired
    private UserService userService;

    @Autowired
    private RepairService repairService;

    private String username;
    private String password;
like image 809
Maarten Meeusen Avatar asked Nov 01 '22 08:11

Maarten Meeusen


1 Answers

While you have already the data you need in a broader scope, just inject that backing-bean into changeProfileBean:

@ManagedBean
@RequestScoped
public class ChangeProfileBean implements Serializable {

    @ManagedProperty("#{userBean}")
    private UserBean userBean;

    public UserBean getUserBean(){
        return userBean;
    }
    public void setUserBean(UserBean userBean){
        this.userBean = userBean;
    }
    ...
}
like image 191
Omar Avatar answered Nov 15 '22 05:11

Omar