04 expression language

32
© 2009 Marty Hall  Lan ua e Originals of Slides and Source Code for Examples: http: //w w w .coreservlets.com /JSF -Tutorial/ Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JP A, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. 2 © 2009 Marty Hall For li ve tr aining on JSF 1.x or 2. 0, please see courses a p: courses.coreserv e s.com . Ta ught by th e author of  Core Servlets and JSP  , More  , . venues, or cust omized version s can be held on-site at your organization. Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JP A, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Courses developed and taught by Marty Hall   Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom courses. Courses developed and taught by coreservlets.com experts (edited by Marty)   Spring, Hibernate/JPA, EJB3, Ruby/Rails Contact [email protected] for details

Upload: hromenique-cezniowscki

Post on 06-Apr-2018

236 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 1/32

© 2009 Marty Hall

 Lan ua e

Originals of Slides and Source Code for Examples:

http://www.coreservlets.com/JSF-Tutorial/

Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.2

© 2009 Marty Hall

For live training on JSF 1.x or 2.0, please seecourses a p: courses.coreserv e s.com .Taught by the author of Core Servlets and JSP , More 

, .venues, or customized versions can be held on-site

at your organization.

Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

• Courses developed and taught by Marty Hall – Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom courses.

• Courses developed and taught by coreservlets.com experts (edited by Marty) – Spring, Hibernate/JPA, EJB3, Ruby/Rails

Contact [email protected] for details

Page 2: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 2/32

Agenda

• Motivating use of the expression language– Comparing to the JSP 2.0 EL

• Accessing bean properties– rect

– Nested

 – Expressions in output values

– Ex ressions in submission values

– Expressions for action controllers

• Accessing collection elements• Using implicit objects and operators

4

Advantages of the Expression

• Shorthand notation for bean properties.– o re erence t e company ame property .e., resu t o

the getCompanyName method) of a scoped variable (i.e.object stored in request, session, or application scope) or

y, y u u#{company.companyName}. To reference the firstName

property of the president property of a scoped variable or,#{company.president.firstName}.

• Simple access to collection elements.– To reference an element of an array, List, or Map, you

use #{variable[indexOrKey]}. Provided that the index orkey is in a form that is legal for Java variable names, thedot notation for beans is interchangeable with the bracketnotation for collections.

5

Page 3: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 3/32

Advantages of the Expression

• Succinct access to request parameters, cookies,.

– To access the standard types of request data, you can use one of 

several predefined implicit objects.• A small but useful set of sim le o erators. 

– To manipulate objects within EL expressions, you can use any of several arithmetic, relational, logical, or empty-testing operators.

• Conditional out ut.– To choose among output options, you do not have to resort to Java

scripting elements. Instead, you can use #{test ? option1 : option2}.

• Automatic type conversion.– The expression language removes the need for most typecasts and

for much of the code that parses strings as numbers.

• Empty values instead of error messages.– In most cases, missing values or NullPointerExceptions result in

empty strings, not thrown exceptions.

6

The JSF EL vs. the JSP 2.0 EL

J SF 1.1 EL J SP 2.0 EL

• an e use on y nattributes of JSF tags

• Requires a taglib

• an e use anyw ere nthe JSP page

• Requires no taglibdeclaration

• Available in servers

su ortin JSP 1.2+

declaration

• Available only in servers

su ortin JSP 2.0+ – E.g., WebLogic 8.1, Tomcat 4,

Oracle 9i, WebSphere 5

• Uses # blah

 – E.g., WebLogic 9, Tomcat 5 & 6,

Oracle 10g, WebSphere 6

• Uses blah

• Can represent submitteddata and output values

 

• Represents output valuesonly

,session, application, andmanaged beans defs

,session, and applicationonly

7

Page 4: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 4/32

Activating the Expression.

• Available only in servers that support JSP 2.0 or. serv e s . or .

– E.g., Tomcat 5 or 6, not Tomcat 4– See htt ://theserverside.com/reviews/matrix.tss

• You must use the JSP 2.0 (servlet 2.4) web.xml file– The web.xml file in the sample JSF apps uses servlets 2.3 (JSP 1.2)

