【问题标题】:JSF 2.0 @ManagedProperty returns null valueJSF 2.0 @ManagedProperty 返回空值
【发布时间】:2013-05-24 11:33:29
【问题描述】:

通过定义托管属性将一个托管bean注入另一个托管bean时遇到了一些麻烦。但是该属性为空。谁能告诉我,为什么我的财产是空的? UserLoginBean.java

    @RequestScoped
public class UserLoginBean extends AbstractMB implements Serializable{

    private static final long serialVersionUID = 1L;
    private String username;
        private String password;
//getter and setter
        public void login() throws ServletException, IOException{
    try
    {
      ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); 
      HttpServletRequest request = ((HttpServletRequest)context.getRequest());

      ServletResponse resposnse = ((ServletResponse)context.getResponse());
      RequestDispatcher dispatcher = request.getRequestDispatcher("/j_spring_security_check");
      dispatcher.forward(request, resposnse);
      FacesContext.getCurrentInstance().responseComplete();
     }
    catch (Exception ex) {
        ex.printStackTrace();
        displayErrorMessageToUser("Login or Password Failed");
    }

ReclamationMB.java

@RequestScoped
public class ReclamationMB extends AbstractMB implements Serializable {
...
@ManagedProperty("#{loginBean}")
    private UserLoginBean userLogin;
/getter and setter

但在 .xhtml 中它不为空,它返回用户名:

<h:outputText value="#{loginBean.username}

【问题讨论】:

  • 既然代码中没有...属性是否定义了setter?
  • @SJuan76 OP 在他的代码中写了getter and setter
  • 是的,它在两个类中有一个 setter 和一个 getter
  • 您是否使用:@ManagedBean 注释了您的托管 bean?
  • 您是否在请求 ReclamationMB 的同一个 .xhtml 中请求 UserLoginBean?似乎只请求了 ReclamationMB,所以 UserLoginBean 将是 null,因为它是 @RequestScoped。只是猜测。

标签: jsf-2


【解决方案1】:

ReclamationMB 中的 userLogin 是 null 还是用户名是 null?如果 userLogin 不为 null,则注入工作正常,但 bean 是新创建的,因为它是 Requestscoped。 您可以将 UserLoginBean 放入 Viewscope 以防止重新创建 bean:

@ViewScoped
 public class UserLoginBean extends AbstractMB implements Serializable{...}

或者您可以通过提供 PostConstruct 方法在 ReclamationsMB 中手动填充 userLogin 所需的数据

@RequestScoped
 public class ReclamationMB extends AbstractMB implements Serializable {
 ...
 @ManagedProperty("#{loginBean}")
 private UserLoginBean userLogin; //getter and setter

 @PostConstruct
 public void init() {
   //Call Bean methods or set variables manually
   userLogin.setUsername(...);
 }

【讨论】:

  • 不,userLogin 为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 2014-06-06
相关资源
最近更新 更多