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.
So having this bean:
@ManagedBean
@RequestScoped
public class TimeBean{
public Date getTime(){
return new Date();
}
}
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.
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>