JSPTips

How to find size of Collection in OGNL – JSTL workaround

1 Mins read

We are using OGNL(Object-Graph Navigation Language) syntax in our web application, which is built on Spring MVC framework. Our view pages are created in JSP using JSTL and OGNL syntax. We have a page where we wanted to check the size of a collection and if its empty we wanted to display certain message on the page.

We searched on web for various options but didn’t find many useful solutions except for one option mentioned below.

First option we tried is directly checking for the size attribute using ${myCollection.size}, but this doesn’t work as Java Collections don’t follow Java bean method naming conventions and there is no getSize() method available in it. So this option is ruled out.

Second option we tried is calling the method itself by using this syntax ${myCollection.size()}, but looks like JSTL doesn’t like it. JSTL is expecting it to be a function. So this option is also ruled out.

Final option we tried is JSTL function library, which worked for me and the syntax is simple

${fn:length(myCollection)}

For this to work you also need to include the JSTL functions namespace in your JSP page. It can be done using below syntax.

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

This syntax can be easily used in any JSTL conditional construct. For example below condition can be used to check if collection has some data.

<c:when test="${fn:length(myCollection)>0}">

I am sure many people would already know this, but finding such a non-standard syntax is difficult for Java developers, so its worth sharing with fellow developer in same Java world. Let me know if you have idea about a better way of doing the same thing.

Related posts
KubernetesTips

3 Tips to Troubleshoot Readiness Probe Failed Errors Effectively : Kubernetes

4 Mins read
A Kubernetes readiness probe can improve your service’s quality and reduce operational issues, making your service more resilient and robust. However, the…
GadgetsSoftwareTechnologyTips

Is It good to Wear Eyeglasses for Software Engineers?

2 Mins read
As technology continues to be a fundamental tool in our day-to-day lives, we spend more time staring at digital screens. This may…
Tips

The 3 Things It Takes To Become A Digital Nomad

3 Mins read
There is so little reason to sit in a cubicle in an office that takes hours out of your day commuting to…
Power your team with InHype

Add some text to explain benefits of subscripton on your services.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *