【问题标题】:Trying to set and get attribute from one class to another via a 3rd class in JAVA尝试通过 JAVA 中的第 3 类设置和获取从一个类到另一个类的属性
【发布时间】:2016-11-03 02:45:22
【问题描述】:

我有一个看起来像这样的 bean 类

@ManagedBean(name = "usingBean")
@SessionScoped
public class UserInfo implements Serializable {

    private static final long serialVersionUID = 2668727340500045081L;

    String loginId;

}

我在过滤器类中设置了这个 bean 属性。

我正在尝试在另一个 bean 类中获取此属性

@ManagedProperty(value = "#{usingBean}")
private UserInfo user;

public UserInfo getUser() {
    return user;
}

public void setUser(UserInfo user) {
    this.user = user;
}
UserInfo neededBean = (UserInfo) context.getApplication()
                .createValueBinding("#{usingBean}").getValue(context);
                return neededBean.getLoginId();

当我尝试打印它时它显示为 null,但它确实被插入到数据库中。当不同的用户登录时它不会改变。

【问题讨论】:

    标签: java jsf httpsession facescontext


    【解决方案1】:

    尝试用简单的方法,在您的过滤器类中将您的属性设置为会话

           FacesContext context = FacesContext.getCurrentInstance();
            HttpServletRequest request = (HttpServletRequest) context
                    .getExternalContext().getRequest();
            HttpSession httpSession = request.getSession(false);
            httpSession.setAttribute("loginId", loginId);
    

    在其他类中,您可以从会话中获取“loginId”...

            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletRequest request = (HttpServletRequest) context
                    .getExternalContext().getRequest();
            HttpSession httpSession = request.getSession(false);
            String loginId= (String) httpSession.getAttribute("loginId");
    

    【讨论】:

    • 你调试你的代码吗?当您的会话值更改为 null 时!
    • 我明白了..非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2010-12-04
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多