Learn Java for Web Development

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

Listing 3-26 illustrates accessing a header named user-agent, using the expression
${header.user-agent} or ${header["user-agent"]}.


Listing 3-26. Using EL Implicit Object Header


${header["user-agent"]}


Here’s the output:


Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0


Accessing Cookie


The El implicit object cookie gives us access to the cookie. Listing 3-27 illustrates the cookie stored
in the servlet.


Listing 3-27. Setting a Cookie in a Servlet


1.String userName = "vishal";
2.Cookie c = new Cookie("userName", userName);
3.c.setPath("/");
4.response.addCookie(c);


Listing 3-28 illustrates how to use an EL implicit object to access the cookie in the JSP page.


Listing 3-28. Using an EL Implicit Object Cookie


${cookie.userName.value}


Accessing a Scoped Attribute


The El implicit object sessionScope gives access to the attribute stored in the session scope.
Listing 3-29 illustrates the attribute stored in the session in a servlet.


Listing 3-29. Setting a Session Attribute in a Servlet


HttpSession session = request.getSession();
Book book = new Book();
book.setBookTitle("Beginning Java");
session.setAttribute("book", book);


Listing 3-30 illustrates using an EL implicit object called sessionScope to access the book title in the
JSP page.


Listing 3-30. Using EL Implicit Object sessionScope


Book title in Session Scope ${sessionScope.book.bookTitle}

Free download pdf