Hello, In jweb+ mock exams, there is one question on EL which is like
Consider the following code appearing in a JSP file:
<% request.setAttribute("names", new String[]{ "A", "B", "C" } ); request.setAttribute("index", "1"); %> <h1><!-- insert code here --></h1> Which of the following statements will print B in inserted in the above JSP page? Select 3 correct options
The answer listed are: b ${names[1]} c ${names.index} d ${names[index]}
By the way the other options listed for this question are: a ${names.1} e ${names.$index} f ${names[$index]}
Reading HFSJ, I thought ${name.index}, can be used only when the first attribute is a Map or a Bean and the second one after the . is a key in a Map or a property in a Bean. Further, I remember reading that for Array Lists, List etc the [] operator needs to be used.
You are correct. I tried some coding and proved c is wrong. Here is the error message I got:
The "." operator was supplied with an index value of type "java.lang.String" to be applied to a List or array, but that value cannot be converted to an integer.
In ${names["index"]} "index" is a string literal so it will not work However ${names[index]} ie without quotes will work since we have set the index var in the request
ie ${names[index]} --> ${names["1"]} -------> first
And yeah , i didnt explain properly in my previous post ${names["1"]} is valid in case of EL though not in java
You have tried the wrong expression . If you look at my previous post the expression i had suggested is ${names[index]} whereas the expression you tried is ${names[${index}]}
This is because when nesting expressions you need to use only one $ sign If 2 or more present then the error you got is thrown
Morover even with the first expression i dont think it will work since you are setting the var in the request scope and trying to access it in the same page (which is not in request scope )
try putting it in the page scope with the first expression i suggested
Thanks, Shiva. ${names[index]} works. And I don't have to put it in page scope since the EL automatically checks request scope when it's not in page scope.
Eat that pie! EAT IT! Now read this tiny ad. READ IT!