【问题标题】:ManagedBean method doesn't work in JSFManagedBean 方法在 JSF 中不起作用
【发布时间】:2015-02-11 08:11:27
【问题描述】:

我编写了两个 managedbean 类,分别命名为 MessageHelloWorld。它们如下:

Message.java:

package com.bean;

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

@ManagedBean(name = "message", eager = true)
@RequestScoped
@SessionScoped
public class Message {

    private String message = "Hello World!";

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

HelloWorld.java

package com.bean;

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

@ManagedBean(name = "helloWorld")
@RequestScoped
@SessionScoped
public class HelloWorld {

   @ManagedProperty(value="#{message}")
   private Message messageBean;
   private String msg;


   public HelloWorld() {
      System.out.println("HelloWorld started!"); 
   }

   public void setMessage(String message) {
       this.msg = message;
   }

   public String getMessage() {
      if(messageBean != null){
         msg = messageBean.getMessage();
      }       
      return msg;
   }

   public void setMessageBean(Message message) {
      this.messageBean = message;
   }

   public void showMsg(){
      // String str="I am a demo string!";
       System.out.println(msg +" I am from showMsg()");
   }  
}

还有,我的index.xhtml 在这里:

<body>
    #{helloWorld.message}
    <h:form>
        <h:commandButton value="Show Msg" action="#{helloworld.showMsg}"/>
    </h:form>
</body>

#{helloWorld.message} 完美打印消息。但是&lt;h:commandButton&gt; does not invoke the methodshowMsg()`。有什么问题?

【问题讨论】:

  • #{helloWorld.showMsg} - 注意大写 W
  • 您应该使用RequestScopeSessionScope - 两者一起使用没有任何意义。
  • 仅供参考:此外,eager = true 仅适用于应用程序范围的 JSF 托管 bean。就像从@ManagedBean 注释中删除一样好。

标签: jsf


【解决方案1】:

您已将action="#{helloworld.showMsg}" 与小写w 一起用于世界。 EL 区分大小写。改为action="#{helloWorld.showMsg}"

另外,你在 cmets 中被告知,你不能同时使用 @RequestScoped@SessionScoped,选择一个。而且,action 属性应该解析为字符串(showMsg() 返回void),它用于执行导航。如果您只想完成某件事,而不需要导航,请改用actionListener

【讨论】:

    【解决方案2】:

    如果有人不小心使用了不同的导入,例如javax.annotation.ManagedBean,ManagedBean 注释不起作用。必须是javax.faces.bean.ManagedBean

    【讨论】:

    • 这不是这个实际问题的答案......但是,如果您犯了这个错误,它可能会显示相同的行为。此外,您的“答案”在其他几个问答中,其中包括:stackoverflow.com/questions/15057564/…
    【解决方案3】:

    ELjsf 中区分大小写。你已经使用了action="#{helloworld.showMsg} 和小写的w 并且你声明了@ManagedBean(name="helloWorld") 和大写的W。试试看,action="#{helloWorld.showMsg}

    【讨论】:

      猜你喜欢
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      • 2012-02-07
      • 2013-10-22
      • 1970-01-01
      • 2013-09-11
      相关资源
      最近更新 更多