Defining and reusing an EL variable in JSF page

JsfJsf 2El

Jsf Problem Overview


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 !

Jsf Solutions


Solution 1 - Jsf

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 https://stackoverflow.com/questions/3342984/jstl-in-jsf2-facelets-makes-sense

Solution 2 - Jsf

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}"
/>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlbert GanView Question on Stackoverflow
Solution 1 - JsfBalusCView Answer on Stackoverflow
Solution 2 - JsfMatt BallView Answer on Stackoverflow