Rectangle 27 68

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

Thanks. I'll Test this. validationErrorMap is not map. My incorrect naming. Sorry. Its array list which contains list of input fields that failed validation.

Thanks for suggestion in the update. I wanted to use a map initially. So gave that name. But later changed to list. First expression is working fine (using parentheses). Thanks a lot

java - null check in jsf expression language - Stack Overflow

java jsf el
Rectangle 27 11

This behavior is expected and by specification. Attribute values which are value expressions are set by UIComponent#setValueExpression(). They are namely supposed to be evaluated only when they are really been used, usually during view render time.

The id (and binding) attribute has special treatment: it's evaluated during view build time before it's been set, so the "regular" setter would be called instead of the setValueExpression() (because rendering of the view would otherwise crash when the id (or binding) attribute dynamically evaluates to a different value than it was during the view build time for some reason).

Better is to delegate the getters/setters to UIComponent#getStateHelper() instead of to local properties. The setValueExpression() ultimately also end up in the StateHelper (note that it doesn't call the setter at all; just call the getter if you need the data) and the getAttributes() also resolves the values from the StateHelper.

public String getName() {
   return (String) getStateHelper().eval("name");
}

public void setName(String name) {
    getStateHelper().put("name", name);
}

Note that you can safely remove the getId() and setId() methods, because they're already definied in the UIComponentBase superclass which you're extending from.

Thanks for the answer! I would like to ask if I have to implement some special method to distinguish between different types of attributes values inside my component. (I understood that UIComponentBase handles it on its own) And if yes, is there a best practice to do it?!

No and you should generally not care about it either. To get the (evaluated) attribute value, just invoke the getter.

jsf 2 - JSF 2 Custom components having Expression Language for attribu...

jsf jsf-2 attributes custom-component
Rectangle 27 150

Yes, since some genius in the Java API creation committee decided that, even though certain classes have size() members or length attributes, they won't implement getSize() or getLength() which JSF and most other standards require, you can't do what you want.

There's a couple ways to do this.

One: add a function to your Bean that returns the length:

Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function

fn is probably the way to go, unfortunately it is only available in JSTL versions greater then 1.1.

Or, as I said, in Facelets

Using fn:length worked for me with bare JSP (no JSF, Facelets; ultra legacy project being lightly updated before being phased out). The proper taglib to use: <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

For people landing here like me, still 2 year latter, considere you may add the following namespace to your facelet: xmlns:fn="http://java.sun.com/jsp/jstl/functions"

java - How do you get the length of a list in the JSF expression langu...

java jsp jsf jstl el
Rectangle 27 150

Yes, since some genius in the Java API creation committee decided that, even though certain classes have size() members or length attributes, they won't implement getSize() or getLength() which JSF and most other standards require, you can't do what you want.

There's a couple ways to do this.

One: add a function to your Bean that returns the length:

Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function

fn is probably the way to go, unfortunately it is only available in JSTL versions greater then 1.1.

Or, as I said, in Facelets

Using fn:length worked for me with bare JSP (no JSF, Facelets; ultra legacy project being lightly updated before being phased out). The proper taglib to use: <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

For people landing here like me, still 2 year latter, considere you may add the following namespace to your facelet: xmlns:fn="http://java.sun.com/jsp/jstl/functions"

java - How do you get the length of a list in the JSF expression langu...

java jsp jsf jstl el
Rectangle 27 39

You could compare Class#getName() or, maybe better, Class#getSimpleName() to a String.

<h:link rendered="#{model['class'].simpleName eq 'ClassA'}">      
    #{errorMessage1}
</h:link>
<h:link rendered="#{model['class'].simpleName eq 'ClassB'}">      
    #{errorMessage2}
</h:link>

Note the importance of specifying Object#getClass() with brace notation ['class'] because class is a reserved Java literal which would otherwise throw an EL exception in EL 2.2+.

The type safe alternative is to add some public enum Type { A, B } along with public abstract Type getType() to the common base class of the model.

<h:link rendered="#{model.type eq 'A'}">      
    #{errorMessage1}
</h:link>
<h:link rendered="#{model.type eq 'B'}">      
    #{errorMessage2}
</h:link>

wouldnt work for interfaces... any suggestion for that?

@Lucas: it's impossible if the implementation is an interface :) If you've a problem with it, it's caused by something else.

The Class string test suggestion is useful in some situations, but it does not work for interfaces or for subclasses. There is a real and urgent need for instanceof. Please vote here: java.net/jira/browse/JSP_SPEC_PUBLIC-113. See also related problem, how call a composite component bound to a type only for a matching type using some kind of test other than 'rendered', which does not seem to work during build phase (remarks at bottom of stackoverflow.com/questions/16665705/)