– e samp e apps a coreserv e s.com a rea y use s vers on, or useany web.xml file distributed with Tomcat 5 or 6.

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=" - ". . _ _ .

version="2.4">

</web-app>8

Preventing Use of Standard.

• To enforce EL-only with no scripting, usescripting-invalid in web.xml– Still permits both the JSF EL and the JSP 2.0 EL

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=

"http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"

" ".

<jsp-property-group>

<url-pattern>*.jsp</url-pattern>

<scripting-invalid>true</scripting-invalid>

</jsp-property-group>

</web-app>

9

Page 5: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 5/32

Downsides to Preventing Use of

• Harder debugging– <% System.out.println("...."); %>

• No redirects– < response.sen e rect we come. aces ; >

• Some techniques hard to do with MVC–  

if (outputShouldBeExcel()) {response.setContentType("application/vnd.ms-excel");

%>

•  not mean it is always bad

10

© 2009 Marty Hall

 Pro erties

Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.11

Page 6: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 6/32

Outputting Bean Properties

• #{varName.propertyName}– Means to search the HttpServletRequest, the HttpSession, the

ServletContext (i.e. look for a scoped variable), and managed beansdefinitions, in that order , and output the specified bean property

– ust e use n attr ute o a tag

• Equivalent forms– <h:outputText value="#{customer.firstName}"/>

• Works with all JSF versions. Scoped variable or managed bean.

– ${customer.firstName}• Works only with JSP 2.0 and later. Scoped variable only.

– <%@ page import="coreservlets.NameBean" %><% NameBean person =

(NameBean)pageContext.findAttribute("customer"); %><%= person.getFirstName() %>

• Ugly pre-EL version.

12

Bean Properties Example:

 package coreservlets;

import java.util.*;

 public class TestBean {rivate Date creationTime = new Date

 private String greeting = "Hello";

 public Date getCreationTime() {

}

 public String getGreeting() {

}

 public double getRandomNumber() {re urn a .ran om ;

}}

13

Page 7: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 7/32

Bean Properties Example:- .

<?xml version='1.0' encoding='UTF-8'?>

...

<faces-config>< - >

<managed-bean-name>testBean</managed-bean-name>

<managed-bean-class>

.

</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope>

< mana ed-bean>

...

</faces-config>

14

Bean Properties Example:- . .

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<f:view>

...

<BODY>

<TABLE BORDER=5 ALIGN="CENTER"> 

<TR><TH CLASS="TITLE">Accessing Bean Properties</TH></TR>

</TABLE>

<UL>  

<h:outputText value="#{testBean.creationTime}"/>

<LI>Greeting:

<h:outputText value="#{testBean.greeting}"/>

<LI>Random number:

<h:outputText value="#{testBean.randomNumber}"/>

</UL>

</BODY></HTML>

</f:view>

15

Page 8: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 8/32

Bean Properties Example:

16

© 2009 Marty Hall

 Bean Pro erties

Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.17

Page 9: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 9/32

Nested Bean Properties

• #{varName.prop1.prop2}– First searches scoped variables and managed beans

definitions for an entry named varName–  

• I.e., calls getProp1 method

– Then accesses prop2 property of that result• I.e., calls getProp2 on the output of getProp1

– Can be nested arbitrarily

18

Nested Properties Example:

 package coreservlets;

 pu c c ass NameBean private String firstName = "Missing first name"; private String lastName = "Missing last name";

 

 public NameBean(String firstName, String lastName) {setFirstName(firstName);

}

 public String getFirstName() {return(firstName);

}

 public void setFirstName(String newFirstName) {firstName = newFirstName;

}

...}

19

Page 10: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 10/32

Nested Properties Example:

 package coreservlets;

 pu c c ass CompanyBean private String companyName;

 private String business;

,String business) {

setCompanyName(companyName);setBusiness(business);

 public String getCompanyName() { return(companyName); }

ublic void setCom an Name(Strin newCom an Name) {companyName = newCompanyName;

}

...}

20

Nested Properties Example:

 package coreservlets;

  private NameBean name; private CompanyBean company;

 public EmployeeBean(NameBean name, CompanyBean company) {setName(name);setCompany(company);

}

