Object persistence and EL
Agenda
• Persisting Object in Request, Session, Application Scope in
Servlet
• Understanding the implementation of EL
Introduction to EL
• EL was first introduced in JSTL 1.0
• EL is now incorporated in JSP 2.0
• Pattern that identifies expression language is ${}
• To deactivate the evaluation of EL specify the isELIgnore
attribute of page directive to true
Operators in EL
Operator Description
. Access abean property orMap entry.
[] Access an array orList element.
() Grouping of asubexpression forevaluation order.
? : Conditional test: condition ? ifTrue : ifFalse.
+ Addition.
- Subtraction.
* Multiplication.
/or div Division.
% or mod Modulo (remainder).
Operators in EL
Operator Description
== or eq equality.
!= or ne inequality.
< or lt less than.
> or gt greater than.
<= or le less than or equal.
>= or ge greater than or equal.
&& or and logical AND.
|| or or logical OR.
! or not Unary Boolean complement.
empty Test for null,empty String,array or Collection.
func(args) A function call.
Accessing Scoped Variable
• ${varName}
- Means to search the PageContext, the HttpServletRequest, the
HttpSession, and the ServletContext, in that order, and output
the object with that attribute name.
- PageContext does not apply with MVC.
• Equivalent forms
- ${name}
- <%= pageContext.findAttribute("name") %>
- <jsp:useBean id="name” type="somePackage.SomeClass”
scope="...“>
<%= name %>
Accessing Bean properties
• ${varName.propertyName}
- Means to find scoped variable of given name and output the
specified bean property
• Equivalent forms
- ${customer.firstName}
<%@ page import=“model.NameBean" %>
<% NameBean person =
(NameBean)pageContext.findAttribute("customer");
%>
<%= person.getFirstName() %>
Accessing Bean properties
• Equivalent forms
- ${customer.firstName}
- <jsp:useBean id="customer”
type="coreservlets.NameBean”
scope="request, session, or application" />
<jsp:getProperty name="customer” property="firstName" />
• This is better than script on previous slide.
- But, requires you to know the scope
- And fails for subproperties.
• No non-Java equivalent to ${customer.address.zipCode}
Accessing persisted value
• Scope Examples
• Accessing a page-scoped attribute named as firstName:
${pageScope.firstName}
• Accessing a request-scoped attribute named as firstName:
${requestScope.firstName}
• Accessing a session-scoped attribute named as 'lastName' (null if not
found): ${sessionScope.lastName}
• Page Context Examples
• ${pageContext.request.protocol} $
• {pageContext.response.locale}
• ${pageContext.session.id} ${pageContext.servletContext} Above we are
accessing request, response, session, and application properties, using the
pageContext implicit object.
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"]}
Accessing Collections
• ${attributeName[entryName]}
Works for
- Array. Equivalent to theArray[index]
- List. Equivalent to theList.get(index)
- Map. Equivalent to theMap.get(keyName)
• Equivalent forms (for HashMap)
- ${stateCapitals["maryland"]}
- ${stateCapitals.maryland}
• But the following is illegal since 2 is not a legal var name
- ${listVar.2}
Reading Cookie using EL
• Cookie Example
• addCookies.java Cookie c=new Cookie("name","test");
• res.addCookie(c);
• Test.jsp
• Name : ${cookie["name"]}
• Value : ${cookie["name"].value}
• Here in addCookies.java we are creating a new Cookie,These values
can be retrieved in jsp by using ${cookie.xxxx}.
Using EL in custom tags
• EL expressions can be used:
- In static text
- In any standard or custom tag attribute that can accept
an expression
• The value of an expression in static text is computed and inserted into
the current output. If the static text appears in a tag body, note that an
expression will not be evaluated if the body is declared to be
tagdependent
Using EL in custom tags
• There are three ways to set a tag attribute value:
- With a single expression construct:
- <some:tag value="${expr}"/>
- The expression is evaluated and the result is coerced to the attribute's expected
type.
• With one or more expressions separated or surrounded by text:
- <some:tag value="some${expr}${expr}text${expr}"/>
- The expressions are evaluated from left to right. Each expression is coerced to a
String and then concatenated with any intervening text. The resulting String is then
coerced to the attribute's expected type.
• With text only:
- <some:tag value="sometext"/>
- In this case, the attribute's String value is coerced to the attribute's expected type.
Advantages of Expression language
• Concise access to stored objects.
- To output a “scoped variable” (object stored with setAttribute in the
PageContext, HttpServletRequest, HttpSession, or ServletContext) named
saleItem, you use ${saleItem}.
• Shorthand notation for bean properties.
- To output the companyName property (i.e., result of the getCompanyName
method) of a scoped variable named company, you use
${company.companyName}. To access the firstName property of the president
property of a scoped variable named company, you use
${company.president.firstName}.
• Simple access to collection elements.
- To access 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 s interchangeable with
the bracket notation for collections.
Advantages of Expression language
• Succinct access to request parameters, cookies, and other request data.
- To access the standard types of request data, you can use one ofseveral
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.
Summary
• The JSP 2.0 EL provides concise, easy to read access to
- Bean properties
- Collection elements
- Standard HTTP elements such as request
parameters,request headers, and cookies
• The JSP 2.0 EL works best with MVC
- Use only to output values created by separate Java
code
• Resist use of EL for business logic

