The JSF Expression Language

September 21, 2017 | Author: Daisy Kelley Campbell | Category: N/A
Share Embed Donate


Short Description

1 2012 Marty Hall The JSF Expression Language Originals of Slides and Source Code for Examples: This somewhat old tutor...

Description

© 2012 Marty Hall

The JSF Expression Language Originals of Slides and Source Code for Examples: http://www.coreservlets.com/JSF-Tutorial/

This somewhat old tutorial covers JSF 1, and is left online for those maintaining existing projects. All new projects should use JSF 2, which is both simpler and more powerful. See http://www.coreservlets.com/JSF-Tutorial/jsf2/.

Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. 2

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

© 2012 Marty Hall

For live training on JSF 1 or 2, please see courses at http://courses.coreservlets.com/. Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. • Courses developed and taught by Marty Hall – JSF 2, PrimeFaces, servlets/JSP, Ajax, jQuery, Android development, Java 6 or 7 programming, custom mix of topics – Ajax courses can concentrate on 1EE library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, etc.) or survey several Customized Java Training: http://courses.coreservlets.com/

• Courses developed and taught by coreservlets.com experts (edited by Marty)

Java, JSF– 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Spring, Hibernate/JPA, EJB3, GWT, Hadoop, SOAP-based and RESTful Web Services Contact [email protected] for details Developed and taught by well-known author and developer. At public venues or onsite at your location.

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

• Accessing bean properties – Direct – Nested

• Submitting bean properties – Expressions in output values – Expressions in submission values – Expressions for action controllers

• Accessing collection elements • Using implicit objects and operators 4

Advantages of the Expression Language (Important) • Shorthand notation for bean properties. – To reference the companyName property (i.e., result of the getCompanyName method) of a scoped variable (i.e. object stored in request, session, or application scope) or managed bean named company, you use #{company.companyName}. To reference the firstName property of the president property of a scoped variable or managed bean named company, you use #{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 or key is in a form that is legal for Java variable names, the dot notation for beans is interchangeable with the bracket notation for collections. 5

Advantages of the Expression Language (Less Important) • Succinct access to request parameters, cookies, and other request data. – To access the standard types of request data, you can use one of several predefined implicit objects.

• A small but useful set of simple operators.

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

• Conditional output.

– 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 • • •

JSF 1.1 EL

JSP 2.0 EL

Can be used only in attributes of JSF tags Requires a taglib declaration Available in servers supporting JSP 1.2+

• Can be used anywhere in the JSP page • Requires no taglib declaration • Available only in servers supporting JSP 2.0+



• • • 7

E.g., WebLogic 8.1, Tomcat 4, Oracle 9i, WebSphere 5

– E.g., WebLogic 9, Tomcat 5 & 6, Oracle 10g, WebSphere 6

Uses #{blah} • Uses ${blah} Can represent submitted • Represents output values data and output values only Looks in request, • Looks in request, session, application, and session, and application managed beans defs only

Activating the Expression Language in JSP 2.0 • Available only in servers that support JSP 2.0 or 2.1 (servlets 2.4 or 2.5) – E.g., Tomcat 5 or 6, not Tomcat 4 – See http://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) – The sample apps at coreservlets.com already use this version, or use any web.xml file distributed with Tomcat 5 or 6.

8



Preventing Use of Standard Scripting Elements in JSP 2. • To enforce EL-only with no scripting, use scripting-invalid in web.xml – Still permits both the JSF EL and the JSP 2.0 EL *.jsp true 9

Downsides to Preventing Use of Scripting Elements • Harder debugging –

• No redirects –

• Some techniques hard to do with MVC –

• Just because scripting is usually bad does not mean it is always bad 10

© 2012 Marty Hall

Outputting Bean Properties Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. 11

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

Outputting Bean Properties • #{varName.propertyName} – Means to search the HttpServletRequest, the HttpSession, the ServletContext (i.e. look for a scoped variable), and managed beans definitions, in that order, and output the specified bean property – Must be used in attribute of a JSF tag

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

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

– • Ugly pre-EL version. 12

Bean Properties Example: TestBean package coreservlets; import java.util.*; public class TestBean { private Date creationTime = new Date(); private String greeting = "Hello"; public Date getCreationTime() { return(creationTime); } public String getGreeting() { return(greeting); }

} 13