ublic Em lo eeBean() {this(new NameBean("Marty", "Hall"),

new CompanyBean("coreservlets.com","J2EE Training and Consulting"));

}

 public NameBean getName() { return(name); }

 public void setName( NameBean newName) {name = newName;

...}

21

Page 11: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 11/32

Nested Properties Example:- .

<faces-config>

...

<managed-bean>

<managed-bean-name>employee</managed-bean-name>< - - >

coreservlets.EmployeeBean

</managed-bean-class>

< - - > < - - >

</managed-bean>

...

< faces-confi >

22

Nested Properties Example:- . .

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<f:view>

...

<BODY>

" " 

<TR><TH CLASS="TITLE">Using Nested Bean Properties</TH></TR>

</TABLE>

<UL><LI>Employee's first name:

<h:outputText value="#{employee.name.firstName}"/>

<LI>Employee's last name:

< =" " >. .

<LI>Name of employee's company:

<h:outputText value="#{employee.company.companyName}"/>

<LI>Business area of employee's company:

<h:outputText value="#{employee.company.business}"/>

</UL>

</BODY></HTML>

</f:view>23

Page 12: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 12/32

Nested Properties Example:

24

© 2009 Marty Hall

 Pro erties

Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.25

Page 13: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 13/32

Three Meanings of #{...}

• Designating output value– var ame.property ame means to output t e g ven

property of the given scoped variable or managed bean– <h:outputText value="#{employee.address}"/>• Anytime accessed, means to output text

– <h:inputText value="#{employee.address}"/>• When form initially displayed, means to prepopulate field

• Designating submitted value– <h:inputText value="#{employee.address}"/>

• When form submitted desi nates where value stored 

• Designating method call after submission

– <h:commandButton value="Button Label"" "= .

• When form submitted, designates action handler

26

JSP 2.0 and Struts Equivalents

• Designating output value– <h:outputText value="#{employee.address}"/>

• Similar to ${employee.address}, but scoped vars only

• Similar to <bean:write name="em lo ee" property="address"/> but scoped vars only

– <h:inputText value="#{employee.address}"/>• .

<INPUT TYPE="TEXT"...VALUE="${employee.address}">

• Similar to html:text in Struts

• es gna ng su m e va ue– No JSP 2.0 equivalent

–  

• Designating method call after submission

–27

Page 14: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 14/32

Submitting Properties Example:

 package coreservlets;

 public class EmployeeBean {

 private NameBean name; private CompanyBean company;

...

 public String processEmployee() {if (Math.random() < 0.5) {return("accept");

} else {" "

}}

}

28

Nested Properties Example:- .

<faces-config>

...

<managed-bean>

<managed-bean-name>employee</managed-bean-name>

<managed-bean-class>

coreservlets.EmployeeBean

</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope>

</managed-bean>

...<navigation-rule>

<from-view-id>/submitting-properties.jsp</from-view-id>

<navigation-case>

<from-outcome>accept</from-outcome>

<to-view-id>/WEB-INF/results/accept.jsp</to-view-id>

</navigation-case>

<navigation-case>

<from-outcome>reject</from-outcome>

<to-view-id>/WEB-INF/results/reject.jsp</to-view-id>

</navigation-case>

</navigation-rule>

</faces-config>29

Page 15: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 15/32

Submitting Properties Example:- . .

...

< >

Your first name:

<h:inputText value="#{employee.name.firstName}"/><BR>

Your last name:

<h:inputText value="#{employee.name.lastName}"/>

<BR>

 Name of your company:

<h:inputText value="#{employee.company.companyName}"/>

<BR>

Bus ness area o your company:

<h:inputText value="#{employee.company.business}"/>

<BR>" "

action="#{employee.processEmployee}"/>

</h:form>30

Submitting Properties Example:

31

Page 16: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 16/32

Submitting Properties Example:-.

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<f:view>

...

<BODY>

<TABLE BORDER=5 ALIGN="CENTER"> 

<TR><TH CLASS="TITLE">Employee Accepted</TH></TR>

</TABLE>

<UL>

'

<h:outputText value="#{employee.name.firstName}"/>

<LI>Employee's last name:

<h:outputText value="#{employee.name.lastName}"/>

<LI>Name of employee's company:

<h:outputText value="#{employee.company.companyName}"/>

<LI>Business area of employee's company:

<h:outputText value="#{employee.company.business}"/>

</UL>

Congratulations.

</BODY></HTML>

</f:view>32

Submitting Properties Example:. .

...

<BODY>

<TABLE BORDER=5 ALIGN="CENTER">

<TR><TH CLASS="TITLE">Employee Accepted</TH></TR>

</TABLE>

<LI>Employee's first name:

${employee.name.firstName}

<LI>Employee's last name:${employee.name.lastName}

<LI>Name of employee's company:

${employee.company.companyName}

< > ' 

${employee.company.business}

</UL>

Congratulations.

</BODY></HTML>

33

Page 17: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 17/32

Submitting Properties Example:-.

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<f:view>

...

<BODY>

<TABLE BORDER=5 ALIGN="CENTER"> 

<TR><TH CLASS="TITLE">Employee Rejected</TH></TR>

</TABLE>

<UL>

'

<h:outputText value="#{employee.name.firstName}"/>

<LI>Employee's last name:

<h:outputText value="#{employee.name.lastName}"/>

<LI>Name of employee's company:

<h:outputText value="#{employee.company.companyName}"/>

<LI>Business area of employee's company:

<h:outputText value="#{employee.company.business}"/>

</UL>

Congratulations.

</BODY></HTML>

</f:view>34

Submitting Properties Example:. .

...

<BODY>

<TABLE BORDER=5 ALIGN="CENTER">

<TR><TH CLASS="TITLE">Employee Rejected</TH></TR>

</TABLE>

<LI>Employee's first name:

${employee.name.firstName}

<LI>Employee's last name:${employee.name.lastName}

<LI>Name of employee's company:

${employee.company.companyName}

< > ' 

${employee.company.business}

</UL>

Congratulations.

</BODY></HTML>

35

Page 18: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 18/32

Submitting Properties Example:

36

Submitting Properties Example:

37

Page 19: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 19/32

© 2009 Marty Hall

Accessing Collections

Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.38

Equivalence of Dot and Array

• Equivalent forms– #{name.property}

– #{name["property"]}

•  – To access arrays, lists, and other collections

• See u comin slides – To calculate the property name at request time.

• #{name1[name2]} (no quotes around name2)

– o use names t at are ega as ava var a e names• #{foo["bar-baz"]}

• #{foo["bar.baz"]}

39

Page 20: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 20/32

Accessing Collections

• #{attributeName[entryName]}

• Works for– Array. Equivalent to

• e rray n ex ge ng an se ng

– List. Equivalent to• theList.get(index) or theList.set(index, submitted-val )

– Map. Equivalent to• theMap.get(key) or theMap.put(key, submitted-val )

•  – #{stateCapitals["maryland"]}

– .

– But the following is illegal since 2 is not a legal var name• #{listVar.2}

40

Collections Example:

 public class PurchaseBean { private String[] cheapItems =

" " " - " " ", , private List<String> mediumItems =

new ArrayList<String>(); private Map<String,String> valuableItems =

new HashMap<String,String>();= 

 public PurchaseBean() { mediumItems.add("iPod");

 mediumItems.add("GameBoy");" ".valuableItems.put("low", "Lamborghini");valuableItems.put("medium", "Yacht");valuableItems.put("high", "Chalet");

}

 public String[] getCheapItems() {return(cheapItems);

} public List<String> getMediumItems() {

} public Map<String,String> getValuableItems() {

return(valuableItems);}

41

Page 21: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 21/32

Collections Example:

 public String purchaseItems() {

isEverythingOK = Utils.doBusinessLogic(this);

isEverythingOK = Utils.doDataAccessLogic(this);

if (isEverythingOK) {

return("success");

} else {

return("failure");

}

}

42

Collections Example: Utils public class Utils {

ublic static boolean doBusinessLo ic 

(PurchaseBean bean) {

// Business logic omitted

return(Math.random() > 0.1);

}

 public static boolean doDataAccessLogic

 

// Database access omitted

return(Math.random() > 0.1);

}

}