What about hierarchical inheritance. I have an Item class which has two sub classes, namely Product and Service. In turn Product class has two subclasses named Medicine and Consumable. So I want to check weather a medicine entity is a Product ? It will return true only if I check it to be a Medicine, but not when checked as a Product.

@jonnieZG: Nope, use the type safe alternative as shown in answer's second part (in other words, works for all types/subclasses).

jsf - instanceof check in EL expression language - Stack Overflow

jsf el instanceof
Rectangle 27 12

You can use Apache Commons Lang 3.x StringEscapeUtils#escapeEcmaScript() method for this in EL.

/WEB-INF/functions.taglib.xml
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
    version="2.0">
    <namespace>http://example.com/functions</namespace>

    <function>
        <name>escapeJS</name>
        <function-class>org.apache.commons.lang3.StringEscapeUtils</function-class>
        <function-signature>java.lang.String escapeEcmaScript(java.lang.String)</function-signature>
    </function>
</taglib>

Then register it in /WEB-INF/web.xml as follows:

<context-param>
    <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/functions.taglib.xml</param-value>
</context-param>

Then you can use it as follows:

<html ... xmlns:func="http://example.com/functions">
...
<script>var foo = '#{func:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{func:escapeJS(bean.foo)}')" />

Alternatively, if you happen to already use the JSF utility library OmniFaces, then you can also just use its builtin of:escapeJS() function:

<html ... xmlns:of="http://omnifaces.org/functions">
...
<script>var foo = '#{of:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{of:escapeJS(bean.foo)}')" />

I've followed the above, but I'm getting the following exception : javax.servlet.ServletException: com.sun.faces.el.impl.ElException: No function is mapped to the name "util:escapeJS" I'm on JSF 1.1, JSP 2.1... any idea what I should look at?

@bendicott: Above answer uses a Facelet taglib. You're using JSP, not Facelets. You need to create a JSP taglib instead.

Had to correct the taglib-definition but your solution is great... simple and effective!

jsf - Escape JavaScript in Expression Language - Stack Overflow

javascript jsf escaping el
Rectangle 27 47

#{MyBean.somelist.size()}

works for me (using JBoss Seam which has the Jboss EL extensions)

Maybe the newer specifications of the EL support the size method? Can anyone confirm or deny this?

@nemo - this is being addressed in a JSR245 maintenance release: blogs.sun.com/kchung/entry/jsr_245_mr_part_i (In terms of JEE specs, that'll be JEE6)

@McDowell, Thanks for the info, I'm really surprised it took them this long to get around to fixing the issue.

Thank you. It worked for me too. +1. But until JEE 6 is widely supported, I'll probably stick with the "more standard" JSTL function.

This work in JSF2, Ok.

java - How do you get the length of a list in the JSF expression langu...

java jsp jsf jstl el
Rectangle 27 47

#{MyBean.somelist.size()}

works for me (using JBoss Seam which has the Jboss EL extensions)

Maybe the newer specifications of the EL support the size method? Can anyone confirm or deny this?

@nemo - this is being addressed in a JSR245 maintenance release: blogs.sun.com/kchung/entry/jsr_245_mr_part_i (In terms of JEE specs, that'll be JEE6)

@McDowell, Thanks for the info, I'm really surprised it took them this long to get around to fixing the issue.

Thank you. It worked for me too. +1. But until JEE 6 is widely supported, I'll probably stick with the "more standard" JSTL function.

This work in JSF2, Ok.

java - How do you get the length of a list in the JSF expression langu...

java jsp jsf jstl el
Rectangle 27 14

To take the boolean property as an example, it's described in chapter 8.3.2 of JavaBeans spec:

In addition, for boolean properties, we allow a getter method to match the pattern:

public boolean is<PropertyName>()

This is<PropertyName> method may be provided instead of a get<PropertyName> method, or it may be provided in addition to a get<PropertyName> method.

In either case, if the is<PropertyName> method is present for a boolean property then we will use the is<PropertyName> method to read the property value.

An example boolean property might be:

public boolean isMarsupial();
    public void setMarsupial(boolean m);

So, #{bean.marsupial} expects exactly the above getter/setter pair.

And in chapter 1.18.5 of EL spec:

  • If A is null or "", return false
Boolean
  • Otherwise, if A is a String, and Boolean.valueOf(A) does not throw an exception, return it

Exactly what I was looking for. Thank you. I had been under the impression that using hasX was valid for a boolean. It is a fairly standard convention but I guess Java(beans) has to draw the line somewhere.

jsp - How does Java expression language resolve boolean attributes? (i...

jsp jsf boolean el
Rectangle 27 5

When the action attribute contains an EL expression, it's interpreted as a method expression. It's thus really only valid when you use action="#{bean.someMethod}". However, your attempt does not represent a valid method expression, it's represents instead a value expression which is not accepted by the action attribute.

If you intend to append additional request/view parameters to the form submit, then you should rather use <f:param>.

<h:commandButton value="Save Edits" action="editOrDeletePage.xhtml">
    <f:param name="editing" value="true" />
    <f:param name="id" value="#{product.id}" />
    <f:param name="name" value="#{product.productName}" />
    <f:param name="description" value="#{product.description}" />
    <f:param name="quantity" value="#{product.quantity}" />
</h:commandButton>

Note that those parameters don't end up in the request URL (as you see in the browser address bar) and that your theoretical approach also wouldn't have done that, a JSF command button namely generates a HTML <input type="submit"> element which submits to the very same URL as specified in the action attribute of the parent HTML <form method="post">.

Also note that those parameters are not evaluated during the form submit, but during displaying the form. If you intented to pass submitted values along that way, then you're basically doing it wrong. Perhaps you want to specify them as view parameters so that you can use action="editOrDeletePage?faces-redirect=trueincludeViewParams=true" as action.

After all, it's hard to propose the right solution for you as you didn't elaborate the concrete functional requirement in detail at all.

Not A Valid Method Expression in JSF - Stack Overflow

jsf
Rectangle 27 14

Note: This solution is better for older versions of JSTL. For versions greater then 1.1 I recommend using fn:length(MyBean.somelist) as suggested by Bill James.

The problem is that we are trying to invoke the list's size method (which is a valid LinkedList method), but it's not a JavaBeans-compliant getter method, so the expression list.size-1 cannot be evaluated.

There are two ways to address this dilemma. First, you can use the RT Core library, like this:

<c_rt:out value='<%= list[list.size()-1] %>'/>

Second, if you want to avoid Java code in your JSP pages, you can implement a simple wrapper class that contains a list and provides access to the list's size property with a JavaBeans-compliant getter method. That bean is listed in Listing 2.25.

The problem with c_rt method is that you need to get the variable from request manually, because it doesn't recognize it otherwise. At this point you are putting in a lot of code for what should be built in functionality. This is a GIANT flaw in the EL.

I ended up using the "wrapper" method, here is the class for it;

public class CollectionWrapper {

    Collection collection;

    public CollectionWrapper(Collection collection) {
        this.collection = collection;
    }

    public Collection getCollection() {
        return collection;
    }

    public int getSize() {
        return collection.size();
    }
}

A third option that no one has mentioned yet is to put your list size into the model (assuming you are using MVC) as a separate attribute. So in your model you would have "someList" and then "someListSize". That may be simplest way to solve this issue.

java - How do you get the length of a list in the JSF expression langu...

java jsp jsf jstl el
Rectangle 27 14

Note: This solution is better for older versions of JSTL. For versions greater then 1.1 I recommend using fn:length(MyBean.somelist) as suggested by Bill James.

The problem is that we are trying to invoke the list's size method (which is a valid LinkedList method), but it's not a JavaBeans-compliant getter method, so the expression list.size-1 cannot be evaluated.

There are two ways to address this dilemma. First, you can use the RT Core library, like this:

<c_rt:out value='<%= list[list.size()-1] %>'/>

Second, if you want to avoid Java code in your JSP pages, you can implement a simple wrapper class that contains a list and provides access to the list's size property with a JavaBeans-compliant getter method. That bean is listed in Listing 2.25.

The problem with c_rt method is that you need to get the variable from request manually, because it doesn't recognize it otherwise. At this point you are putting in a lot of code for what should be built in functionality. This is a GIANT flaw in the EL.

I ended up using the "wrapper" method, here is the class for it;

public class CollectionWrapper {

    Collection collection;

    public CollectionWrapper(Collection collection) {
        this.collection = collection;
    }

    public Collection getCollection() {
        return collection;
    }

    public int getSize() {
        return collection.size();
    }
}

A third option that no one has mentioned yet is to put your list size into the model (assuming you are using MVC) as a separate attribute. So in your model you would have "someList" and then "someListSize". That may be simplest way to solve this issue.

java - How do you get the length of a list in the JSF expression langu...

java jsp jsf jstl el
Rectangle 27 7

EL
public class MyBean {

    public boolean getIsClassA() {
        if(model instanceof ClassA) {
            return true;
        }
        return false;
    }


}

And then do the check by calling the backing bean:

<h:link outcome="#{PageNameA}?faces-redirect=true&amp;" rendered="#{myBean.isClassA}">      
    #{errorMessage}
</h:link>

This is indeed a good answer. I howerver adopted another solution: rendered="#{listRow.rowData.getClass().getName() == 'ClassB'}" (ClassB must be fully quelified). Is there something strong against this "not-so-elegant" solution?

I think this solution is better because it's easier to understand, but that depends somewhat on the intent. If your intent is to display only one link or the other, then put just one link in the view and use a backing bean for the business logic that decides what the outcome should be. This is also more testable. If you want to possibly display both links, then the other solution works OK, but I would still prefer the backing bean for testability and clarity. You have a perfectly good language (java) so there's no need to do crazy things and hard-code class names in EL.

This is a more general solution than the (sometimes still useful) EL-based Class String test suggested by BalusC, since can work for interfaces and subclasses, but it is pain to have to do it all the time, and it often pollutes both the backing beans and/or entities (or wherever one places the test). We need instanceof in JSF2.x a.s.a.p !

This solution works for Hierarchical Inheritance as well.

jsf - instanceof check in EL expression language - Stack Overflow

jsf el instanceof
Rectangle 27 5

Basically what you've stated is all there is to it. EL expects the object to follow regular java bean standards. These 2 should help:

jsp - How does Java expression language resolve boolean attributes? (i...

jsp jsf boolean el
Rectangle 27 33

EL (Expression Language, those #{} things) won't cache the result of the calls or so. It just accesses the data straight in the bean. This does normally not harm if the getter just returns the data.

The setter call is done by @ManagedProperty. It basically does the following:

selector.setProfilePage(request.getParameter("profilePage"));

The getter calls are all done by rendered="#{selector.profilePage == 'some'}" during the render response phase. When it evaluates false the first time, in UIComponent#encodeAll(), then no more calls will be done. When it evaluates true, then it will be re-evaluated six more times in the following sequence:

  • UIComponent#encodeBegin() - Locates renderer for the begin of component.
  • Renderer#encodeBegin() - Renders begin of component.
  • UIComponent#encodeChildren() - Locates renderer for children of component.
  • Renderer#encodeChildren() - Renders children of component.
  • UIComponent#encodeEnd() - Locates renderer for end of component.
  • Renderer#encodeEnd() - Renders end of component.

The component and its renderer verifies during every step if it is allowed to render. During a form submit, if an input or command component or any of its parents has a rendered attribute, then it will also be evaluated during apply request values phase as part of safeguard against tampered/hacked requests.

True, this look like clumsy and inefficient. It was considered the achilles heal of JSF as per spec issue 941. It's been suggested to remove all those repeated checks and stick to the one done in UIComponent#encodeAll(), or to evaluate isRendered() on a per-phase basis. During EG discussion, it became clear the root of the problem is in EL, not in JSF, and that performance could be greatly improved with CDI. So there was no necessity to solve it from JSF spec side on.

If your concern is that the managed property should be checked only once after its setting if it's null or empty, then consider to move it into a method which is annotated with @PostConstruct. Such a method will be called directly after bean's construction and all dependency injection.

@PostConstruct
public void init() {
    if (profilePage == null || profilePage.trim().isEmpty()) {
        profilePage = "main";
    }
}

Yes, but how I have specified, i have only one #{selector.profilePage} in only one page. Thats what I don't understand :)

I haven't observed the behaviour in JSF 2.0 closely, it isn't worth the effort so microoptimize it since it's particularly cheap, but you may want to add a Thread.dumpStack(); to the getter to learn where this call originates and a sysout of FacesContext.getCurrentInstance().getPhaseId() to learn which phase it's sitting in now.

Uhm ok, so is more complicate to understand this :) I think i shouldn't mind about it when programming on jsf (just i wanted to know if i done somethings wrong). But seems to happen to all. So ok, i initialize it after PostConstruct :)

Added an example. If this topic will be closed, or the question is unrelated, i'll open a new one :) Let me know

Nice one man :) So, if i use @ManagedProperty (that such as selector.setProfilePage(request.getParameter("profilePage"));) and i use this value only to get param (not my case) i could remove the public void setProfilePage(String profilePage) { this.profilePage=profilePage; } (i wont do it, its a bean, maybe i'll use this in a future). Now is clear why it calls many times the getter method :) What i don't understand is why my code still doesnt work properly : I must click many time in the button to set profilePage attribute (the ajax call start, but seems that bean doesnt update itself

jsf - Why is the getter called so many times by the rendered attribute...

jsf jsf-2 facelets getter
Rectangle 27 33

EL (Expression Language, those #{} things) won't cache the result of the calls or so. It just accesses the data straight in the bean. This does normally not harm if the getter just returns the data.

The setter call is done by @ManagedProperty. It basically does the following:

selector.setProfilePage(request.getParameter("profilePage"));

The getter calls are all done by rendered="#{selector.profilePage == 'some'}" during the render response phase. When it evaluates false the first time, in UIComponent#encodeAll(), then no more calls will be done. When it evaluates true, then it will be re-evaluated six more times in the following sequence:

  • UIComponent#encodeBegin() - Locates renderer for the begin of component.
  • Renderer#encodeBegin() - Renders begin of component.
  • UIComponent#encodeChildren() - Locates renderer for children of component.
  • Renderer#encodeChildren() - Renders children of component.
  • UIComponent#encodeEnd() - Locates renderer for end of component.
  • Renderer#encodeEnd() - Renders end of component.

The component and its renderer verifies during every step if it is allowed to render. During a form submit, if an input or command component or any of its parents has a rendered attribute, then it will also be evaluated during apply request values phase as part of safeguard against tampered/hacked requests.

True, this look like clumsy and inefficient. It was considered the achilles heal of JSF as per spec issue 941. It's been suggested to remove all those repeated checks and stick to the one done in UIComponent#encodeAll(), or to evaluate isRendered() on a per-phase basis. During EG discussion, it became clear the root of the problem is in EL, not in JSF, and that performance could be greatly improved with CDI. So there was no necessity to solve it from JSF spec side on.

If your concern is that the managed property should be checked only once after its setting if it's null or empty, then consider to move it into a method which is annotated with @PostConstruct. Such a method will be called directly after bean's construction and all dependency injection.

@PostConstruct
public void init() {
    if (profilePage == null || profilePage.trim().isEmpty()) {
        profilePage = "main";
    }
}

Yes, but how I have specified, i have only one #{selector.profilePage} in only one page. Thats what I don't understand :)

I haven't observed the behaviour in JSF 2.0 closely, it isn't worth the effort so microoptimize it since it's particularly cheap, but you may want to add a Thread.dumpStack(); to the getter to learn where this call originates and a sysout of FacesContext.getCurrentInstance().getPhaseId() to learn which phase it's sitting in now.

Uhm ok, so is more complicate to understand this :) I think i shouldn't mind about it when programming on jsf (just i wanted to know if i done somethings wrong). But seems to happen to all. So ok, i initialize it after PostConstruct :)

Added an example. If this topic will be closed, or the question is unrelated, i'll open a new one :) Let me know

Nice one man :) So, if i use @ManagedProperty (that such as selector.setProfilePage(request.getParameter("profilePage"));) and i use this value only to get param (not my case) i could remove the public void setProfilePage(String profilePage) { this.profilePage=profilePage; } (i wont do it, its a bean, maybe i'll use this in a future). Now is clear why it calls many times the getter method :) What i don't understand is why my code still doesnt work properly : I must click many time in the button to set profilePage attribute (the ajax call start, but seems that bean doesnt update itself

jsf - Why is the getter called so many times by the rendered attribute...

jsf jsf-2 facelets getter
Rectangle 27 4

rendered="#{node.getClass().getSimpleName() == 'Logt_anno'}"

jsf - instanceof check in EL expression language - Stack Overflow

jsf el instanceof
Rectangle 27 2

There is an implicit session object available in EL as #{session} But it looks like returned session will under the hood be retrieved as follows:

return extCtx.getSession(true);

So, if you really need to get it from EL with false flag, you can put your code to method of some managed bean and call it.

Or you can call getSession from implicit request object:

#{request.getSession(false)}

primefaces - JSF expression language facecontext session - Stack Overf...

jsf primefaces el
Rectangle 27 6

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<h:outputText value="Table Size = #{fn:length(SystemBean.list)}"/>

On screen it displays the Table size

Table Size = 5

Yes this I find is the simplest way of doing it. I'm using websphere6 with JSP (legacy system). used the same tablib and then use the 'dollar sign' as opposed to 'hash' because hash didn't work. ie: {fn:length(SystemBean.list)}

java - How do you get the length of a list in the JSF expression langu...

java jsp jsf jstl el
Rectangle 27 6

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<h:outputText value="Table Size = #{fn:length(SystemBean.list)}"/>

On screen it displays the Table size

Table Size = 5

Yes this I find is the simplest way of doing it. I'm using websphere6 with JSP (legacy system). used the same tablib and then use the 'dollar sign' as opposed to 'hash' because hash didn't work. ie: {fn:length(SystemBean.list)}

java - How do you get the length of a list in the JSF expression langu...

java jsp jsf jstl el