Reputation: 1188
What is the correct (best) way to set a managed bean's property from a request's parameter?
The URL for my JSF page looks something like this:
https://eample.com/app/faces/page.xhtml?ts=2012-01-05T10:00:00.000
I have found that I can read the parameter using the following:
<h:outputText value="#{param['ts']}" />
But what I really need to do is set my bean's property from this value. So what is the best JSF way code this so I get something which results Java code like this:
myBean.setTimestamp(request.getParameter("timestamp"));
Many thanks
Upvotes: 0
Views: 3336
Reputation: 1108722
Based on your question history, you're using JSF2, so just the <f:viewParam>
should do.
<f:metadata>
<f:viewParam name="ts" value="#{myBean.timestamp}" />
</f:metadata>
That's it.
As <f:viewParam>
extends from UIInput
(like <h:inputText>
and so on), you can even perform conversion and validation on it using e.g. <f:convertDateTime>
and required="true"
.
<f:metadata>
<f:viewParam id="ts" name="ts" value="#{myBean.timestamp}" required="true">
<f:convertDateTime pattern="yyyy-MM-dd'T'HH:mm:ss.SSS" />
</f:viewParam>
</f:metadata>
...
<h:message for="ts" />
This way the #{myBean.timestamp}
can be a fullworthy java.util.Date
property. Any conversion and validation errors will end up in the <h:message>
associated with <f:viewParam id>
.
Note that unlike with @ManagedProperty
, the #{myBean}
can just be a @ViewScoped
one.
Upvotes: 0
Reputation: 108889
Assuming a JSF managed bean with request scope, inject it as a managed property:
import javax.faces.bean.*;
@ManagedBean @RequestScoped
public class ReqBean {
@ManagedProperty("#{param.ts}") private String ts;
public String getTs() {
return ts;
}
public void setTs(String ts) {
this.ts = ts;
}
}
If the bean is in a broader scope, you will need to look it up programmatically:
private String lookUpTs() {
return FacesContext.getCurrentInstance()
.getExternalContext()
.getRequestParameterMap()
.get("ts");
}
If you are using CDI beans, you will need to consider other options (see here for one approach.)
Upvotes: 1