6

This is a simple question, I should know the answer and I'm ashamed to admit I don't. I am sending a compound object to my JSP page:

public class MyObject {
    private List<MyFoo> myFoo;
    public getMyFoo();
    public setMyFoo();
}

// In the controller...
model.addAttribute("myObject", myObject);

When this goes into the JSP page I can address the model instance of myObject as:

${myObject}

and the list inside as

${myObject.myFoo}

What I want to do is list the size of myFoo on my JSP output, like so:

${myObject.myFoo.size}

But of course size() is not a bean property, so a JSPException is thrown.

Is there a simple, elegant way of doing this in the JSP page or do I need to stick another attribute on the model and put the size in there?

user1071914
  • 3,295
  • 11
  • 50
  • 76

2 Answers2

15

You could use JSTL tag libraries, they are often useful for common JSP operations. Here's a quick reference: https://code.google.com/p/dlcode/downloads/detail?name=jstl-quick-reference.pdf

Include the taglib with this line:

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

Then your case would be:

${fn:length(myObject.myFoo)}
Matteo Di Napoli
  • 567
  • 5
  • 17
1

One plausible (but may not be elegant enough) way is to add a getter function:

public getMyFooSize() { return myFoo.size(); }

And then use the following in JSP:

${myObject.myFooSize}
Tsung-Ting Kuo
  • 1,171
  • 6
  • 16
  • 21
  • 1
    This was what I finally did. May not be perfect, but it did solve the problem. – user1071914 Dec 02 '15 at 15:09
  • @user1071914 But why not use the methods proposed by Matt? It seems to be more elegant. – Tsung-Ting Kuo Dec 02 '15 at 15:50
  • 1
    I already had the change done and checked in, working and tested. If there's time at the end of the project, perhaps I'll go back and update it. – user1071914 Dec 02 '15 at 21:42
  • 1
    It's a ugly kludge for sure but at times this is the only viable option (at least that I've found). The primary use case where I've run into this is when dynamically generating javascript using JSTL. The parser freaks out when you have an open javascript array [ or object { character and won't let you use "fn", – Night Owl Jul 03 '16 at 04:38