43

Page 22: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 22/32

Collections Example:- .

<faces-config>

...

<managed-bean>

<managed-bean-name>purchases</managed-bean-name>

<managed-bean-class>coreservlets.PurchaseBean

</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope>

</managed-bean>

...

<navigation-rule>

<from-view-id>/using-collections.jsp</from-view-id>

<navigation-case>

<from-outcome>success</from-outcome>

<to-view-id>/WEB-INF/results/success.jsp</to-view-id>

</navigation-case>

<navigation-case><from-outcome>failure</from-outcome>

<to-view-id>/WEB-INF/results/failure.jsp</to-view-id>

</navigation-case>

</navigation-rule>

</faces-config>44

Collections Example:- . .

...

<h:form>

<UL>

<LI><B>Cheap Items</B>

<OL>

<LI><h:in utText

value="#{purchases.cheapItems[0]}"/>

<LI><h:inputText

value="#{purchases.cheapItems[1]}"/>

 

value="#{purchases.cheapItems[2]}"/>

</OL>

<LI><B>Medium Items</B>

<LI><h:inputText

value="#{purchases.mediumItems[0]}"/>

<LI><h:inputText

value="#{purchases.mediumItems[1]}"/>

<LI><h:inputText

value="#{purchases.mediumItems[2]}"/>

</OL>45

Page 23: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 23/32

Collections Example:. . .

<LI><B>Valuable Items</B>

<UL>

<LI>Low:

<h:inputText

value='#{purchases.valuableItems["low"]}'/>

<LI>Medium:

<h:inputText

value='#{purchases.valuableItems["medium"]}'/>

<LI>High:

 

value='#{purchases.valuableItems["high"]}'/>

</UL>

</UL>

:comman u on va ue= urc ase

action="#{purchases.purchaseItems}"/>

</h:form>

...

• Important note– Since I am using double quotes around the hash table key,

I have to use single quotes around the entire JSF expression46

Collections Example:

47

Page 24: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 24/32

Submitting Properties Example:-.

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>< :v ew>...<UL>

<LI><B>Cheap Items</B><OL><LI><h:out utText

value="#{purchases.cheapItems[0]}"/><LI><h:outputText

value="#{purchases.cheapItems[1]}"/><LI><h:outputText

value="#{purchases.cheapItems[2]}" ></OL><LI><B>Medium Items</B><OL>< ><

value="#{purchases.mediumItems[0]}"/><LI><h:outputText

value="#{purchases.mediumItems[1]}"/><LI><h:outputTextvalue="#{purchases.mediumItems[2]}"/>

</OL>...</f:view>

48

Submitting Properties Example:. .

...

<UL>

<LI><B>Cheap Items</B>

<OL>

<LI>${purchases.cheapItems[0]}

.

<LI>${purchases.cheapItems[2]}

</OL>

<LI><B>Medium Items</B><OL>

<LI>${purchases.mediumItems[0]}

<LI>${purchases.mediumItems[1]}

< > .

</OL>

...

49

Page 25: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 25/32

Submitting Properties Example:

50

© 2009 Marty Hall

 O erators

Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.51

Page 26: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 26/32

JSF EL Has Almost the Same

• facesContext. The FacesContext object.– . . . . .

• param and paramValues. Request params.– E.g. #{param.custID}

. .– E.g. #{header.Accept} or #{header["Accept"]}– #{header["Accept-Encoding"]}

• . .– E.g. #{cookie.userCookie.value} or

#{cookie["userCookie"].value}

. .• requestScope, sessionScope, applicationScope.

– Instead of searching scopes.•

– Using implicit objects usually works poorly with MVC model

52

Example: Implicit Objects<!DOCTYPE …>

<P>

<UL>

<LI><B>test Request Parameter:< B>${param.test}

<LI><B>User-Agent Header:</B>{header["User-Agent"]}

<LI><B>JSESSIONID Cookie Value:</B>

${cookie.JSESSIONID.value}

<LI><B>Server:</B>

${pageContext.servletContext.serverInfo}

</UL>

</BODY></HTML>

53

Page 27: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 27/32

Example: Implicit Objects

