Is it possible to define variable and reuse the variable later in EL expressions ?
For example :
<h:inputText
value="#{myBean.data.something.very.long}"
rendered="#{myBean.data.something.very.long.showing}"
/>
What i have in mind is something like :
<!--
somehow define a variable here like :
myVar = #{myBean.data.something.very.long}
-->
<h:inputText
value="#{myVar}"
rendered="#{myVar.showing}"
/>
Any ideas ? Thank you !
You can use <c:set> for this:
<c:set var="myVar" value="#{myBean.data.something.very.long}" scope="request" />
This EL expression will then be evaluated once and stored in the request scope. Note that this works only when the value is available during view build time. If that's not the case, then you'd need to remove the scope attribtue so that it becomes a true "alias":
<c:set var="myVar" value="#{myBean.data.something.very.long}" />
Note thus that this does not cache the evaluated value in the request scope! It will be re-evaluated everytime.
Do NOT use <ui:param>. When not used in order to pass a parameter to the template as defined in <ui:composition> or <ui:decorate>, and thus in essence abusing it, then the behavior is unspecified and in fact it would be a bug in the JSF implementation being used if it were possible. This should never be relied upon. See also JSTL in JSF2 Facelets... makes sense?
Like any view in MVC, the page should be as simple as possible. If you want a shortcut, put the shortcut into the controller (the #ManagedBean or #Named bean).
Controller:
#Named
public MyBean
{
public Data getData()
{
return data;
}
public Foo getFooShortcut()
{
return data.getSomething().getVery().getLong();
]
}
View:
<h:inputText
value="#{myBean.fooShortcut}"
rendered="#{myBean.fooShortcut.showing}"
/>
Related
Let's say I have a simple method that, like this:
public String test()
{
return "hello";
}
Now let's say I have the following PrimeFace component:
<p:fieldset styleClass="containers" rendered="#{controller.test()}">
<h2>Testing</h2>
<p:outputLabel for="test" value="Test" />
<p:inputText id="test" />
</p:fieldset>
The method above returns "hello". I would like to dynamically show and hide that fieldSet by comparing the returned value of that method to a field of one of my beans. For instance, on the rendered parameter, I would like to do something like: controller.test() != "some variable" which would return true or false. Am I allow to do that? If not, what is the way of doing it?
Basically the goal is to dynamically show and hide some container by comparing the returned value of a method with a bean property.
Look Like you misunderstood rendered
The rendered Attribute
A component tag uses a Boolean EL expression, along with the rendered
attribute, to determine whether or not the component will be rendered.
If you will check above definition you will know what exactly is the use of this attribute.
More you can see below
The rendered attribute which uses Boolean EL expression indicates
whether a component is currently visible or not. The property is
useful when you want to hide components for specific users or based on
condition. The default value of rendered attribute is true.
<h:outputText value=”mapping” rendered=”Boolean EL expression” />
For example, the commandLink component in the following section of a page is not rendered if the cart contains no items:
<h:commandLink id="check"
...
rendered="#{cart.numberOfItems > 0}">
<h:outputText
value="#{bundle.CartCheck}"/>
</h:commandLink>
With your concrete problem you can do like this
Make a String variable call value
Now create get/set methods for above variable
Now in your test method you can add
public void test(){
value="hello";
}
Bur remember you have call test() method of page load
Now in your Xhtml or Jsf or Jsp page
rendered="#{controller.value != 'hello'}"
Or better way create a Boolean variable and do all the magic of hide and show the component
I try to write my own tree component. A tree node renders as a div containing child components of the tree component, for example:
<my:tree id="extendedTree"
value="#{controller.rootNode}"
var="node">
<h:outputText id="xxx" value="#{node.name}" />
<h:commandLink value="Test" actionListener="#{controller.nodeSelectionActionListener}" />
</my:tree>
So far, so good - everything works as expected, but the h:outputText gets the same id repeatedly.
So I had my component implement javax.faces.NamingController, overwriting getContainerClientId():
#Override
public String getContainerClientId(FacesContext context) {
String clientId = super.getClientId(context);
String containerClientId = clientId + ":" + index;
return containerClientId;
}
index is set and updated during iteration over the nodes. But getContainerClientId() is called only once for every children (not for every iteration and every children, as I would expect). That causes every child id to be prefixed with the same container id:
form:treeid:0:xxx
Same thing for overwriting getClientId().
What did I miss?
The answer is hidden in the bottom of chapter 3.1.6 of JSF 1.2 specification:
3.1.6 Client Identifiers
...
The value returned from this method must be the same throughout
the lifetime of the component instance unless setId() is called, in which case it will be
recalculated by the next call to getClientId().
In other words, the outcome of getClientId() is by default cached by the JSF component as implemented in UIComponentBase#getClientId() (see also the nullcheck at line 275 as it is in Mojarra 1.2_15) and this cache is resetted when the UIComponentBase#setId() is called (see also line 358 as it is in Mojarra 1.2_15). As long as you don't reset the cached client ID, it will return the same value on every getClientId() call.
So, while rendering the children in encodeChildren() implementation of your component or the renderer which shall most probably look like this,
for (UIComponent child : getChildren()) {
child.encodeAll(context);
}
you should for every child be calling UIComponent#setId() with the outcome of UIComponent#getId() to reset the internally cached client ID before encoding the child:
for (UIComponent child : getChildren()) {
child.setId(child.getId());
child.encodeAll(context);
}
The UIData class behind the <h:dataTable> implementation does that by the way also (see line 1382 as it is in Mojarra 1.2_15). Note that this is not JSF 1.x specific, the same applies on JSF 2.x as well (and also on UIRepeat class behind Facelets <ui:repeat>).
It's worth mentioning that if your component's children have children, then it may also be necessary to refresh their cached ids, too. With this mark-up, slightly adapted from the original:
<my:tree id="extendedTree"
value="#{controller.rootNode}"
var="node">
<h:panelGroup layout="block" id="nodeBlock">
<h:outputText id="xxx" value="#{node.name}" />
<h:commandLink value="Test" actionListener="#{controller.nodeSelectionActionListener}" />
</h:panelGroup>
</my:tree>
The id for the <panelGroup> comes out OK after applying BalusC's fix above but all the sub-components come out with 0 in the iterator.
To fix that, iterate through all the levels of children too and refresh their cached ids. So:
child.setId(child.getId()); becomes uncacheId(child); where the uncacheId function is defined:
private void uncacheId(UIComponent el) {
el.setId(el.getId());
el.getChildren().forEach(this::uncacheId);
}
That may be obvious but it took me a while to figure out, so ...
h:outputText id gives you same as you didn't make it dynamic. You can create it like:
<h:outputText id="xxx_#{node.id}" value="#{node.name}" />
Assume node has an 'id' attribute which is an unique.
I know how to write out individual cookies from facelets:
JSF:
<h:outputText value="#{facesContext.externalContext.requestCookieMap['TESTCOOKIE'].value}" />
Outputs:
MyCookieValue
I have been able to write out map, but the output is not the values but a reference to the value.
JSF:
<h:outputText value="#{facesContext.externalContext.requestCookieMap}" />
Output:
{DEFAULTUSERNAME=javax.servlet.http.Cookie#36a236a2,
TESTCOOKIE=javax.servlet.http.Cookie#36b436b4,
JSESSIONID=javax.servlet.http.Cookie#36d836d8}
You don't need such a long value expression to access your cookies in JSF 2.0, there is an implicit object named cookie which references the cookie map and it's equivalent to facesContext.externalContext.requestCookieMap.
So, following code:
<h:outputText value="#{cookie['TESTCOOKIE'].value}" />
should output the same as:
<h:outputText value="#{facesContext.externalContext.requestCookieMap['TESTCOOKIE'].value}" />
Now, if you want to iterate through all of them, my recommendation is to use backing bean:
#RequestScoped
#ManagedBean(name = "triky")
public class TrikyBean {
public List getCookies() {
FacesContext context = FacesContext.getCurrentInstance();
Map cookieMap = context.getExternalContext().getRequestCookieMap();
return new ArrayList(cookieMap.values());
}
}
And then use it like this
<ui:repeat value="#{triky.cookies}" var="ck">
#{ck.name}: #{ck.value}<br/>
</ui:repeat>
Clarification: This comes from the fact that the <ui:repeat /> tag will only accept java.util.List in its value attribute, otherwise it will create its own ListModel with just one element inside. Besides, the collection given by the default implementation of the values() method in a java.util.Map is not a java.util.List but a java.util.Set, so, the <ui:repeat/> tag was using that set as the only element of its own list model and when iterating through that list model the number of elements was just one and none of them were actually cookies.
Maps have a values() method that returns a collection of all elements. I think you need a stronger EL engine than the default to do method invocation outside of getters to do that though, like JBoss EL or JUEL (both of which i strongly recommend for any java ee 6 project).
The alternative is doing method invocation in java and supplying a getter like this:
myBean.java
public Collection getCookies(){
return FacesContext.getCurrentInstance().getExternalContext().getRequestCookieMap().values();
}
And iterating over the collection in your markup
<ui:repeat value="#{myBean.cookies}" var="cookie">
<p>#{cookie.name}: #{cookie.value</p>
</ui:repeat>
Haven't tried this out but something similar will work. You might have to replace the Collection with a List, not sure if ui:repeat supports Collections.
EDIT: as per the comment below, you could try this:
<ui:repeat value="#{facesContext.externalContext.requestCookieMap.values()}" var="cookie">
<p>#{cookie.name}: #{cookie.value</p>
</ui:repeat>
The conditional operator works in many attributes like "rendered" "value" and others.
But it does not work in action? Or am I doing it wrong?
<h:commandLink action="#{true ? bean.methodTrue() : bean.methodFalse()}"/>
Error: javax.el.ELException: Not a Valid Method Expression
(I realized it using primefaces ajax action attribute)
This is not supported. The action attribute is supposed to be a MethodExpression, but the conditional operator makes it a ValueExpression syntax. I don't think this will ever be supported for MethodExpressions in EL.
You have basically 2 options:
Create a single action method which delegates the job.
<h:commandButton ... action="#{bean.method}" />
with
public String method() {
return condition ? methodTrue() : methodFalse();
}
If necessary, pass it in as method argument by #{bean.method(condition)}.
Or, conditionally render 2 buttons.
<h:commandButton ... action="#{bean.methodTrue}" rendered="#{bean.condition}" />
<h:commandButton ... action="#{bean.methodFalse}" rendered="#{not bean.conditon}" />
Is there a way to temporarily save the value of calcuation in a JSF page?
I want to do the following without calculating twice:
<h:outputText value="#{complexModel.currencyAmount.currency}">
<h:outputText value="#{complexModel.currencyAmount.amount}">
I've tried using the alias bean but I get an error saying java.lang.IllegalArgumentException - row is unavailable.
e.g.
<t:aliasBean id="bean" alias="#{bean}" value="#{complexModel.currencyAmount}">
<h:outputText value="#{bean.currency}">
<h:outputText value="#{bean.amount}">
</t:aliasBean>
Thanks.
Two ways (at least):
Using lazy-init field of your complexModel. something like:
private Currency currencyAmount;
public Currency getCurrencyAmount() {
if (currencyAmount == null) {
currencyAmount = calculateCurrencyAmount();
}
return currencyAmount;
}
Using the JSTL <c:set> tag:
(the namespace first)
xmlns:c="http://java.sun.com/jstl/core"
then
<c:set var="varName" value="#{complexModel.currencyAmount}" />
And then the calculated value will be accessible through #{varName}.
In JSF 2.0,you can use <ui:param/> which it's powerful.
<ui:param name="foo" value="#{zhangsan.foo}"/>