【问题标题】:Reuse object and its methods in code of multiple @ManagedBeans在多个 @ManagedBeans 的代码中重用对象及其方法
【发布时间】:2015-06-03 21:35:55
【问题描述】:

我只想通过@RequestScoped LoginBean 设置我的用户对象一次。然后我想通过 CDI 在其他 @ManagedBean 中重用它的 setter、getter 和 isLoggedIn() 方法。

设置用户对象的请求范围类

@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类

@ManagedBean
@SessionScoped
public class Bean {

    private User loggedInUser = null;

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

    // Getters and setters for loggedInUser

}

我想参考loggedInuser的类

@ManagedBean
@RequestScoped
public class ShowUserDetails extends Bean {

    private Details details = new Details();

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

}

目前的解决方案

  • 我可以在每个需要loggedInUser 的Backing Bean 中列出一个Bean @ManagedProperty。这似乎是错误的,因为我在每个班级都复制粘贴了两行。
  • 我可以使用context.getApplication().evaluateExpressionGet() 从 FacesContext 获取 Bean 类的实例。这允许我有一种方法来检索超类中的 Bean 实例,但这似乎也是错误的。也就是说,如果我找不到纯 CDI 解决方案,我会采用这种方法。

【问题讨论】:

  • 如果您有 cdi,为什么要使用 @ManagedBean

标签: java jsf-2 cdi


【解决方案1】:

您担心在每个 bean 中添加两行代码,但您确实想编写

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

并且很可能在一个 bean 中多次出现(并且很可能在 else 语句中也有很多次)。

那我肯定会去使用注解和拦截器

另请参阅

【讨论】:

    【解决方案2】:

    我的解决方案是使用 HttpSession 来存储 User 对象,而不是使用类成员变量。这使我可以拥有一个处理获取/设置的类,而所有其他类可以简单地调用“getLoggedinUser”来检索整个对象而无需访问数据库。

    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);
    }`
    

    【讨论】:

      猜你喜欢
      • 2015-11-09
      • 1970-01-01
      • 2017-07-25
      • 2021-12-04
      • 2012-10-07
      • 1970-01-01
      • 2018-09-27
      • 2015-08-10
      • 2011-10-15
      相关资源
      最近更新 更多