Reputation: 7890
Here is an quote from Oracle JavaEE 6 tutorial docs for passing parameter in value expression and method expression in JSF 2.
Parameters are supported for both value expressions and method expressions. In the following example, which is a modified tag from guessNumber application, a random number is provided as an argument rather than from user input to the method call:
<h:inputText value="#{userNumberBean.userNumber('5')}">
The above example uses a value expression.
And this is the default one:
<h:inputText value="#{userNumberBean.userNumber}">
Bean class -
import java.util.Random;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserNumberBean {
Integer randomInt = null;
Integer userNumber = null;
public UserNumberBean() {
Random randomGR = new Random();
randomInt = new Integer(randomGR.nextInt(10));
System.out.println("Duke's number: " + randomInt);
}
public void setUserNumber(Integer user_number) {
userNumber = user_number;
}
public Integer getUserNumber() {
return userNumber;
}
}
The following expression is not passing 5 as a parameter to the inputText:
<h:inputText value="#{userNumberBean.userNumber('5')}">
It actually causes an error at run-time.
My question: How do I achieve this ??
Upvotes: 6
Views: 8132
Reputation: 22692
You don't need to pass a parameter in the example you've provided.
In this situation getters and setters are invoked automatically on your backing bean.
The following code will invoke getUserNumber and/or setUserNumber to retrieve and/or modify the value of the inputText component:
<h:inputText value="#{userNumberBean.userNumber}">
The form value entered by the user will be passed to setUserNumber as a parameter.
To pass a parameter to a backing bean method, you might do something like this:
<h:commandButton action="#{userNumberBean.displayAlert('Hey')}" value="Say Hey"/>
<h:commandButton action="#{userNumberBean.displayAlert('Later')}" value="Say Bye"/>
This would invoke a method that looks like this:
public String displayAlert(String someText)
As Bhesh Gurung's answer suggests, you can set userNumber to 5 by default in the constructor.
You could also use one of the methods suggested here to apply a default value.
Upvotes: 5
Reputation: 51030
To set (display) 5 as the default value in the textbox, make the following change in the view -
<h:inputText value="#{userNumberBean.userNumber}">
and set the value of the property in the managedbean:
@ManagedBean
@SessionScoped
public class UserNumberBean {
private Integer randomInt = null;
private Integer userNumber = null;
public UserNumberBean() {
//...
this.userNumber = 5; // try this here
}
//getter/setter
Upvotes: 2