How to get element from String [] attribute in JSTL / JSP tag

In a simple JSP, I can get the first EL element ${form.items[0]} , but in the JSP tag the same expression raises 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:

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

JSP Code:

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

Maybe I forgot the attribute type or something else? Why is there a way to access values ​​other than JSP and JSP tags?

+6
source share
1 answer

You need to specify the accelerated attribute type of the user tag. By default, it is java.lang.String , and the JSP container forcibly binds the attribute to the string before passing it to your tag. So it calls toString in your String array.

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

or

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

gotta do the trick. If not, using

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

should, but it's less clear.

+13
source

Source: https://habr.com/ru/post/895140/


All Articles