Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 772
timofey.tatarinov Avatar asked Aug 16 '11 12:08

timofey.tatarinov


People also ask

Which Taglib attribute is used for JSTL in JSP?

Install JSTL Library To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses the library.

Which tag is used in JSTL to show the output?

The <c:out> tag is similar to JSP expression tag, but it can only be used with expression. It will display the result of an expression, similar to the way < %=... % > work.

Which JSTL provides support for string manipulation in JSTL?

The JSTL core tag provide variable support, URL management, flow control, etc. The URL for the core tag is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c. The functions tags provide support for string manipulation and string length.

What is difference between JSTL and JSP?

JSP lets you even define your own tags (you must write the code that actually implement the logic of those tags in Java). JSTL is just a standard tag library provided by Sun (well, now Oracle) to carry out common tasks (such as looping, formatting, etc.).


1 Answers

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.

like image 169
JB Nizet Avatar answered Sep 18 '22 06:09

JB Nizet