问题描述
我正在尝试从一本书中学习Java,并且已经读到最后一章了,这使我有些困惑.它显示了一个包含值表达式的JSF文件:
I'm trying to learn Java from a book and I've made it to the last chapter which is throwing me a bit for a loop. It shows a JSF file that contains the value expression:
#{timeBean.time}
它还显示了TimeBean.java文件,其中包含一个getTime()
方法,该方法又具有一个变量time
.该变量不会出现在该方法之外.这本书说#{timeBean.time}
调用getTime()
,但是我不知道如何,所以不能将其扩展到其他应用程序.
It also shows the TimeBean.java file, which contains a getTime()
method, which in turn has a variable time
. The variable does not appear outside that method. The book says that #{timeBean.time}
calls getTime()
but I don't understand how, so I can't extend it to other applications.
为澄清起见,问题在于我不理解#{timeBean.time}
For possible clarification, the problem is that I don't understand where the .time
part is coming from in #{timeBean.time}
推荐答案
JSF创建了称为托管bean的bean实例,您可以使用#{}
包装的表达式(也称为 EL表达式. #{timeBean.time}
实际上是从timeBean
实例调用getTime()
getter.缺省情况下,Bean实例以简单名称类引用,其首字符小写.
JSF creates bean instances called managed beans, which you can call from your pages using #{}
wrapped expressions, also called EL expressions. #{timeBean.time}
is actually invoking getTime()
getter from timeBean
instance. Bean instances are referred by default with classes simple name with their first character lowercased.
所以有这个豆子:
@ManagedBean
@RequestScoped
public class TimeBean{
public Date getTime(){
return new Date();
}
}
使用@ManagedBean
注释,我们告诉JSF它需要由它管理.使用@RequestScoped
,我们可以表示bean的范围,实际上,每次在页面中指定JSF时,JSF都会为每个浏览器请求创建一个bean实例,并调用getTime()
getter方法.
With @ManagedBean
annotation we tell JSF that it need to be managed by it. With @RequestScoped
we're expressing the scope of the bean, actually JSF will create one bean instance per browser request and will call getTime()
getter method, each time you specify it in your page.
对于表单字段,必须指定一个同时具有getter和setter方法的变量.这是因为在处理表单时,JSF将设置该值.
For form fields, you must specify a variable which has both getter and setter methods. That's because JSF will set that value when form is processed.
@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);
}
}
然后您可以通过以下方式在表单输入中使用它:
Then you can use it in form inputs that way:
<h:form>
<h:inputText value="#{timeFormBean.time}">
<f:convertDateTime pattern="yyyy-MM-dd"/>
</h:inputText>
<h:commandButton value="process" action="#{timeFormBean.processTime}" />
</h:form>
这篇关于JSF值表达式和bean,它们如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!