Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在多个@ManagedBeans的代码中重用对象及其方法_Java_Jsf 2_Cdi - Fatal编程技术网

Java 在多个@ManagedBeans的代码中重用对象及其方法

Java 在多个@ManagedBeans的代码中重用对象及其方法,java,jsf-2,cdi,Java,Jsf 2,Cdi,我只想通过@RequestScope登录域设置一次用户对象。然后我想通过CDI在其他@ManagedBean中重用它的setter、getter和isLoggedIn方法 设置用户对象的请求作用域类 存储用户对象的SessionScoped类 类,我要在其中引用loggedInuser 迄今为止的解决办法 我可以在每个需要loggedInUser的支持Bean中列出Bean@ManagedProperty。这似乎是错误的,因为我在每节课上都要复制粘贴两行。 我可以使用context.getApp

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

设置用户对象的请求作用域类 存储用户对象的SessionScoped类 类,我要在其中引用loggedInuser 迄今为止的解决办法 我可以在每个需要loggedInUser的支持Bean中列出Bean@ManagedProperty。这似乎是错误的,因为我在每节课上都要复制粘贴两行。 我可以使用context.getApplication.evaluateExpressionGet从FacesContext获取Bean类的实例。这允许我有一个方法来检索超类中的Bean实例,但这似乎也是错误的。也就是说,如果我无法找到纯CDI解决方案,我将采用这种方法。
您担心在每个bean中添加两行代码,但是您确实想编写

if(isLoggedIn()) { // THIS ALWAYS RETURNS FALSE
      // Do stuff
    }
很可能在bean中多次出现,也很可能在else语句中出现

然后我肯定会使用注释和拦截器

另见


我的解决方案是使用HttpSession来存储用户对象,而不是使用类成员变量。这允许我有一个类来处理获取/设置,而所有其他类都可以简单地调用“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);
}`
如果您有cdi,为什么要使用@ManagedBean?
@ManagedBean
@RequestScoped
public class ShowUserDetails extends Bean {

    private Details details = new Details();

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

}
if(isLoggedIn()) { // THIS ALWAYS RETURNS FALSE
      // Do stuff
    }
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);
}`