简体   繁体   中英

Reuse object and its methods in code of multiple @ManagedBeans

I want to set my User object only once through my @RequestScoped LoginBean. Then I want to reuse its setters, getters and an isLoggedIn() method in other @ManagedBean through CDI.

Request Scoped Class that Sets User Object

@ManagedBean
@RequestScoped
public class LoginBean {

    @ManagedProperty(value = "#{bean}")
    protected Bean bean;

    private String username;
    private String password;

    public String login() {
        bean.setLoggedInUser(userDao.getUser(username));
        return "index";
    }

    // Getters and Setters, including for the @ManagedProperty baseBean.

}

SessionScoped Class that Stores User Object

@ManagedBean
@SessionScoped
public class Bean {

    private User loggedInUser = null;

    public boolean isLoggedIn() {
        return loggedInUser != null;
    }

    // Getters and setters for loggedInUser

}

Class Where I Want To Refer to loggedInuser

@ManagedBean
@RequestScoped
public class ShowUserDetails extends Bean {

    private Details details = new Details();

    public void showDetails() {
    if(isLoggedIn()) { // THIS ALWAYS RETURNS FALSE
          // Do stuff
        }
    }

}

Solutions So Far

  • I can list a Bean @ManagedProperty in every single Backing Bean that needs the loggedInUser. This seems wrong as I am copy-pasting two lines in every class.
  • I can get the instance of Bean class from FacesContext using context.getApplication().evaluateExpressionGet() . This allows me to have one method to retrieve Bean instance in a superclass, however this also seems wrong. That said, this is the method I will go with if I am unable to find a pure CDI solution.

You are worried about adding two lines of code once in each bean, yet you do want to write

if(isLoggedIn()) { // THIS ALWAYS RETURNS FALSE
      // Do stuff
    }

And most likely many times in a bean (and most likely also things in an else statement).

Then I'd certainly go fo using annotations and interceptors

See also

My solution was to use the HttpSession to store the User object instead of having a class member variable. This allowed me to have one class that handled the getting/setting and all the other classes could simply call 'getLoggedinUser' to retrieve the entire object without hitting the DB.

private HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
private static final String LOGGED_IN_USER = "loggedInUser";

public User getLoggedInUser() {
    return (User) session.getAttribute(LOGGED_IN_USER);
}

public void setLoggedInUser(User user) {
    session.setAttribute(LOGGED_IN_USER, user);
}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM