14

I'm working on a JSP where I need to call methods on object that come from a Bean. The previous version of the page does not use JSTL and it works properly. My new version has a set up like this:

<jsp:useBean id="pageBean" scope="request" type="com.epicentric.page.website.PageBean" />
<c:set var="pageDividers" value="<%= pageBean.getPageDividers() %>" />
<c:set var="numColumns" value="${pageDividers.size()}" />

The variable pageDividers is a List object.

I'm encountering this issue: when I ask for pageDivider's size, an exception is thrown. I know this is a simple JTSL error -- what am I doing wrong?

The error message is:

The function size must be used with a prefix when a default namespace is not specified

How do I correctly access or call the methods of my pageDividers object?

Zack The Human
  • 8,373
  • 7
  • 39
  • 60

2 Answers2

27

When using the dot operator for property access in JSTL, ${pageDividers.size} (no () needed) results in a call to a method named getSize().
Since java.util.List offers a method called size() (rather than getSize()) you won't be able to access the list length by using that code.


In order to access to a list size, JSTL offers the fn:length function, used like

${fn:length(pageDividers)}

Note that in order to use the fn namespace, you should declare it as follows

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

In addition, the same function can be used with any collection type, and with Strings too.

abahgat
  • 13,360
  • 9
  • 35
  • 42
  • 1
    Be wary. I ran into an obscure bug in Websphere 6.12- that occurred when a JSTL function was executed in a tag body. This is fixed in Websphere 6.13+, but not lower than 6.13. As we use 6.11, we actually had to go and create custom tags for the functions we used, delegating to the actual code. – MetroidFan2002 Oct 23 '08 at 01:21
  • 5
    This sucks big cahones. Why the hell wont they let you invoke a method using the class/instance itself!? You run into all kinds of wormholes on the JEE platform... ffs! – mjs Apr 10 '12 at 08:07
2

To access the property of a bean using EL you simply name the property (not invoke the method). So lets say you have a method called getSize() in the bean then

${pageDividers.size}

Notice no ().

EDIT:Sorry...made an error in the original post.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192