问题描述:

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

  • https://code.google.com/p/jee6-cdi/source/browse/tutorial/cdi-aop-example/src/main/java/org/cdi/advocacy/security/
  • http://balusc.blogspot.nl/2013/01/apache-shiro-is-it-ready-for-java-ee-6.html
网友答案:

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);
}`
相关阅读:
Top