A String index is coerced to an int for arrays and Lists
The EL for accessing an array is the same as the EL for accessing a List.
Remember folks, this is NOT Java. In EL, the [ ] operator is NOT the array access operator. No, it’s just called the [ ] operator. (We swear, look it up in the spec—it has no name! Just the symbol [ ]. Like Prince, kind of.) If it DID have a name, it would be the array/List/Map/bean Property access operator.
In a Servlet
java.util.ArrayList favoriteFood = new java.util.ArrayList(); favoriteFood.add("chai ice cream"); favoriteFood.add("fajitas"); favoriteFood.add("thai pizza"); favoriteFood.add("anything in dark chocolate"); request.setAttribute("favoriteFood", favoriteFood);
In a JSP
If the thing to the left of the bracket is an array or a List, and the index is a String literal, the index is coerced to an int.
This would NOT work:
${favoriteFood["one"]}
Because “one” can’t be turned into an int. You’ll get an error if the index can’t be coerced.
Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.