Learn Java for Web Development

(Tina Meador) #1
CHAPTER 3: Best Practices in Java EE Web Development 119

Listing 3-14. Using the [ ] Operator with a List or an Array


someArray["1"]
someArray[1]
someList["2"]
someList[2]


For example, the array in Listing 3-15 can be accessed as illustrated in Listing 3-16.


Listing 3-15. Setting an Array as an Attribute in the Servlet Code



  1. String [ ] books = {"Clojure", "Groovy ", "Java" , "Scala"} ;

  2. request.setAttribute("books", books);


Listing 3-16. Using the [ ] Operator


Book: ${books[0]}


The output displayed for Listing 3-16 is as follows:


Book: Clojure


Note Lists can be accessed in the same manner as arrays.

If there is a String literal inside the brackets of the [ ] operator, the variable to which the [ ] operator
is applied is either a JavaBean or a Map. Listing 3-17 illustrates the code for setting a Map as an
attribute in the Servlet.


Listing 3-17. Code Fragment for Setting a Map as an Attribute in the Servlet Code


1.Map<String, String> bookMap = new HashMap<>();
2.bookMap.put("Groovy", "Beginning Groovy");
3.bookMap.put("Java", " Beginning Java");
4.bookMap.put("Scala", " Beginning Scala");
5.request.setAttribute("books", bookMap);


In Listing 3-18, EL searches for the attribute bound to the name books in the scope. In Listing 3-17,
books is a Map set in the request attribute. Therefore, EL searches for the key Groovy passed in the
[ ] operator of Listing 3-18 and evaluates it.


Listing 3-18. Using the [ ] Operator


Book : ${books["Groovy"] }


The output displayed for Listing 3-8 is as shown here:


Book: Beginning Groovy

Free download pdf