ManagedProperty无法正常工作 [英] ManagedProperty not working

查看:189
本文介绍了ManagedProperty无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JSF 2属性绑定方面遇到问题,老实说,我在这里碰壁.

I have problem with JSF 2 property binding and honestly I hit a wall here..

我要完成的工作是:一个请求范围的bean(loginBean)处理登录操作,并将用户名存储在会话范围的bean(userBean)中.我想通过@ManagedProperty将userBean注入loginBean,但是当调用loginBean.doLoginAction时,userBean设置为null.

What I want to accomplish is this: a request-scoped bean (loginBean) process login action and stores username in the session-scoped bean (userBean). I want to inject userBean into loginBean via @ManagedProperty, but when loginBean.doLoginAction is called, userBean is set to null.

这是代码:

UserBean类

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class UserBean {

private String username;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public boolean isLogged() {
    if (username != null)
        return true;
    return false;
}
}

loginBean类:

loginBean class:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class LoginBean {

@ManagedProperty(value = "userBean")
private UserBean userBean;

private String name;
private String password;    

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public UserBean getUserBean() {
    return userBean;
}

public void setUserBean(UserBean userBean) {
    this.userBean = userBean;
}

public String doLoginAction() {
    if (name.equals("kamil") && password.equals("kamil")) {
        userBean.setUsername(name);
    }
    return null;
}

public String doLogoutAction() {
    return null;
}
}           

有什么想法我在这里做错了吗?

Any ideas what I'm doing wrong here?

推荐答案

您需要指定EL表达式#{},而不是纯字符串:

You need to specify an EL expression #{}, not a plain string:

@ManagedProperty(value = "#{userBean}")
private UserBean userBean;

或更短,因为value服装已经是默认服装:

or, shorter, since the value attirbute is the default already:

@ManagedProperty("#{userBean}")
private UserBean userBean;

另请参见:

  • JSF2中的通信-相互之间注入托管Bean
  • See also:

    • Communication in JSF2 - Injecting managed beans in each other
    • 这篇关于ManagedProperty无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