How to get an item from the String[] attribute in JSTL/JSP tag
Asked Answered
U

1

6

In plain JSP I can get first item by EL ${form.items[0]}, but in a JSP tag the same expression throws the following exception:

javax.el.PropertyNotFoundException: Could not find property 0 in class java.lang.String

The value of ${form.items} is [Ljava.lang.String;@315e5b60.

JSP tag code is:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ attribute name="items" required="true" %>
${items[0]}

JSP code is:

<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%>
<t:input items="${form.items}"></t:input>

Maybe I forgot type of the attribute or something else? Why is the way to access values different in JSP and JSP tag?

Unheard answered 16/8, 2011 at 12:34 Comment(0)
H
15

You need to specify the expeded type of the custom tag attribute. By default, it's java.lang.String, and the JSP container coerces the attribute to a string before passing it to your tag. It thus calls toString on your String array.

<%@ attribute name="items" required="true" type="java.lang.String[]" %>

or

<%@ attribute name="items" required="true" type="[Ljava.lang.String" %>

should do the trick. If neither does, using

<%@ attribute name="items" required="true" type="java.lang.Object" %>

should, but it's less clear.

Henrion answered 16/8, 2011 at 13:14 Comment(2)
Thanks, first solution works (type="java.lang.String[]"). Second - doesn't work, I tried it before.Unheard
Using java.lang.Object allows the tag to get both arrays and java.util.List. That may be useful in some cases too.Albite

© 2022 - 2024 — McMap. All rights reserved.