Advance java session 14

  • 1.
  • 2.
    Agenda • Persisting Objectin Request, Session, Application Scope in Servlet • Understanding the implementation of EL
  • 3.
    Introduction to EL •EL was first introduced in JSTL 1.0 • EL is now incorporated in JSP 2.0 • Pattern that identifies expression language is ${} • To deactivate the evaluation of EL specify the isELIgnore attribute of page directive to true
  • 4.
    Operators in EL OperatorDescription . Access abean property orMap entry. [] Access an array orList element. () Grouping of asubexpression forevaluation order. ? : Conditional test: condition ? ifTrue : ifFalse. + Addition. - Subtraction. * Multiplication. /or div Division. % or mod Modulo (remainder).
  • 5.
    Operators in EL OperatorDescription == or eq equality. != or ne inequality. < or lt less than. > or gt greater than. <= or le less than or equal. >= or ge greater than or equal. && or and logical AND. || or or logical OR. ! or not Unary Boolean complement. empty Test for null,empty String,array or Collection. func(args) A function call.
  • 6.
    Accessing Scoped Variable •${varName} - Means to search the PageContext, the HttpServletRequest, the HttpSession, and the ServletContext, in that order, and output the object with that attribute name. - PageContext does not apply with MVC. • Equivalent forms - ${name} - <%= pageContext.findAttribute("name") %> - <jsp:useBean id="name” type="somePackage.SomeClass” scope="...“> <%= name %>
  • 7.
    Accessing Bean properties •${varName.propertyName} - Means to find scoped variable of given name and output the specified bean property • Equivalent forms - ${customer.firstName} <%@ page import=“model.NameBean" %> <% NameBean person = (NameBean)pageContext.findAttribute("customer"); %> <%= person.getFirstName() %>
  • 8.
    Accessing Bean properties •Equivalent forms - ${customer.firstName} - <jsp:useBean id="customer” type="coreservlets.NameBean” scope="request, session, or application" /> <jsp:getProperty name="customer” property="firstName" /> • This is better than script on previous slide. - But, requires you to know the scope - And fails for subproperties. • No non-Java equivalent to ${customer.address.zipCode}
  • 9.
    Accessing persisted value •Scope Examples • Accessing a page-scoped attribute named as firstName: ${pageScope.firstName} • Accessing a request-scoped attribute named as firstName: ${requestScope.firstName} • Accessing a session-scoped attribute named as 'lastName' (null if not found): ${sessionScope.lastName} • Page Context Examples • ${pageContext.request.protocol} $ • {pageContext.response.locale} • ${pageContext.session.id} ${pageContext.servletContext} Above we are accessing request, response, session, and application properties, using the pageContext implicit object.
  • 10.
    Dot and arrayNotations 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"]}
  • 11.
    Accessing Collections • ${attributeName[entryName]} Worksfor - Array. Equivalent to theArray[index] - List. Equivalent to theList.get(index) - Map. Equivalent to theMap.get(keyName) • Equivalent forms (for HashMap) - ${stateCapitals["maryland"]} - ${stateCapitals.maryland} • But the following is illegal since 2 is not a legal var name - ${listVar.2}
  • 12.
    Reading Cookie usingEL • Cookie Example • addCookies.java Cookie c=new Cookie("name","test"); • res.addCookie(c); • Test.jsp • Name : ${cookie["name"]} • Value : ${cookie["name"].value} • Here in addCookies.java we are creating a new Cookie,These values can be retrieved in jsp by using ${cookie.xxxx}.
  • 13.
    Using EL incustom tags • EL expressions can be used: - In static text - In any standard or custom tag attribute that can accept an expression • The value of an expression in static text is computed and inserted into the current output. If the static text appears in a tag body, note that an expression will not be evaluated if the body is declared to be tagdependent
  • 14.
    Using EL incustom tags • There are three ways to set a tag attribute value: - With a single expression construct: - <some:tag value="${expr}"/> - The expression is evaluated and the result is coerced to the attribute's expected type. • With one or more expressions separated or surrounded by text: - <some:tag value="some${expr}${expr}text${expr}"/> - The expressions are evaluated from left to right. Each expression is coerced to a String and then concatenated with any intervening text. The resulting String is then coerced to the attribute's expected type. • With text only: - <some:tag value="sometext"/> - In this case, the attribute's String value is coerced to the attribute's expected type.
  • 15.
    Advantages of Expressionlanguage • Concise access to stored objects. - To output a “scoped variable” (object stored with setAttribute in the PageContext, HttpServletRequest, HttpSession, or ServletContext) named saleItem, you use ${saleItem}. • Shorthand notation for bean properties. - To output the companyName property (i.e., result of the getCompanyName method) of a scoped variable named company, you use ${company.companyName}. To access the firstName property of the president property of a scoped variable named company, you use ${company.president.firstName}. • Simple access to collection elements. - To access 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 s interchangeable with the bracket notation for collections.
  • 16.
    Advantages of Expressionlanguage • Succinct access to request parameters, cookies, and other request data. - To access the standard types of request data, you can use one ofseveral 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.
  • 17.
    Summary • The JSP2.0 EL provides concise, easy to read access to - Bean properties - Collection elements - Standard HTTP elements such as request parameters,request headers, and cookies • The JSP 2.0 EL works best with MVC - Use only to output values created by separate Java code • Resist use of EL for business logic