ManagedBean方法在JSF中不起作用

时间:2014-12-12 15:17:54

标签: jsf

我编写了两个名为MessageHelloWorld的托管bean类。它们如下:

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}完美打印信息。但是<h:commandButton> does not invoke the method showMsg()`。问题是什么?

3 个答案:

答案 0 :(得分:4)

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

此外,您在评论中告诉我们,您不能同时使用@RequestScoped@SessionScoped,请选择一个。并且,action属性应解析为String(showMsg()返回void),它用于执行导航。如果您只是想完成某项操作而无需导航,请改用actionListener

答案 1 :(得分:0)

{p> ELjsf中区分大小写。您已将action="#{helloworld.showMsg}与小写w一起使用,并使用大写@ManagedBean(name="helloWorld")声明W。试试吧,action="#{helloWorld.showMsg}

答案 2 :(得分:0)

如果有人意外使用其他导入,则ManagedBean注释不起作用,例如javax.annotation.ManagedBean。它必须是javax.faces.bean.ManagedBean