public double getRandomNumber() { return(Math.random()); }

Bean Properties Example: faces-config.xml testBean coreservlets.TestBean request ...

14

Bean Properties Example: bean-properties.jsp (.faces) ... Accessing Bean Properties Creation time: Greeting: Random number: 15

Bean Properties Example: Result

16

© 2012 Marty Hall

Accessing Nested Bean Properties Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. 17

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

Nested Bean Properties • #{varName.prop1.prop2} – First searches scoped variables and managed beans definitions for an entry named varName – Then accesses prop1 property • 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: NameBean package coreservlets; public class NameBean { private String firstName = "Missing first name"; private String lastName = "Missing last name"; public NameBean() {} public NameBean(String firstName, String lastName) { setFirstName(firstName); setLastName(lastName); } public String getFirstName() { return(firstName); } public void setFirstName(String newFirstName) { firstName = newFirstName; } 19

}

...

Nested Properties Example: CompanyBean package coreservlets; public class CompanyBean { private String companyName; private String business; public CompanyBean(String companyName, String business) { setCompanyName(companyName); setBusiness(business); } public String getCompanyName() { return(companyName); } public void setCompanyName(String newCompanyName) { companyName = newCompanyName; } }

...

20

Nested Properties Example: EmployeeBean package coreservlets; public class EmployeeBean { private NameBean name; private CompanyBean company; public EmployeeBean(NameBean name, CompanyBean company) { setName(name); setCompany(company); } public EmployeeBean() { 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

...

Nested Properties Example: faces-config.xml ... employee coreservlets.EmployeeBean request ...

22

Nested Properties Example: nested-properties.jsp (.faces)

23

... Using Nested Bean Properties Employee's first name: Employee's last name: Name of employee's company: Business area of employee's company:

Nested Properties Example: Result

24

© 2012 Marty Hall

Submitting Bean Properties Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. 25

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

Three Meanings of #{...} • Designating output value – #{varName.propertyName} means to output the given property of the given scoped variable or managed bean – • Anytime accessed, means to output text



• When form initially displayed, means to prepopulate field

• Designating submitted value



• When form submitted, designates where value stored

• Designating method call after submission – • When form submitted, designates action handler

26

JSP 2.0 and Struts Equivalents • Designating output value – • Similar to ${employee.address}, but scoped vars only • Similar to but scoped vars only

– • Similar to JSP 2.0 • Similar to html:text in Struts

• Designating submitted value – No JSP 2.0 equivalent – Similar to html:text in Struts

• Designating method call after submission 27

– No JSP 2.0 or Struts equivalent

Submitting Properties Example: EmployeeBean package coreservlets; public class EmployeeBean { private NameBean name; private CompanyBean company; ...

}

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

28

Nested Properties Example: faces-config.xml

29

... employee coreservlets.EmployeeBean request ... /submitting-properties.jsp accept /WEB-INF/results/accept.jsp reject /WEB-INF/results/reject.jsp

Submitting Properties Example: submitting-properties.jsp (.faces) ... Your first name: Your last name: Name of your company: Business area of your company: 30

Submitting Properties Example: Input Page Result

31

Submitting Properties Example: accept.jsp (JSF-Only Version)

32

... Employee Accepted Employee's first name: Employee's last name: Name of employee's company: Business area of employee's company: Congratulations.

Submitting Properties Example: accept.jsp (JSP 2.0 Version) ... Employee Accepted Employee's first name: ${employee.name.firstName} Employee's last name: ${employee.name.lastName} Name of employee's company: ${employee.company.companyName} Business area of employee's company: ${employee.company.business} Congratulations.

33

Submitting Properties Example: reject.jsp (JSF-Only Version)

34

... Employee Rejected Employee's first name: Employee's last name: Name of employee's company: Business area of employee's company: Congratulations.

Submitting Properties Example: reject.jsp (JSP 2.0 Version) ... Employee Rejected Employee's first name: ${employee.name.firstName} Employee's last name: ${employee.name.lastName} Name of employee's company: ${employee.company.companyName} Business area of employee's company: ${employee.company.business} Congratulations.

35

Submitting Properties Example: Results

36

Submitting Properties Example: Results (Continued)

37

© 2012 Marty Hall

Accessing Collections Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. 38

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

Equivalence of Dot and Array Notations • Equivalent forms – #{name.property} – #{name["property"]}

• Reasons for using array notation – To access arrays, lists, and other collections • See upcoming slides

– To calculate the property name at request time. • #{name1[name2]}

(no quotes around name2)

– To use names that are illegal as Java variable names • #{foo["bar-baz"]} • #{foo["bar.baz"]}

39

Accessing Collections • #{attributeName[entryName]} • Works for – Array. Equivalent to • theArray[index] (getting and setting)

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

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

• Equivalent forms (for HashMap) – #{stateCapitals["maryland"]} – #{stateCapitals.maryland} – But the following is illegal since 2 is not a legal var name 40

• #{listVar.2}

Collections Example: PurchaseBean public class PurchaseBean { private String[] cheapItems = { "Gum", "Yo-yo", "Pencil" }; private List mediumItems = new ArrayList(); private Map valuableItems = new HashMap(); private boolean isEverythingOK = true; public PurchaseBean() { mediumItems.add("iPod"); mediumItems.add("GameBoy"); mediumItems.add("Cell Phone"); valuableItems.put("low", "Lamborghini"); valuableItems.put("medium", "Yacht"); valuableItems.put("high", "Chalet"); }

41

public String[] getCheapItems() { return(cheapItems); } public List getMediumItems() { return(mediumItems); } public Map getValuableItems() { return(valuableItems); }

Collections Example: PurchaseBean (Continued) 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 { public static boolean doBusinessLogic (PurchaseBean bean) { // Business logic omitted return(Math.random() > 0.1); } public static boolean doDataAccessLogic (PurchaseBean bean) { // Database access omitted return(Math.random() > 0.1); } }

43

Collections Example: faces-config.xml

44

... purchases coreservlets.PurchaseBean request ... /using-collections.jsp success /WEB-INF/results/success.jsp failure /WEB-INF/results/failure.jsp

Collections Example: using-collections.jsp (.faces)

45

... Cheap Items Medium Items

Collections Example: using-collections.jsp (.faces)–Cont. Valuable Items Low: Medium: High: ...

• Important note 46

– Since I am using double quotes around the hash table key, I have to use single quotes around the entire JSF expression

Collections Example: Input Page Result

47

Submitting Properties Example: success.jsp (JSF-Only Version) ... Cheap Items Medium Items ... 48

Submitting Properties Example: success.jsp (JSP 2.0 Version) ... Cheap Items ${purchases.cheapItems[0]} ${purchases.cheapItems[1]} ${purchases.cheapItems[2]} Medium Items ${purchases.mediumItems[0]} ${purchases.mediumItems[1]} ${purchases.mediumItems[2]} ...

49

Submitting Properties Example: Results

50

© 2012 Marty Hall

Implicit Objects and Operators Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. 51

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

JSF EL Has Almost the Same Predefined Variables as JSP 2 • facesContext. The FacesContext object. – E.g. #{facesContext.externalContext.session.id}

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

• header and headerValues. Request headers. – E.g. #{header.Accept} or #{header["Accept"]} – #{header["Accept-Encoding"]}

• cookie. Cookie object (not cookie value). – E.g. #{cookie.userCookie.value} or #{cookie["userCookie"].value}

• initParam. Context initialization param. • requestScope, sessionScope, applicationScope. – Instead of searching scopes.

• Problem

– Using implicit objects usually works poorly with MVC model 52

Example: Implicit Objects … test Request Parameter: ${param.test} User-Agent Header: ${header["User-Agent"]} JSESSIONID Cookie Value: ${cookie.JSESSIONID.value} Server: ${pageContext.servletContext.serverInfo} 53

Example: Implicit Objects (Result)

54

Expression Language Operators • Arithmetic – + - * / div % mod

• Relational – == eq != ne < lt > gt = ge

• Logical – && and || or ! Not

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

• CAUTION – Use extremely sparingly to preserve MVC model 55

Example: Operators … Arithmetic Operators Relational Operators ExpressionResultExpressionResult \${3+2-1}${3+2-1} \${1<2}${1
View more...

Comments

Copyright � 2017 SILO Inc.