EL - the [] and . operators

Using Expression Language, we can access components of a JavaBean, array, list, map, both with the square brackets "[]" operator or the dot "." operator.

Let's slightly modify the servlet we defined in the previous post, putting an array of Strings in a request attribute:
String[] favoriteMusic = {"Subsonica", "Tocotronic", "Bilk", "Baustelle"};
request.setAttribute("musicList", favoriteMusic);
In the JSP page we can access the elements of the array using the [] operator.
<h2>Using EL: [] for array</h2>
<br />First song is by: ${musicList[0]}
<br />Second song is by: ${musicList["1"]}
It is worth spending a few words on the second line: the string "1" is converted to integer, and then the number is used as index to retrieve the second element of the array.

Now we create a list in our servlet:
java.util.ArrayList<String> favoriteFood = new java.util.ArrayList<String>();
favoriteFood.add("hazelnut icecream");
favoriteFood.add("fajitas");
favoriteFood.add("veggie pizza");
favoriteFood.add("anything in dark chocolate");
request.setAttribute("favoriteFood", favoriteFood);
And we access it in the JSP in the same way. Moreover, we can also use the list as a valid object for EL, since a list has a good override to the toString() method:
<h2>Using EL: [] for list</h2>
Foods are: ${favoriteFood}
<br />
<br />First food is ${favoriteFood[0]}
<br />Second food is ${favoriteFood["1"]}
For JavaBeans and maps make sense using both notation. We define a map in the servlet:
java.util.Map<String, String> musicMap = new java.util.HashMap<String, String>();
musicMap.put("Ambient", "Zero 7");
musicMap.put("Surf", "Tahiti 80");
musicMap.put("DJ", "BT");
musicMap.put("Indie", "Bilk");
request.setAttribute("musicMap", musicMap);
And we use it in the JSP page:
<h2>Using EL: [] or . for JavaBeans and Maps</h2>
Music map is: ${musicMap}
<br />
<br />Ambient is by: ${musicMap.Ambient}
<br />Yes, ambient is by ${musicMap["Ambient"]}
We should be careful and not mix incorrectly the two notations: ${musicMap[Ambient]} won't work as expected, since Ambient is not an object available to the code in the JSP page.

If we defined in the servlet this array:
String[] musicTypes = {"Ambient", "Surf", "DJ", "Indie"};
request.setAttribute("MusicType", musicTypes);
We could use nested expressions in the JSP page, like this:
<h2>Using EL: nested expression</h2>
${MusicType[0]} music is by ${musicMap[MusicType[0]]}
MusicType[0] is evaluated to "Ambient", so it could be used as an acceptable key for the musicMap.

For more information on the subject, I suggest you to read the eighth chapter of Head First Servlet and JSP.

No comments:

Post a Comment