54

Expression Language Operators

• Arithmetic– + - * / div % mod

• Relational– == eq = ne < t > gt <= e >= ge

• Logical–  

• Empty–

– True for null, empty string, empty array, empty list,empty map. False otherwise.

• CAUTION– Use extremely sparingly to preserve MVC model

55

Page 28: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 28/32

Example: Operators

<TABLE BORDER=1 ALIGN="CENTER"> 

<TR><TH CLASS="COLORED" COLSPAN=2>Arithmetic Operators

<TH CLASS="COLORED" COLSPAN=2>Relational Operators<TR><TH>Expression<TH>Result<TH>Expression<TH>Result

<TR ALIGN="CENTER">

<TD>\${3+2-1}<TD>${3+2-1}

<TD>\${1&lt;2}<TD>${1<2}

" "

<TD>\${"1"+2}<TD>${"1"+2}

<TD>\${"a"&lt;"b"}<TD>${"a"<"b"}

<TR ALIGN="CENTER">

<TD>\${1 + 2*3 + 3/4}<TD>${1 + 2*3 + 3/4}

<TD>\${2/3 &gt;= 3/2}<TD>${2/3 >= 3/2}

<TR ALIGN="CENTER"><TD> <TD>

<TD>\${3/4 == 0.75}<TD>${3/4 == 0.75}

…56

Example: Operators (Result)

57

Page 29: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 29/32

Evaluating Expressions

• ${ test ? expression1 : expression2 }– Evaluates test and outputs either expression1 or

expression2

– Relatively weak • c:if and c:choose from JSTL are much better

– Tempts you to put business/processing logic in JSP page.

– Should only be used for presentation logic.• ven en, cons er a erna ves

58

Example: Conditional

 public class Conditionals extends HttpServlet {

,

HttpServletResponse response)

throws ServletException, IOException {

a es ean app es =

new SalesBean(150.25, -75.25, 22.25, -33.57);

SalesBean oranges =

new a es ean - . , - . , . , . ;

request.setAttribute("apples", apples);

request.setAttribute("oranges", oranges);

RequestDispatcher dispatcher =

request.getRequestDispatcher

("/el/conditionals.jsp");

dispatcher.forward(request, response);

}

}59

Page 30: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 30/32

Example: Conditional

 public class SalesBean {rivate double 1 2 3 4

 public SalesBean(double q1Sales,double q2Sales,double q3Sales,double q4Sales) {

q1 = q1Sales; q2 = q2Sales;= = 

}

 public double getQ1() { return(q1); } public double getQ2() { return(q2); } public double getQ3() { return(q3); }

 public double getQ4() { return(q4); }  pu c ou e ge o a

return(q1 + q2 + q3 + q4); }}

60

Example: Conditional

<TABLE BORDER=1 ALIGN="CENTER">

<TR><TH>

<TH CLASS="COLORED">Apples

<TH CLASS="COLORED">Oranges

" "

<TD ALIGN="RIGHT">${apples.q1}

<TD ALIGN="RIGHT">${oranges.q1}

<TR><TH CLASS="COLORED">Second Quarter<TD ALIGN="RIGHT">${apples.q2}

<TD ALIGN="RIGHT">${oranges.q2}

< >< =" ">

<TD ALIGN="RIGHT"

BGCOLOR="${(apples.total < 0) ? "RED" : "WHITE" }">

${apples.total}

<TD ALIGN="RIGHT"

BGCOLOR="${(oranges.total < 0) ? "RED" : "WHITE" }">

${oranges.total}

</TABLE>…61

Page 31: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 31/32

Example: Conditional

62

Summary

• The JSF EL rovides concise eas -to-read access to– Bean properties

– Collection elements

• Plays Triple Role– utput va ues

– Submitted values

–  

• JSF EL for input values similar to JSP 2 EL– Exce t JSF EL accesses mana ed beans even if the are

not yet scoped variables

– Submitted values and action handlers: no JSP 2.0 equiv63

Page 32: 04 Expression Language

8/3/2019 04 Expression Language

http://slidepdf.com/reader/full/04-expression-language 32/32

© 2009 Marty Hall

Questions?

Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.64