Learn Java for Web Development

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

Listing 3-21. Code Fragment for Setting a Map and an Array as Attributes 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);
6.
7.String[ ] categories = {"Groovy", "Java", "Scala"};
8.request.setAttribute("category", categories);


Listing 3-22. Nested EL Expression


Book : ${ books[category[1]] }


Here’s the output:


Book : Beginning Java


Now that you have learned how far you can go with the. and [ ] operators, it is time to see why EL
is so important. You will now see why it is so important by completing the application you started to
create, specifically, by writing the JSP page. Listing 3-23 illustrates book.jsp. This JSP page uses
scripting elements (scriptlets and expressions) and EL. The idea is to compare the two, i.e. scripting
elements and EL. This comparison is illustrated in Figure 3-7.


Listing 3-23. book.jsp


1.<%@page import="com.apress.chapter03.model.Book"%>
2.<%@page import="com.apress.chapter03.model.Author"%>
3.<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
4.<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
5.
6.
7.
8.
9.


10.
11.
12.
13.
14.
15.<%
16.Book book = (Book) request.getAttribute("bookAttrib");
17.Author author = book.getAuthor();
18.%>
19.
20.
22.
23.
24.
25.

Descriptioncodeoutput
Author's Name using Scriptlet and Expression
21.
${fn:escapeXml("<%= author.getName() %>")}<%=author.getName()%>