0

我正在尝试从一本书中学习 Java,并且我已经完成了最后一章,这让我有点陷入困境。它显示了一个包含值表达式的 JSF 文件:

#{timeBean.time}

它还显示了 TimeBean.java 文件,其中包含一个getTime()方法,而该方法又具有一个变量time。该变量不会出现在该方法之外。这本书说#{timeBean.time}调用getTime()但我不明白如何调用,所以我不能将它扩展到其他应用程序。

为了可能的澄清,问题是我不明白这.time部分是从哪里来的#{timeBean.time}

4

2 回答 2

2

JSF 创建称为托管 bean 的 bean 实例,您可以使用#{}包装的表达式(也称为EL 表达式)从页面调用这些实例。#{timeBean.time}实际上是从实例调用getTime()getter 。timeBean默认情况下,使用类简单名称引用 Bean 实例,并且它们的第一个字符小写。

所以有这个bean:

@ManagedBean
@RequestScoped
public class TimeBean{
    public Date getTime(){
        return new Date();
    }
}

通过@ManagedBean注解我们告诉 JSF 它需要由它来管理。由于@RequestScoped我们表达了 bean 的范围,实际上 JSF 会为每个浏览器请求创建一个 bean 实例,并且getTime()每次您在页面中指定它时都会调用 getter 方法。

对于表单字段,您必须指定一个同时具有 getter 和 setter 方法的变量。这是因为 JSF 将在处理表单时设置该值。

@ManagedBean
@RequestScoped
public class TimeFormBean{

    //Initializes time with current time when bean is constructed
    private Date time = new Date();

    public Date getTime(){
        //No logic here, just return the field
        return time;
    }

    public void setTime(Date d){
        time=d;
    }

    public void processTime(){
        System.out.println("Time processed: " + time);
    }

}

然后您可以通过这种方式在表单输入中使用它:

<h:form>
    <h:inputText value="#{timeFormBean.time}">  
        <f:convertDateTime pattern="yyyy-MM-dd"/>  
    </h:inputText>
    <h:commandButton value="process" action="#{timeFormBean.processTime}" />
</h:form>
于 2013-09-06T19:56:35.160 回答
0

您正在寻找的概念称为“Java Beans”。

在 Java 中,Java Bean 使用特定的命名约定实现 getter(也称为访问器)和 setter(也称为 mutator)。

我更容易证明描述命名约定。

boolean xxxBlammo;
Boolean hoot; // Note that this is not a boolean (primative).
String  smashy;  // the key is that this is not a boolean.

// convention: starts with is, first letter of property is capatalized.
public boolean isXxxBlammo() 
{
    return xxxBlammo;
}

// Note that the return type is not the primative boolean.
// convention: starts with get, first letter of prooperty is capatalized.
public Boolean getHoot()
{
    return hoot;
}

// The naming convention is the same for getSmashy as it is for getHoot.
// convention: starts with get, first letter of prooperty is capatalized.
public String getSmashy()
{
    return smashy;
}

// starts with set, first letter of property is capatalized.
public void setXxxBlammo(final boolean newValue)
{
    xxxBlammo = newValue;
}

// same naming convention for all setters.
public void setHoot(final Boolean newValue) ...
public void setSmashy(final String newValue) ...

EL 表达式 #{beany.smashy} 引用“beany”Java Bean 的“smashy”属性,这意味着它转换为对 getSmashy() getter 的调用。

在您的情况下,#{timeBean.time} 引用“timeBean”Java Bean 的“time”属性,这意味着它转换为对 getTime() getter 的调用。

于 2013-09-06T20:06:18.040 回答